Basic Information
Futures UDST-M API
Using the Futures UDST-M API to develop applications, you can accurately obtain market data of the Bibox spot market and conduct automated transactions quickly. The Futures UDST-M API contains many interfaces, which are roughly divided into the following groups according to their functions:
- Market Data Endpoints REST interface for obtaining market data
- User Data Endpoints REST interface for obtaining user private data
- Market Data Streams WebSocket interface for obtaining market data
- User Data Streams WebSocket interface for obtaining user private data
Futures UDST-M API usage is as followsBase URL:
- Market Data Endpoints: https://api.bibox.com/api
- User Data Endpoints: https://api.bibox.com/api
- Market Data Stream: wss://market-wss.bibox360.com/cbu
- User Data Stream: wss://user-wss.bibox360.com/cbu
List of alternate API domains
https://api.bibox.tel/v1/public/queryApiDomain
The REST interface of the Futures UDST-M API uses the following HTTP methods:
- GET Used to get market data or private data
- POST Used to submit orders and other operations
- DELETE Used to revoke orders and other operations
Parameters required by the REST interface of the Futures UDST-M API should be appended to the request according to the following rules:
- Interface parameters of type GET should be appended to the Query String
- The interface parameters of the POST type should be appended to the Request Body in JSON format
- Interface parameters of type DELETE should be appended to Request Body in JSON format
Response
The response data of the Futures UDST-M API is returned in JSON format. For the specific format, please refer to the description of each interface.
Error
Errors from the Futures UDST-M API are returned in the following JSON format:
{
"error": error code,
"message": "error message"
}
Among them, error indicates the type of error, and message contains the cause of the error or a hint on how to avoid the error. For specific error types, please refer to the Error chapter.
Time or Timestamp
The time values involved in the interface parameters and response data of the Futures UDST-M API are all UNIX time in milliseconds.
Traffic Restrictions
Bibox imposes the following access restrictions on requests from the same IP:
- Access Limits
- Usage Limits CPU usage limit
- Access Limits Access frequency limit
- The same IP has a maximum of 10000 requests every 10 seconds, and requests that exceed the limit will receive a -2101 error.
- The user can send up to 10,000 requests at any frequency within 10 seconds as needed, either roughly every 10ms, or 10,000 consecutive times within 1 second, then wait 9 seconds.
- Usage Limits
- The same IP consumes up to 10,000 CPU points every 10 seconds, and requests that exceed the limit will receive a -2102 error.
- Different APIs consume different CPU time, depending on how the API accesses the data.
- In this article, the way each API interface accesses data will be indicated in the form of "cache" and "database". API that accesses the cache consumes less CPU time, and API that accesses the database consumes more CPU time. Depending on the parameters sent by the user, the API may access the cache and database in a mix, or even access the database multiple times, which will increase the CPU time consumed by the API.
- The CPU time consumed by each API request will be included in the response header Bibox-Usage in the format t1:t2:t3, where t1 represents the CPU time consumed by this API request, and t2 represents the current IP consumption in the last 10 seconds CPU time, t3 represents the remaining available CPU time of the current IP in the last 10 seconds.
Authentication
Example
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const expireTime = Date.now() + 20000;
const queryStr = 'asset=USDT';
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString(); // POST or DELETE replace queryStr with bodyStr
const url = `${endpoints}/v4/cbu/userdata/accounts?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/accounts'
expireTime = int(time.time()) * 1000 + 20000
query_str = 'asset=USDT'
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/accounts";
string query_str = "asset=USDT";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Authentication
- The private interface is used to access private information such as accounts and delegations. Additional signatures are required when requesting to satisfy Bibox for authentication. This section describes how to create a signature.
Generate Api Key
- To create a signature, you first need to generate a combination of Api Key and Secret Key. Please keep in mind the Secret Key generated during this process, as this value is only displayed once, if you forget the Secret Key, delete the Api Key and generate a new Api Key and Secret Key combination.
HTTP request headers
Requests to access private interfaces must append the following HTTP request headers:
- Bibox-Api-Key generated Api Key
- Bibox-Api-Sign signature
The following HTTP request headers can also be appended if desired:
- Bibox-Expire-Time
- Interface expiration time.
- The value is Unix time in milliseconds. The server will ignore requests received after this time. This is mainly used to avoid the impact of network delays.
- The expiration time is limited to the next 60 seconds.
Create signature
Before sending the request, first determine the message body for signing. For GET type requests, the expiration time plus Query String is the message body that needs to be signed (expireTime: queryString). For POST and DELETE type requests, the expiration time plus Body String is the message body that needs to be signed (expireTime: bodyString). The specific method of signing is as follows:
- Step 1: Use the Secret Key as the key to execute the HmacSHA256 algorithm on the message body that needs to be signed
- Step 2: Convert the above result to Hex String
- Step 3: Use Hex String as the value of the request header Bibox-Api-Sign
Api Key permissions
*Private interfaces require specific permissions to execute. Appropriate permissions can be granted to the Api Key. If the Api Key is not granted the permissions required by an interface, then requests submitted using that Api Key will be rejected. *
The following permissions can be granted to Api Key:
- View permission allows Api Key to get private data.
- Trade permission allows Api Key to submit or revoke delegation, and allows Api Key to obtain transaction-related data.
*The permissions required by the interface will be given in the description of each interface. *
Market Data Endpoints
Get Timestamp
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/timestamp`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/timestamp'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/timestamp";
string url = endpoints + path;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
{
"time":"1653618929241"
}
Get server time
- Request method GET
- Request path /v4/cbu/marketdata/timestamp
- Data source
Cache
Get Listed Pairs
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/pairs?symbol=4BTC_USDT`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/pairs?symbol=4BTC_USDT'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/pairs";
string query_str = "symbol=4BTC_USDT";
string url = endpoints + path + "?" + query_str;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
"symbol":"4BTC_USDT", trading pair name
"base":"BTC",
"quote":"USDT", the quote currency
"price_scale":1, price decimal places
"quantity_min": 0.001, the minimum order quantity (coin)
"quantity_max": 100, the maximum order quantity (coin)
"quantity_increment": 0.001, order increment (coin)
}
]
Get a list of currencies
- Request method GET
- Request path /v4/cbu/marketdata/pairs
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | No | Trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. Multiple trading pair codes can be specified as follows /pairs?symbol=4BTC_USDT,4ETH_USDT If not specified symbol parameter, it returns the information of all trading pairs |
- Data source
Cache
Get Order Book
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/order_book?symbol=4BTC_USDT`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/order_book?symbol=4BTC_USDT'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/order_book";
string query_str = "symbol=4BTC_USDT";
string url = endpoints + path + "?" + query_str;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
{
"i":update id,
"t":update time,
"b":[ buy order
[
commission price,
commission amount
]
],
"a":[ Sell order
[
commission price,
commission amount
]
]
}
Get depth data
- Request method GET
- Request path /v4/cbu/marketdata/order_book
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | yes | trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. |
level | int32 | no | Specifies the maximum level depth to return Valid values 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000 Default value 100 |
price_scale | integer | No | Specify the depth of consolidation by price. For example, the price of the specified trading pair has a maximum of 4 decimal places. price_scale=0, the price returned includes a maximum of 4 decimal places, and price_scale=1. The price contains up to 3 decimal places, and the order quantity is the sum of all orders in the price range of 0.0010 The price returned when price_scale=2 contains up to 2 decimal places, and the order volume is the sum of all orders in the price range of 0.0100 When price_scale=3, the price returned contains at most 1 decimal place, and the order quantity is the sum of all orders in the price range of 0.1000. The price returned when price_scale=4 contains at most 0 decimal places, and the order volume is the price range Sum of all orders in 1.0000 Valid values 0, 1, 2, 3, 4, 5 Default value 0 |
Note: The data is sorted according to the best price, that is, the depth of the buy side is sorted by price from large to small, and the depth of the sell side is sorted by price from small to large
- Data source
Cache
Get Candles
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/candles?symbol=4BTC_USDT&time_frame=1m`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/candles?symbol=4BTC_USDT&time_frame=1m'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/candles";
string query_str = "symbol=4BTC_USDT&time_frame=1m";
string url = endpoints + path + "?" + query_str;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
[
time,
open,
high,
low,
close,
volume,
amount,
first trade id,
trade count,
]
...
]
Get K-line data
- Request method GET
- Request path /v4/cbu/marketdata/candles
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | yes | trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. |
time_frame | string | Yes | K-line data time frame Valid values 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 3d, 1W or 1M |
before | int64 | No | utc time limited to return the latest time of the K-line record |
after | int64 | No | utc time limited to return the earliest time of the K-line record |
limit | integer | No | Get the maximum number of K-line records The default value is 100, and the maximum value is 1000 |
- Parameter combinations and data sources supported by this interface
- symbol + time_frame --> cache
- symbol + time_frame + limit --> cache
- symbol + time_frame + before --> database
- symbol + time_frame + before + limit --> database
- symbol + time_frame + after --> database
- symbol + time_frame + after + limit --> database
The returned results are sorted by time from earliest to latest
Get TagPrices
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/tagPrices?symbol=4BTC_USDT&time_frame=1m`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/tagPrices?symbol=4BTC_USDT&time_frame=1m'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/tagPrices";
string query_str = "symbol=4BTC_USDT&time_frame=1m";
string url = endpoints + path + "?" + query_str;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
[
time,
open,
high,
low,
close,
volume,
amount,
first trade id,
trade count,
]
...
]
Get Tag Price Data
- Request method GET
- Request path /v4/cbu/marketdata/tagPrices
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | yes | trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. |
time_frame | string | Yes | K-line data time frame Valid values 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 3d, 1W or 1M |
before | int64 | No | utc time limited to return the latest time of the K-line record |
after | int64 | No | utc time limited to return the earliest time of the K-line record |
limit | integer | No | Get the maximum number of K-line records The default value is 100, and the maximum value is 1000 |
- Parameter combinations and data sources supported by this interface
- symbol + time_frame --> cache
- symbol + time_frame + limit --> cache
- symbol + time_frame + before --> database
- symbol + time_frame + before + limit --> database
- symbol + time_frame + after --> database
- symbol + time_frame + after + limit --> database
The returned results are sorted by time from earliest to latest
Get Indices
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/indices?symbol=4BTC_USDT&time_frame=1m`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/indices?symbol=4BTC_USDT&time_frame=1m'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/indices";
string query_str = "symbol=4BTC_USDT&time_frame=1m";
string url = endpoints + path + "?" + query_str;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
[
time,
open,
high,
low,
close,
volume,
amount,
first trade id,
trade count,
]
...
]
Get index price data
- Request method GET
- Request path /v4/cbu/marketdata/indices
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | yes | trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. |
time_frame | string | Yes | K-line data time frame Valid values 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 3d, 1W or 1M |
before | int64 | No | utc time limited to return the latest time of the K-line record |
after | int64 | No | utc time limited to return the earliest time of the K-line record |
limit | integer | No | Get the maximum number of K-line records The default value is 100, the maximum value is 1000 |
- Parameter combinations and data sources supported by this interface
- symbol + time_frame --> cache
- symbol + time_frame + limit --> cache
- symbol + time_frame + before --> database
- symbol + time_frame + before + limit --> database
- symbol + time_frame + after --> database
- symbol + time_frame + after + limit --> database
The returned results are sorted by time from earliest to latest
Get Trades
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/trades?symbol=4BTC_USDT`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/trades?symbol=4BTC_USDT'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/trades";
string query_str = "symbol=4BTC_USDT";
string url = endpoints + path + "?" + query_str;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
"i":"128851",trade id
"p":"30479.2",transaction price
"q":"0.04",Volume
"s":"buy", transaction direction
"t":"1652434793000",trading time
}
...
]
Get transaction records
- Request method GET
- Request path /v4/cbu/marketdata/trades
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | yes | trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. |
start_time | int64 | no | limit the earliest time to return transaction records |
end_time | int64 | no | limit the latest time to return transaction records |
before | int64 | no | transaction id limited to return the maximum id of transaction records |
after | int64 | no | transaction id limited to return the maximum id of transaction records |
limit | integer | no | get the maximum number of records default 100, maximum 1000 |
- Parameter combinations and data sources supported by this interface
- symbol --> cache
- symbol + limit --> cache
- symbol + start_time --> database
- symbol + start_time + limit --> database
- symbol + end_time --> database
- symbol + end_time + limit --> database
- symbol + start_time + end_time --> database
- symbol + start_time + end_time + limit --> database
- symbol + before --> database
- symbol + before + limit --> database
- symbol + after --> database
- symbol + after + limit --> database
The parameter combination whose data source is cache is used to get the last 1000 transaction records
The parameter combination whose data source is database is used to obtain earlier transaction records
If the latest transaction record is obtained with the parameter combination whose data source is database, the result will be slightly delayed than the cache data source * Usage Usage example: Get all transaction records of a trading pair within three months
- First use the symbol + limit parameter combination to get the latest transaction record
- Use the trade id of the first record obtained as the value of the before parameter, and repeatedly use the symbol + before + limit parameter combination to obtain more records, until all transaction records within three months are obtained and then stop
The returned results are sorted by transaction record id from small to large
Get Tickers
Request
let request = require("request");
const endPoint = 'https://api.bibox.com/api';
const url = `${endPoint}/v4/cbu/marketdata/ticker?symbol=4BTC_USDT`
request.get(url,
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body)
});
import requests
END_POINT = 'https://api.bibox.com/api';
def do_request():
path = '/v4/cbu/marketdata/ticker?symbol=4BTC_USDT'
resp = requests.get(END_POINT + path)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
namespace ConsoleProgram
{
public class Class1
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/marketdata/ticker";
string query_str = "symbol=4BTC_USDT";
string url = endpoints + path + "?" + query_str;
string responseBody = await client.GetStringAsync(url);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
"s":"4BTC_USDT", trading pair name
"o": 31366.2, 24-hour opening price
"h": 32117.7, the highest price in 24 hours
"l": 32117.7, the lowest price in 24 hours
"p": 27650.5, latest price
"q": 0.075, the last transaction quantity
"v": 2239.385, volume
"a":66224658.4286,Transaction value
"c":-0.1184, up or down
"t":57394,Number of transactions
"f": 63958, starting trade id
"bp": 27643.4, buy one price
"bq": 0.089, buy one quantity
"ap": 27645.5, sell one price
"aq": 0.01, sell a quantity
}
]
Get Ticker Data
- Request method GET
- Request path /v4/cbu/marketdata/ticker
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | Yes | Trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. Multiple trading pair codes can be specified as follows /pairs?symbol=4BTC_USDT,4ETH_USDT |
- Data Source
Cache
Market Data Streams
Overview
Example
const WebSocket = require('ws');
const biboxws = 'wss://market-wss.bibox360.com/cbu';
let wsClass = function () {
};
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({
"id": 123,
"method": "SUBSCRIBE",
"params": [
"4BTC_USDT.order_book.1",
]
}));
setInterval(function () {
ws.ping(Date.now())
},30000)
});
ws.on('close', data => {
console.log('close, ', data);
});
ws.on('error', data => {
console.log('error', data);
});
ws.on('ping', data => {
console.log('ping ', data.toString('utf8'));
});
ws.on('pong', data => {
console.log('pong ', data.toString('utf8'));
});
ws.on('message', data => {
console.log("rece message")
console.log(data)
});
};
let instance = new wsClass();
instance._initWs().catch(err => {
console.log(err);
});
import websocket
import json
ws_url = 'wss://market-wss.bibox360.com/cbu'
def stringify(obj):
return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")
def get_sub_str():
subdata = {
"id": 123,
"method": "SUBSCRIBE",
"params": [
"4BTC_USDT.order_book.1",
]
}
return stringify(subdata)
def on_message(ws, message):
print(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;
using Newtonsoft.Json.Linq;
namespace Example
{
public class Program
{
public static void Main (string[] args)
{
string wsuri = "wss://market-wss.bibox360.com/cbu";
var jarray = new JArray();
jarray.Add("4BTC_USDT.order_book.1");
JObject val = new JObject {
{"id", 123 },
{"method", "SUBSCRIBE" },
{"params", jarray }
};
string payload = JsonConvert.SerializeObject(val);
using (var ws = new WebSocket (wsuri)) {
ws.OnMessage += (sender, e) => {
Console.WriteLine ("recv: " + e.Data);
};
ws.Connect ();
ws.Send (payload);
ConsoleKey key;
do
{
key=Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}
}
*Using Websocket push service can get market information in time. *
- Connect to Websocket server
Please use the following URL to connect to the Websocket server:
wss://market-wss.bibox360.com/cbu
After connecting, the client can send the following JSON-formatted request to the server
{
"id": 123, // request id given by client
"method": "..." // request type
"params": [ // request parameter list
"...",
"...",
...
]
}
After receiving the request, the server will send the following response in JSON format to the client
{
"id": 123, // request id
"result": "..." // the request result, "result":null also means the subscription is successful
}
If an error occurs, the server will send the following error message to the client
{
"id": 123, // request id
"error": -1000, // error code
"message": "..." // error description
}
At the same time, the server will also send the following data stream in JSON format to the client, the data stream contains the change information of the market
{
"stream": "4BTC_USDT.trades", // data stream name
"data": ..., // data
}
request: subscribe to data stream
{
"id": 1,
"method": "SUBSCRIBE",
"params": [
"stream name",
"stream name",
...
]
}
After connecting, please send the request to the server first, and then the server will send the corresponding data stream to the client when the market price changes.
"data stream name" is the data stream name, which is a string in the following format. symbol.data_type.param1.param2...
Among them, symbol is the name of the trading pair, such as 4BTC_USDT, 4ETH_USDT, etc. data_type is the data type, currently only the following data types are supported order_book: depth trades: list of trades candles: candlesticks ticker: latest transaction information indices: index price K line tagPrices: mark the price K line
After data_type is the parameter list, different data types have different parameter lists, which will be introduced later
request: unsubscribe stream
{
"id": 1,
"method": "UNSUBSCRIBE",
"params": [
"data stream name",
"data stream name",
...
]
}
If the request is handled correctly by the server, the client will receive the following response:
{
"id":123,
"result":null
}
If the request fails, the client will receive the following error response:
{
"id": 123, // request id
"error": -1000, // error code
"message": "..." // error description
}
Request Methods
Request type and parameters
The client can send the following request to the server
{
"id": 123, // request id given by client
"method": "..." // request type
"params": [ // request parameter list
"...",
"...",
...
]
}
- where the value of the method field is one of the following request types:
optional value | Description |
---|---|
SUBSCRIBE | 1. Subscribe to the data stream 2. The parameter is a list of data stream names 3. After successful subscription, the server will send the data stream to the client when the market price changes |
UNSUBSCRIBE | 1. Unsubscribe data stream 2. The parameter is a list of data stream names 3. After successfully unsubscribing, the client will no longer receive the corresponding data stream |
Subscribe Order Book
Subscribe in-depth information
Send the following request to subscribe to in-depth information
{
"id": 123,
"method": "SUBSCRIBE",
"params": [
"4BTC_USDT.order_book.1",
"4ETH_USDT.order_book.1",
...
]
}
- parameter
- The parameter of the request is the depth stream name, in the following format:
- <symbol>.order_book.<max depth>
- <symbol> is the name of the trading pair, such as 4BTC_USDT, 4ETH_USDT, etc.
- <max depth> is the maximum depth, valid values are 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000
Data flow
// If the subscription is successful, the following data stream will be returned
{
"id":123,
"result":null
}
// After that, the following data stream will be returned
{
"stream":"4APE_USDT.order_book.1",
"data":{
"i":"13890055",update id
"t":"1654826751000",time
"b":[ buy order
[
price,
quantity
],
[
"5.645",
"103"
]
],
"a":[ Sell order
[
"5.646",
"902"
],
[
"5.647",
"0"
]
]
}
}
After successful subscription, the client will first receive a full depth data stream, and then will receive an incremental change data stream, please use the following method to synthesize the full depth. The number is 0, which means that the depth is deleted. If the price is the same, the quantity will be replaced directly.
Subscribe Trades
Subscribe to Trades List
Send the following request to subscribe to the transaction list
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.trades",
"4ETH_USDT.trades",
...
]
}
- parameter
- The parameter of the request is the name of the transaction flow, in the following format:
- <symbol>.trades
- <symbol> is the name of the trading pair, such as 4BTC_USDT, 4ETH_USDT, etc.
Data flow
// If the subscription is successful, the following data stream will be returned
{
"id":123,
"result":null
}
// After that, the following data stream will be returned
{
"stream":"4BTC_USDT.trades",
"data":[
{
"i":"128851",trade id
"p":"30479.2",transaction price
"q":"0.04",Volume
"s":"buy", transaction direction
"t":"1652434793000",trading time
}
]
}
Subscribe Candles
Subscribe to K line
Send the following request to subscribe to K-line
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.candles.1m",
"4ETH_USDT.candles.1h",
...
]
}
- parameter
- The K-line flow name format is as follows:
- <symbol>.candles.<time_frame>
- <symbol> is the name of the trading pair, such as 4BTC_USDT, 4ETH_USDT, etc.
- <time_frame> is the K-line period, the valid values are 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 1w, 1M
Data flow
// If the subscription is successful, the following data stream will be returned
{
"id":123,
"result":null
}
// After that, the following data stream will be returned
{
"stream":"4BTC_USDT.candles.1m", // data category
"data":{
"t":60000,
"e":[
[
time,
open,
high,
low,
close,
volume,
amount,
first trade id,
trade count,
]
...
]
}
}
Subscribe Tickers
Subscribe to Tickers
Send the following request to subscribe to Ticker
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.ticker",
"4ETH_USDT.ticker",
...
]
}
- parameter
- The format of the Ticker stream name is as follows:
- <symbol>.ticker
- <symbol> is the name of the trading pair, such as 4BTC_USDT, 4ETH_USDT, etc.
Data flow
// If the subscription is successful, the following data stream will be returned
{
"id":123,
"result":null
}
// After that, the following data stream will be returned
{
"stream":"4BTC_USDT.ticker",
"data":{
"s":"4BTC_USDT", trading pair name
"o": 31366.2, 24-hour opening price
"h": 32117.7, the highest price in 24 hours
"l": 32117.7, the lowest price in 24 hours
"p": 27650.5, latest price
"q": 0.075, the last transaction quantity
"v": 2239.385, volume
"a":66224658.4286,Transaction value
"c":-0.1184, up or down
"t":57394,Number of transactions
"f": 63958, starting trade id
"bp": 27643.4, buy one price
"bq": 0.089, buy one quantity
"ap": 27645.5, sell one price
"aq": 0.01, sell a quantity
}
}
Subscribe Indices
Subscribe to index K line
Send the following request to subscribe to the index K line
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.indices.1m",
"4ETH_USDT.indices.1h",
...
]
}
- parameter
- The format of the index K-line stream name is as follows:
- <symbol>.indices.<time_frame>
- <symbol> is the name of the trading pair, such as 4BTC_USDT, 4ETH_USDT, etc.
- <time_frame> is the K-line period, the valid values are 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 1w, 1M
Data flow
// If the subscription is successful, the following data stream will be returned
{
"id":123,
"result":null
}
// After that, the following data stream will be returned
{
"stream":"4BTC_USDT.indices.1m", // data category
"data":{
"t":60000,
"e":[
[
time,
open(ignore),
high(ignore),
low(ignore),
close,
volume(ignore),
amount(ignore),
firstTradeId(ignore),
tradeCount(ignore),
]
...
]
}
}
Subscribe Tag Prices
Subscribe to tag price K line
Send the following request to subscribe to the tag price candlestick
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.tagPrices.1m",
"4ETH_USDT.tagPrices.1h",
...
]
}
- parameter
- The name format of the mark price K-line stream is as follows:
- <symbol>.tagPrices.<time_frame>
- <symbol> is the name of the trading pair, such as 4BTC_USDT, 4ETH_USDT, etc.
- <time_frame> is the K-line period, the valid values are 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 1w, 1M
Data flow
// If the subscription is successful, the following data stream will be returned
{
"id":123,
"result":null
}
// After that, the following data stream will be returned
{
"stream":"4BTC_USDT.tagPrices.1m", // data category
"data":{
"t":60000,
"e":[
[
time,
open(ignore),
high(ignore),
low(ignore),
close,
volume(ignore),
amount(ignore),
firstTradeId(ignore),
tradeCount(ignore),
]
...
]
}
}
User Data Endpoints
Get Accounts
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'asset=USDT';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/accounts?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/accounts'
expireTime = int(time.time()) * 1000 + 20000
query_str = 'asset=USDT'
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/accounts";
string query_str = "asset=USDT";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
c: 'USDT', currency symbol
b: '8247.1187293513', account available balance
ff: '0', isolated pending order freeze
fc: '346.73844114', all pending orders are frozen
mf: '0', isolated margin
mc: '1396.55822362', full margin
}
]
Get the balance, freezing and other information of various assets in the account corresponding to the API Key
- Request method GET
- Request path /v4/cbu/userdata/accounts
- Permissions: View, Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
asset | string | No | Asset code, such as USDT, etc. Multiple asset codes can be specified in the following form /v4/cbu/userdata/accounts?asset=BTC,ETH If no asset is specified parameter, returns the information of all assets |
- Data Source
Cache
Get an account's ledger
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'asset=USDT&end_time=1651895799668&limit=10';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/ledger?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/ledger'
query_str = 'asset=USDT&end_time=1651895799668&limit=10'
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/ledger";
string query_str = "asset=USDT&end_time=1651895799668&limit=10";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
i: ledger id
s: currency symbol
p: trading pair
T: Bill Type, 1 Transfer,2 Trade,3 Fee,4 Fund fee, 5 Adjust fund fee, 6 Force sub hold, 7 Force clear hold, 8 ADL
a: change amount
b: balance
t: time
}
]
Get the bill of the account corresponding to the API Key, including all records of changing the account balance, such as fund transfer, transaction, fee collection, etc.
- Request method GET
- Request path /v4/cbu/userdata/ledger
- Permissions: View, Trade
- request parameters (should be sorted)
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
asset | string | No | Asset code, such as USDT, etc. Multiple asset codes can be specified in the following form /v4/cbu/userdata/ledger?asset=BTC,ETH If no asset is specified parameter, then return the billing records of all assets |
start_time | int64 | No | Limit the earliest time to return bill records |
end_time | int64 | no | limit the latest time to return bill records |
before | int64 | No | Billing record id Limited to return the maximum id value of the billing record |
after | int64 | No | Billing record id Limited to return the minimum id value of the billing record |
limit | int32 | No | Limit the maximum number of returned billing records default 100 |
start_time | int64 | No | Limit the earliest time to return bill records |
start_time | int64 | No | Limit the earliest time to return bill records |
- Data Source
DB
Create an order
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
'symbol': '4BTC_USDT',
'order_side': 1,
'order_type': 2,
'amount': '0.001',
'price': '20000'
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/order`;
request.post({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'symbol': '4BTC_USDT',
'order_side': 1,
'order_type': 2,
'amount': '0.001',
'price': '20000'
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/order'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.post(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/order";
var myobj = new {
symbol = "4BTC_USDT",
order_side = 1,
order_type = 2,
price = "20000",
amount = "0.001",
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpContent content = new StringContent(body_str, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, 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);
}
}
}
}
Response
{
i: order id
I: client order id
m: pair
T: order type (1 market price,2 limit price)
s: order side (1 open long,2 open short,3 close long,4 close short)
Q: Order quantity
P: order price
S: order status (1 pending,2 deal part,3 filled,4 cancelled with deal part,5 canceled,100 fail)
r: failure reason
M: failure description
E: The number of transactions
e: Average transaction price
C: Order Creation Time
U: order update time
V: update id
z: Order Freeze Assets
rm: maker fee rate
rt: taker fee rate
of: order source
pid: corresponding position id
ot: the order type that contains the take profit and stop loss order
f: handling fee
fb: '0',
fb0: deduct handling fee
n: number of transactions
F: [// Transaction details, only the latest 20 items are displayed
{
i: fill id
t: time
p: price
q: quantity
l: maker or taker
f: fee
fb: 0,
fb0: fee discount
}
]
}
Place order
- Request method POST
- Request path /v4/cbu/userdata/order
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | yes | trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. |
order_side | string | Yes | Order direction, valid values are 1 to open long, 2 to open short, 3 to close long, 4 to close short |
order_type | string | yes | order type, valid values 1 market order, 2 limit order |
client_oid | string | No | Order id, a string with a valid value of int64 integer, it is recommended to use the Unix timestamp when submitting the order |
amount | decimal | No | Delegated amount |
price | decimal | No | Order Limit |
Delegate object Up to 20 deals including the order If the order has more than 20 transactions, the object only contains the last 20 transactions, and other transactions can be obtained through the fills interface
Get an order
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'order_id=1118621391231';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/order?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/order'
query_str = 'order_id=14118828812271651'
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/order";
string query_str = "order_id=14118828812271651";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
{
i: order id
I: client order id
m: pair
T: order type (1 market price,2 limit price)
s: order side (1 open long,2 open short,3 close long,4 close short)
Q: Order quantity
P: order price
S: order status (1 pending,2 deal part,3 filled,4 cancelled with deal part,5 canceled,100 fail)
r: failure reason
M: failure description
E: The number of transactions
e: Average transaction price
C: Order Creation Time
U: order update time
V: update id
z: Order Freeze Assets
rm: maker fee rate
rt: taker fee rate
of: order source
pid: corresponding position id
ot: the order type that contains the take profit and stop loss order
f: handling fee
fb: '0',
fb0: deduct handling fee
n: number of transactions
}
Get the delegate with the specified id
- Request method GET
- Request path /v4/cbu/userdata/order
- Permissions: View, Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
order_id | string | Yes | Order id Order id can be assigned by the exchange, Can also be user-defined (use the client_order_id parameter when submitting the order). When using self When defining an id, you need to add a "c-" prefix before the id. For example: when submitting a delegation, a custom id "123" is used, and when obtaining a delegation, you need to use "c-123". |
Get Orders
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'limit=2&status=settled&symbol=4BTC_USDT';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/orders?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/orders'
query_str = 'limit=2&status=settled&symbol=4BTC_USDT'
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/orders";
string query_str = "limit=2&status=settled&symbol=4BTC_USDT";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
i: order id
I: client order id
m: pair
T: order type (1 market price,2 limit price)
s: order side (1 open long,2 open short,3 close long,4 close short)
Q: Order quantity
P: order price
S: order status (1 pending,2 deal part,3 filled,4 cancelled with deal part,5 canceled,100 fail)
r: failure reason
M: failure description
E: The number of transactions
e: Average transaction price
C: Order Creation Time
U: order update time
V: update id
z: Order Freeze Assets
rm: maker fee rate
rt: taker fee rate
of: order source
pid: corresponding position id
ot: the order type that contains the take profit and stop loss order
f: handling fee
fb: '0',
fb0: deduct handling fee
n: number of transactions
}
...
]
Obtain the delegation that meets the following conditions in the account corresponding to ApiKey
- All unsettled orders
- Settled orders within three months, including rejected, cancelled and filled orders
- All completed orders
- All partially cancelled orders
- Request method GET
- Request path /v4/cbu/userdata/orders
- Permissions: View, Trade
- request parameters (should be sorted)
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
ids | string | No | Order id The order id can be assigned by the exchange, or user-defined (use the client_order_id parameter when submitting the order). When using a custom id, you need to add a "c-" prefix before the id. For example: the custom id "123" is used when submitting the order, and "c-123" must be used when canceling the order. Multiple delegate ids can be specified in the following form "123,124,125,c-200" |
status | string | No | Valid values unsettled, settled unsettled means get unsettled orders, the returned results are sorted in reverse order by order creation time settled means settled orders are acquired, and the returned results are sorted in reverse order by order settlement time Default unsettled |
symbol | string | No | Trading pair code, such as 4BTC_USDT, 4ETH_USDT, etc. Multiple trading pair codes can be specified in the following form /v4/cbu/userdata/orders?symbol=4BTC_USDT,4ETH_USDT When status=unsettled, not specifying symbol will return unsettled orders for all trading pairs When status=settled, symbol parameter must be given |
start_time | long | no | limit the last creation time of the returned delegate |
end_time | long | no | limit the last creation time of the returned delegate |
before | int64 | no | delegate update id limit return delegate's maximum update id |
after | int64 | no | delegate update id limit return delegate's minimum update id |
limit | long | No | Specify the maximum number of delegates to return |
Parameter combinations and data sources supported by this interface
- ids
- status=unsettled + symbol
- status=settled + symbol + start_time
- status=settled + symbol + start_time + limit
- status=settled + symbol + end_time
- status=settled + symbol + end_time + limit
- status=settled + symbol + start_time + end_time
- status=settled + symbol + start_time + end_time + limit
- status=settled + symbol + before
- status=settled + symbol + before + limit
- status=settled + symbol + after
- status=settled + symbol + after + limit
The returned unsettled delegates are sorted by creation time The returned settled orders are sorted by settlement time from earliest to latest
Cancel Orders
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
ids:'14244173146202090'
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/order`;
request.delete({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'ids': '14245272657638034'
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/order'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.delete(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/order";
var myobj = new {
ids = "15741707974869000"
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
var httpMessage = new HttpRequestMessage(HttpMethod.Delete, url)
{
Content = new StringContent(body_str, Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(httpMessage);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
{
}
Revoke the delegation with the specified id
- Request method DELETE
- Request path /v4/cbu/userdata/order
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
ids | string | yes | order id The order id can be assigned by the exchange, or user-defined (use the client_order_id parameter when submitting the order). When using a custom id, you need to add a "c-" prefix before the id. For example: the custom id "123" is used when submitting the order, and "c-123" must be used when canceling the order. Multiple delegate ids can be specified in the following form "123,124,125,c-200" |
If the order with the specified id has been settled, or there is no order with the specified id, you will receive a -3004 error.
Cancel all Orders
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
symbol:'4BTC_USDT'
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/order`;
request.delete({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'symbol': '4BTC_USDT'
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/order'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.delete(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/order";
var myobj = new {
symbol = "4BTC_USDT"
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
var httpMessage = new HttpRequestMessage(HttpMethod.Delete, url)
{
Content = new StringContent(body_str, Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(httpMessage);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
{
}
Revoke all delegations
- Request method DELETE
- Request path /v4/cbu/userdata/order
- Permissions: Trade
- Request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | False | Trade pair codes 4BTC_USDT, 4ETH_USDT etc. |
Returns an empty object if the request is executed correctly, otherwise returns an error message
Get fills
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'limit=2&symbol=4BTC_USDT';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/fills?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/fills'
query_str = 'limit=2&symbol=4BTC_USDT'
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/fills";
string query_str = "limit=2&symbol=4BTC_USDT";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
i: fill id
o: order id
s: pair
T: detail id,
t: time
p: price
q: quantity
l: maker or taker
f: fee
fb: 0,
fb0: fee discount
}
...
]
Get deal records
- Request method GET
- Request path /v4/cbu/userdata/fills
- Permission: View, Trade
- request parameters (should be sorted)
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
order_id | string | false | Orders assigned by the exchange id Limits the return of only the transaction records for the specified order If you do not specify this parameter, please specify it symbol |
symbol | string | false | Trade pair codes For example 4BTC_USDT, 4ETH_USDT etc. Qualifies that only the transaction records for the specified trading pair are returned If you do not specify this parameter, please specify it order_id |
start_time | int64 | false | Limits the earliest time at which a deal record is returned |
end_time | int64 | false | Limits the most recent time returned to the deal record |
before | int64 | false | Deal history id Limits the maximum number of transaction records returned id |
after | int64 | false | Deal history id Limits the minimum number of transaction records returned id |
limit | int32 | false | Limits the maximum number of results returned The default value 100 |
The interface supports parameter combinations and data sources
- symbol --> database
- symbol + limit --> database
- symbol + start_time --> database
- symbol + start_time + limit --> database
- symbol + end_time --> database
- symbol + end_time + limit --> database
- symbol + start_time + end_time --> database
- symbol + start_time + end_time + limit --> database
- symbol + before --> database
- symbol + before + limit --> database
- symbol + after --> database
- symbol + after + limit --> database
- order_id --> database
- order_id + limit --> database
- order_id + before --> database
- order_id + before + limit --> database
The interface supports parameter combinations and data sources
Create an plan order
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
'cmd': 'open',
'symbol': '4BTC_USDT',
'side': 1,
'plan_type': 2,
'trigger_price': '20000',
'book_type': 2,
'price': '20000',
'amount': '0.001',
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/planOrders`;
request.post({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'cmd': 'open',
'symbol': '4BTC_USDT',
'side': 1,
'plan_type': 2,
'trigger_price': '20000',
'book_type': 2,
'price': '20000',
'amount': '0.001',
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/planOrders'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.post(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/planOrders";
var myobj = new {
cmd = "open",
symbol = "4BTC_USDT",
side = 1,
plan_type = 2,
trigger_price = "20000",
book_type = 2,
price = "20000",
amount = "0.001",
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpContent content = new StringContent(body_str, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, 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);
}
}
}
}
Response
{
id: plan order id,
m: pair
s: side,
sid: source order id,
oid: other plan order id,
pid: pisition id (For sub-warehouses),
q: Number of delegates,
t: Take Profit and Stop Loss type.1 Take Profit、2 Stop Loss
gt: Trigger mode (last price trigger)
bt: How to place an order (1 market price,2 limit price)
pg: Trigger the price
pb: Commission price
st: Take Profit stop stop order status(1 wait trigger、2 triggered、3 canceled、4 failed、5 canceled by system)
rs: The reason for the failure
rsm: Description of the failure
bid: Delegate orders order id
V: update id
C: create time,
U: update time
}
Submit a Take Profit and Stop Loss order
- Request method POST
- Request path /v4/cbu/userdata/planOrders
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
cmd | string | True | open |
symbol | string | True | Trade pair codes,如 For example 4BTC_USDT, 4ETH_USDT etc. |
side | string | True | Position direction,Valid values 1Long positions、2Short positions |
plan_type | string | True | Take Profit and Stop Loss Order Type,Valid values 1 Take Profit、2 Stop Loss |
trigger_price | decimal | True | Trigger price |
book_type | int | True | The delegate type,Valid values 1Market Take Profit and Stop Loss,2Limit Take Profit and Stop Loss |
price | decimal | False | Limit order price |
amount | decimal | True | Number of delegates |
Edit an plan order
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
'cmd': 'change',
'order_id': '123',
'book_type': 2,
'price': '20000',
'amount': '0.001',
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/planOrders`;
request.post({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'cmd': 'change',
'order_id': '123',
'book_type': 2,
'price': '20000',
'amount': '0.001',
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/planOrders'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.post(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/planOrders";
var myobj = new {
cmd = "change",
order_id = "123",
book_type = 2,
price = "20000",
amount = "0.001",
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpContent content = new StringContent(body_str, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, 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);
}
}
}
}
Response
{
id: plan order id,
m: pair
s: side,
sid: source order id,
oid: other plan order id,
pid: pisition id (For sub-warehouses),
q: Number of delegates
t: Take Profit and Stop Loss type.1 Take Profit、2 Stop Loss
gt: Trigger mode (last price trigger)
bt: How to place an order (1 market price,2 limit price)
pg: Trigger the price
pb: Commission price
st: Take Profit stop stop order status(1 wait trigger、2 triggered、3 canceled、4 failed、5 canceled by system)
rs: The reason for the failure
rsm: Description of the failure
bid: Delegate orders order id
V: update id
C: create time,
U: update time
}
Modify the Take Profit and Stop Loss order
- You can only modify the order type + order price + the number of orders
- Request method POST
- Request path /v4/cbu/userdata/planOrders
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
cmd | string | True | change |
order_id | string | True | Take Profit and Stop Loss Order Type id |
book_type | int | True | The delegate type,Valid values 1Market Take Profit and Stop Loss,2Limit Take Profit and Stop Loss |
price | decimal | false | Limit order price |
amount | decimal | True | Number of delegates |
Cancel Plan Orders
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
ids:'14244173146202090'
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/planOrders`;
request.delete({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'ids': '14245272657638034'
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/planOrders'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.delete(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/planOrders";
var myobj = new {
ids = "15741707974869000"
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
var httpMessage = new HttpRequestMessage(HttpMethod.Delete, url)
{
Content = new StringContent(body_str, Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(httpMessage);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
{
}
Cancels the Take Profit and Stop Order with the specified ID
- Request method DELETE
- Request path /v4/cbu/userdata/planOrders
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
ids | string | True | id Delegate id You can specify multiple delegate IDs in the following form "123,124" |
If a Take Profit and Stop Order with the specified ID has been triggered, or if there is no Take Profit and Stop Order with the specified ID, you will receive a -3004 error.
Cancel all Plan Orders
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
symbol:'4BTC_USDT'
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/planOrders`;
request.delete({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'symbol': '4BTC_USDT'
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/planOrders'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.delete(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/planOrders";
var myobj = new {
symbol = "4BTC_USDT"
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
var httpMessage = new HttpRequestMessage(HttpMethod.Delete, url)
{
Content = new StringContent(body_str, Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(httpMessage);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
{
}
Cancel all Take Profit and Stop Loss orders
- Request method DELETE
- Request path /v4/cbu/userdata/planOrders
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | False | Trade pair codes For example 4BTC_USDT, 4ETH_USDT etc. |
Returns an empty object if the request is executed correctly, otherwise returns an error message
Get Plan Orders
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'limit=2&status=settled&symbol=4BTC_USDT';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/planOrders?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/planOrders'
query_str = 'limit=2&status=settled&symbol=4BTC_USDT'
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/planOrders";
string query_str = "limit=2&status=settled&symbol=4BTC_USDT";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
id: plan order id,
m: pair
s: side,
sid: source order id,
oid: other plan order id,
pid: pisition id (For sub-warehouses),
q: Number of delegates,
t: Take Profit and Stop Loss type.1 Take Profit、2 Stop Loss
gt: Trigger mode (last price trigger)
bt: How to place an order (1 market price,2 limit price)
pg: Trigger the price
pb: Commission price
st: Take Profit stop stop order status(1 wait trigger、2 triggered、3 canceled、4 failed、5 canceled by system)
rs: The reason for the failure
rsm: Description of the failure
bid: Delegate orders
bid: c order id
V: update id
C: create time,
U: update time
}
...
]
All take profit and stop loss orders are not triggered
- All take profit and stop loss orders are not triggered
- Take Profit and Stop Loss orders within three months, with revocation and triggered
- All take profit and stop loss orders are not triggered Obtain the Take Profit and Stop Loss order in the apiKey corresponding account that meets the following conditions
- Request method GET
- Request path /v4/cbu/userdata/planOrders
- Permission: View, Trade
- request parameters (should be sorted)
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
ids | string | false | Delegate id The delegate id can be exchange-assigned, Multiple delegate IDs can be specified in the following form "123,124,125" |
status | string | false | Valid values unsettled, settled unsettled Indicates that the take profit and stop loss order is obtained without triggering, and the returned result is sorted in reverse order of the order when the order was created and the returned results are sorted in reverse order according to the order when the order was created settled Indicates that the triggered Take Profit and Stop Loss order is obtained, and the returned result is sorted in reverse order of the order triggered by the order default value unsettled |
symbol | string | false | Trade pair codes,For example 4BTC_USDT, 4ETH_USDT etc. Multiple trading pair codes can be specified as follows /v4/cbu/userdata/orders?symbol=4BTC_USDT,4ETH_USDT when status=unsettled , Unsettled orders that do not specify a symbol will return all trading pairs when status=settled , The symbol parameter must be given |
start_time | long | false | Limits the most recent creation time of the return delegate |
end_time | long | false | Limits the most recent creation time of the return delegate |
before | int64 | false | Delegate update ID Limits the maximum update id returned for the delegate |
after | int64 | false | Delegate update ID Qualifies the minimum update id for the return delegate |
limit | long | false | Specifies how many delegates are returned |
The interface supports parameter combinations and data sources
- ids
- status=unsettled + symbol
- status=settled + symbol + start_time
- status=settled + symbol + start_time + limit
- status=settled + symbol + end_time
- status=settled + symbol + end_time + limit
- status=settled + symbol + start_time + end_time
- status=settled + symbol + start_time + end_time + limit
- status=settled + symbol + before
- status=settled + symbol + before + limit
- status=settled + symbol + after
- status=settled + symbol + after + limit
Returned unsettled delegates are sorted by creation time by earlier and most recent The returned setled orders are sorted by settlement time by earlier and most recent
Get Positions
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'symbol=4BTC_USDT';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/positions?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/positions'
query_str = 'symbol=4BTC_USDT'
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/positions";
string query_str = "symbol=4BTC_USDT";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
id: position id,
ui: user id,
v: version,
m: pair symbol,
st: status,
sp: separate,
sd: side,
md: model,1 cross position, 2 Isolated position
l: leverage,
mg: margin,
hc: hold coin,
po: price open,
pa: price alert,
pf: price force,
pt: profit,
f: fee,
fb: 0,
fb0: fee bix0,
ps: The number of stop-loss orders
pp: Number of take profit orders
lc: The number of remaining flats
cc: Number of closed positions (recorded by the sub-position)
pc: Average closing price (recorded by sub-positions)
C: creation time
ud: update id,
U: Update time
}
...
]
Get the position of the corresponding account of apikey
- Request method GET
- Request path /v4/cbu/userdata/positions
- Permission: View, Trade
- request parameters (should be sorted)
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | false | Trade pair codes,For example 4BTC_USDT, 4ETH_USDT etc. |
side | int | false | Position direction, side only works when symbol is active |
Change Position Mode
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
'cmd': 'changeMode',
'symbol': '4BTC_USDT',
'mode': 1,
'leverage_long': '2',
'leverage_short': '4',
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/positions`;
request.post({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'cmd': 'changeMode',
'symbol': '4BTC_USDT',
'mode': 1,
'leverage_long': '2',
'leverage_short': '4',
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/positions'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.post(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/positions";
var myobj = new {
cmd = "changeMode",
symbol = "4BTC_USDT",
mode = 1,
plan_type = 2,
leverage_long = "2",
leverage_short = "4",
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpContent content = new StringContent(body_str, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, 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);
}
}
}
}
Response
{
}
Modify the position mode
- Switch between cross position mode and Isolated position mode
- Leverage multiple adjustment
- Request method POST
- Request path /v4/cbu/userdata/positions
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
cmd | string | true | changeMode |
symbol | string | true | Trade pairs |
mode | int | true | Position mode, valid value 1 cross position, 2 Isolated position |
leverage_long | int | true | Leverage multiples for long positions |
leverage_short | int | true | Short leverage multiple, in full mode mode, the value should be equal to leverage_long |
Change Position Margin
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
'cmd': 'changeMargin',
'symbol': '4BTC_USDT',
'side': 1,
'margin': '2',
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/positions`;
request.post({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'cmd': 'changeMargin',
'symbol': '4BTC_USDT',
'side': 1,
'margin': '2',
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/positions'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.post(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/positions";
var myobj = new {
cmd = "changeMargin",
symbol = "4BTC_USDT",
side = 1,
margin = "2",
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpContent content = new StringContent(body_str, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, 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);
}
}
}
}
Response
{
}
Adjust the margin of the position
- The Isolated position mode can only be modified
- Request method POST
- Request path /v4/cbu/userdata/positions
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
cmd | string | true | changeMargin |
symbol | string | true | Trading pair |
side | int | true | Position direction, valid value 1 long position, 2 short position |
margin | Decimal | true | Margin adjustment quantity |
Clear Position Hold
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
'cmd': 'clear',
'symbol': '4BTC_USDT',
'side': 1,
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/positions`;
request.post({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'cmd': 'clear',
'symbol': '4BTC_USDT',
'side': 1,
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/positions'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.post(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/positions";
var myobj = new {
cmd = "clear",
symbol = "4BTC_USDT",
side = 1,
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpContent content = new StringContent(body_str, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, 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);
}
}
}
}
Response
{
}
Close all positions in the position
- Close positions quickly at market prices
- In extreme markets, there may be a situation where there are insufficient counterpart orders that cannot be completely closed
- The closing price will not exceed the out-of-position range
- Request method POST
- Request path /v4/cbu/userdata/positions
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
cmd | string | true | clear |
symbol | string | false | Trading pair |
side | int | false | Position direction, valid value 1 long position, 2 short position When symbol works, the side only works |
The interface supports parameter combinations and data sources
- cmd=clear --> Close all positions
- cmd=clear + symbol --> Closes all positions of the specified trade
- cmd=clear + symbol + side --> Closes a position held on the specified trade pair for the specified position
Oppose Position
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const param = {
'cmd': 'oppose',
'symbol': '4BTC_USDT',
'side': 1,
}
let bodyStr = JSON.stringify(param);
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + bodyStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/positions`;
request.post({
url:url,
body:param,
json:true,
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import json
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
t = time.time()
def do_request():
param = {
'cmd': 'oppose',
'symbol': '4BTC_USDT',
'side': 1,
}
body_str = json.dumps(param)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + body_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
path = '/v4/cbu/userdata/positions'
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.post(END_POINT + path, json=param, 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
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/positions";
var myobj = new {
cmd = "oppose",
symbol = "4BTC_USDT",
side = 1,
};
string body_str = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + body_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path;
Console.WriteLine(sign_str);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpContent content = new StringContent(body_str, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, 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);
}
}
}
}
Response
{
}
Open a position in the opposite direction
- Quickly close the current position at the market price
- Open a position in the opposite direction of the market price quickly
- The opening and closing prices are not allowed to exceed the range of the out-of-the-position price
- Under extreme market conditions, there may be a situation where the position cannot be completely closed, in which case the position will not continue to be closed, nor will it continue to open the position
- In extreme market conditions, there may be a situation where the position cannot be fully filled, in which case the position will not continue to be opened
- Request method POST
- Request path /v4/cbu/userdata/positions
- Permission: Trade
- request parameters
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
cmd | string | true | oppose |
symbol | string | true | Trading pair |
side | int | true | Position direction, valid value 1 long position, 2 short position |
Get Position Logs
Request
let CryptoJS = require("crypto-js");
let request = require("request");
const endpoints = 'https://api.bibox.com/api'
const apikey = "9e03e8fda27b6e4fc6b29bb244747dcf64092996"; // your apikey
const secret = "b825a03636ca09c884ca11d71cfc4217a98cb8bf"; // your secret
const queryStr = 'limit=2&symbol=4BTC_USDT';
const expireTime = Date.now() + 20000;
const signStr = expireTime + ':' + queryStr;
const sign = CryptoJS.HmacSHA256(signStr, secret).toString();
const url = `${endpoints}/v4/cbu/userdata/dealLog?${queryStr}`;
request.get(url,{
headers: {
'Content-Type': 'application/json',
'Bibox-Api-Key': apikey,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': expireTime,
},
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body) // 7.the result
});
import hashlib
import hmac
import requests
import time
END_POINT = 'https://api.bibox.com/api'
API_KEY = '9e03e8fda27b6e4fc6b29bb244747dcf64092996'
SECRET_KEY = 'b825a03636ca09c884ca11d71cfc4217a98cb8bf'
def do_request():
path = '/v4/cbu/userdata/dealLog'
query_str = 'limit=2&symbol=4BTC_USDT'
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime) + ':' + query_str
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'Bibox-Api-Key': API_KEY,
'Bibox-Api-Sign': sign,
'Bibox-Expire-Time': str(expireTime),
}
resp = requests.get(END_POINT + path, query_str, 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 Class1
{
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string endpoints = "https://api.bibox.com/api";
string path = "/v4/cbu/userdata/dealLog";
string query_str = "limit=2&symbol=4BTC_USDT";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime + ":" + query_str;
string sign = HmacSha256(sign_str, secret);
string url = endpoints + path + "?" + query_str;
client.DefaultRequestHeaders.Add("Bibox-Api-Key", apikey);
client.DefaultRequestHeaders.Add("Bibox-Api-Sign", sign);
client.DefaultRequestHeaders.Add("Bibox-Expire-Time", expireTime);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
Response
[
{
i: '1125899906843599056', deal log id
m: '4STEPN_USDT', pair
y: 1, deal log type. 1 open position, 2 close positions, 3 position reduction to reduce the risk level, 4 open positions to empty positions, 5ADL
p: '1125899906842624053', Positions id
sd: 1, Position direction, 1 long position, 2 short positions
md: 1, Position mode, valid value 1 cross position, 2 Isolated position
hc: 3000,Number of open positions
hd: 20,The amount of position change
o: 1.3592983336, The average price of the position opened
pl: 1.3336, The price used
fi: 0, profit
f: 0.0106688, fee
fb: 0,
fb0: 0, Coupon credit handling fee
t: 1653541169000 Time
}
...
]
Get deal records
- Request method GET
- Request path /v4/cbu/userdata/dealLog
- Permission: View, Trade
- request parameters (should be sorted)
Parameter name | Parameter type | Required or not | Description |
---|---|---|---|
symbol | string | false | Trade pair codes For example 4BTC_USDT, 4ETH_USDT etc. Qualifies that only the transaction records for the specified trading pair are returned If you do not specify this parameter, specify it order_id |
start_time | int64 | false | Limits the earliest time at which a deal record is returned |
end_time | int64 | false | Limits the most recent time returned to the deal record |
before | int64 | false | Deal history id Limits the maximum number of transaction records returned id |
after | int64 | false | Deal history id Limits the minimum number of transaction records returned id |
limit | int32 | false | Limits the maximum number of results returned default value 100 |
The interface supports parameter combinations and data sources
- symbol --> database
- symbol + limit --> database
- symbol + start_time --> database
- symbol + start_time + limit --> database
- symbol + end_time --> database
- symbol + end_time + limit --> database
- symbol + start_time + end_time --> database
- symbol + start_time + end_time + limit --> database
- symbol + before --> database
- symbol + before + limit --> database
- symbol + after --> database
- symbol + after + limit --> database
User Data Streams
Overview
例子
const CryptoJS = require("crypto-js");
const WebSocket = require('ws');
const biboxws = 'wss://user-wss.bibox360.com/cbu';
const apikey = "9e2bd17ff73e8531c0f3c26f93e48bfa402a3b13"; // your apikey
const secret = "ca55beb9e45d4f30b3959b464402319b9e12bac7"; // your secret
let wsClass = function () {
};
wsClass.prototype._initWs = async function () {
let that = this;
console.log(biboxws);
const expireTime = Date.now() + 20000;
const sign = CryptoJS.HmacSHA256("" + expireTime, secret).toString();
let ws = new WebSocket(biboxws,"",{headers:{
'BIBOX-API-KEY': apikey,
'BIBOX-API-SIGN': sign,
'Bibox-Expire-Time': expireTime,
}});
that.ws = ws;
ws.on('open', function open() {
console.log(new Date(), 'open');
setInterval(function () {
ws.ping(Date.now())
},30000);
});
ws.on('close', data => {
console.log('close, ', data);
});
ws.on('error', data => {
console.log('error ',data);
});
ws.on('ping', data => {
console.log('ping ', data.toString('utf8'));
});
ws.on('pong', data => {
console.log('pong ', data.toString('utf8'));
});
ws.on('message', data => {
console.log(data.toString()) // the data may be is error message,check the data's stream is order or account
});
};
let instance = new wsClass();
instance._initWs().catch(err => {
console.log(err);
});
import websocket
import hashlib
import hmac
import time
ws_url = 'wss://user-wss.bibox360.com/cbu'
API_KEY = '9e2bd17ff73e8531c0f3c26f93e48bfa402a3b13'
SECRET_KEY = 'ca55beb9e45d4f30b3959b464402319b9e12bac7'
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
print("### opened ###")
def connect():
# websocket.enableTrace(True)
expireTime = int(time.time()) * 1000 + 20000
sign_str = str(expireTime)
sign = hmac.new(SECRET_KEY.encode("utf-8"), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
header = {
'BIBOX-API-KEY': API_KEY,
'BIBOX-API-SIGN': sign,
'Bibox-Expire-Time': str(expireTime),
}
ws = websocket.WebSocketApp(ws_url,
header=header,
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 System.Net.WebSockets;
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 Program
{
static async Task Send(ClientWebSocket ws, string data) =>
await ws.SendAsync(Encoding.UTF8.GetBytes(data), WebSocketMessageType.Text, true, CancellationToken.None);
static async Task Receive(ClientWebSocket ws)
{
var buffer = new ArraySegment<byte>(new byte[2048]);
do
{
WebSocketReceiveResult result;
using (var ms = new MemoryStream())
{
do
{
result = await ws.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
} while (!result.EndOfMessage);
if (result.MessageType == WebSocketMessageType.Close)
break;
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms, Encoding.UTF8))
Console.WriteLine(await reader.ReadToEndAsync());
}
} while (true);
}
static string GetExpireTime(int tmwindow)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds + tmwindow).ToString();
}
static string HmacSha256(string source, string key)
{
HMACSHA256 hmacmd = new HMACSHA256(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 async Task Main (string[] args)
{
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string wsuri = "wss://user-wss.bibox360.com/cbu";
string expireTime = GetExpireTime(20000);
string sign_str = expireTime;
string sign = HmacSha256(sign_str, secret);
do
{
using (var ws = new ClientWebSocket())
try
{
ws.Options.SetRequestHeader("Bibox-Api-Key", apikey);
ws.Options.SetRequestHeader("Bibox-Api-Sign", sign);
ws.Options.SetRequestHeader("Bibox-Expire-Time", expireTime);
await ws.ConnectAsync(new Uri(wsuri), CancellationToken.None);
await Receive(ws);
}
catch (Exception ex)
{
Console.WriteLine($"ERROR - {ex.Message}");
}
} while (true);
}
}
}
Using the Websocket push service, you can timely obtain the balance, order, position and take profit and stop loss order change information of the account in a timely manner
Connect to the Websocket server
Use the following URL to connect to the Websocket server:
wss://user-wss.bibox360.com/cbu
When connecting, append the following HTTP request headers
- BIBOX-API-KEY
- BIBOX-API-SIGN
- Bibox-Expire-Time
For details, see the [Authentication] #authentication section
Data flow After the connection is successfully established, the client will receive the balance change information and the entrustment change information of the apikey corresponding account. The format is as follows:
{
"stream": "account",
"data": { Account }
}
{
"stream": "position",
"data": { Position }
}
{
"stream": "order",
"data": { Order }
}
{
"stream": "planOrder",
"data": { Plan Order }
}
Account
When the account balance changes, you will receive an account event
{
"stream":"account",
"data":{
c: 'USDT', Currency symbol
b: '8247.1187293513', Account available balance
ff: '0', Pending orders are frozen
fc: '346.73844114',Full position pending orders are frozen
mf: '0',Margin Isolated positions
mc: '1396.55822362', margin Full positions
}
}
Orders
When the delegate changes, you receive an order event
{
"stream":"order",
"data":{
i: order id
I: client order id
m: pair
T: order type (1 market price,2 limit price)
s: order side (1 open long,2 open short,3 close long,4 close short)
Q: Order quantity
P: order price
S: order status (1 pending,2 deal part,3 filled,4 cancelled with deal part,5 canceled,100 fail)
r: failure reason
M: failure description
E: The number of transactions
e: Average transaction price
C: Order Creation Time
U: order update time
V: update id
z: Order Freeze Assets
rm: maker fee rate
rt: taker fee rate
of: order source
pid: corresponding position id
ot: the order type that contains the take profit and stop loss order
f: handling fee
fb: '0',
fb0: deduct handling fee
n: number of transactions
}
}
Positions
** When a position changes, a position event is received**
{
"stream":"position",
"data":{
id: position id,
ui: user id,
v: version,
m: pair symbol,
st: status,
sp: separate,
sd: side,
md: model,1 cross position, 2 Isolated position
l: leverage,
mg: margin,
hc: hold coin,
po: price open,
pa: price alert,
pf: price force,
pt: profit,
f: fee,
fb: 0,
fb0: fee bix0,
ps: The number of stop-loss orders
pp: Number of take profit orders
lc: The number of remaining flats
cc: Number of closed positions (recorded by the sub-position)
pc: Average closing price (recorded by sub-positions)
C: creation time
ud: update id,
U: Update time
}
}
Plan Orders
When the Take Profit and Stop Loss order is changed, you receive a planOrder event
{
"stream":"planOrder",
"data":{
id: plan order id,
m: pair
s: side,
sid: source order id,
oid: other plan order id,
pid: pisition id (For sub-warehouses),
q: Number of delegates,
t: Take Profit and Stop Loss type.1 Take Profit、2 Stop Loss
gt: Trigger mode (last price trigger)
bt: How to place an order (1 market price,2 limit price)
pg: Trigger the price
pb: Commission price
st: Take Profit stop stop order status(1 wait trigger、2 triggered、3 canceled、4 failed、5 canceled by system)
rs: The reason for the failure
rsm: Description of the failure
bid: Delegate orders order id
V: update id
C: create time,
U: update time
}
}
Fills
When a fill occurs on an order, a FILL event is received
{
"stream":"fill",
"data":{
i: fill id
o: order id
s: pair
T: detail id,
t: time
p: price
q: quantity
l: maker or taker
f: fee
fb: 0,
fb0: fee discount
}
}
Ledgers
When there is a new bill, you receive a ledger event
{
"stream":"ledger",
"data":{
i: ledger id
s: currency symbol
p: trading pair
T: Bill Type, 1 Transfer,2 Trade,3 Fee,4 Fund fee, 5 Adjust fund fee, 6 Force sub hold, 7 Force clear hold, 8 ADL
a: change amount
b: balance
t: time
}
}
DealLogs
When there is a change in the position size, a dealLog event is received
{
"stream":"dealLog",
"data":{
i: '1125899906843599056', deal log id
m: '4STEPN_USDT', pair
y: 1, deal log type. 1 open position, 2 close positions, 3 position reduction to reduce the risk level, 4 open positions to empty positions, 5ADL
p: '1125899906842624053', Positions id
sd: 1, Position direction, 1 long position, 2 short positions
md: 1, Position mode, valid value 1 cross position, 2 Isolated position
hc: 3000,Number of open positions
hd: 20,The amount of position change
o: 1.3592983336, The average price of the position opened
pl: 1.3336, The price used
fi: 0, profit
f: 0.0106688, fee
fb: 0,
fb0: 0, Coupon credit handling fee
t: 1653541169000 Time
}
}
Errors
错误码
Code | 描述 | Msg |
---|---|---|
2003 | Cookie 失效 | Cookie expired |
2033 | 操作失败!订单已完成或已撤销 | Operation failed! Order completed or canceled |
2034 | 操作失败!请检查参数是否正确 | Operation failed! Please check parameter |
2040 | 操作失败!没有该订单 | Operation failed! No record |
2064 | 订单撤销中,不能再次撤销 | Canceling. Unable to cancel again |
2065 | 委托价格设置过高,请重新设置价格 | Precatory price is exorbitant, please reset |
2066 | 委托价格设置过低,请重新设置价格 | Precatory price is low , please reset |
2067 | 暂不支持市价单 | Limit Order Only |
2068 | 下单数量不能低于0.0001 | Min Amount:0.0001 |
2069 | 市价单无法撤销 | Market order can not be canceled |
2078 | 下单价格非法 | unvalid order price |
2085 | 币种最小下单数量限制 | the trade amount is low |
2086 | 账户资产异常,限制下单 | Abnormal account assets, trade is forbiden |
2091 | 请求过于频繁,请稍后再试 | request is too frequency, please try again later |
2092 | 币种最小下单金额限制 | Minimum amount not met |
3000 | 请求参数错误 | Requested parameter incorrect |
3002 | 参数不能为空 | Parameter cannot be null |
3009 | 推送订阅channel不合法 | Illegal subscription channel |
3010 | websocket连接异常 | websocket connection error |
3011 | 接口不支持apikey请求方式 | Illegal subscribe event |
3012 | apikey无效 | Interface does not support apikey request method |
3016 | 交易对错误 | Invalid apikey |
3017 | 推送订阅event不合法 | Trading pair error |
3024 | apikey权限不足 | apikey authorization insufficient |
3025 | apikey签名验证失败 | apikey signature verification failed |
3026 | apikey ip受限制 | apikey ip is restricted |
3027 | 账户没有apikey | No apikey in your account |
3028 | 账户apikey数量超过了限制数量 | Account apikey has exceeded the limit amount |
3029 | apikey允许ip数量超过了限制数量 | apikey ip has exceeded the limit amount |
3033 | 查询类请求限制一个cmd | query allow only one cmd |
3034 | 最大cmd个数限制 | maxinum cmds |
3035 | cmd请求个数限制 | too many cmds |
4000 | 当前网络连接不稳定,请稍候重试 | the network is unstable now, please try again later |
4003 | 服务器繁忙,请稍后再试 | The server is busy, please try again later |