基本信息
U本位合约 API
使用 U本位合约 API开发应用程序,您可以准确地获取Bibox U本位合约市场的行情数据,快速进行自动化交易。U本位合约 API包含众多接口,按功能大致分为以下几组:
- Market Data Endpoints 用于获取行情数据的REST接口
- User Data Endpoints 用于获取用户私有数据的REST接口
- Market Data Streams 用于获取行情数据的WebSocket接口
- User Data Streams 用于获取用户私有数据的WebSocket接口
U本位合约 API使用如下Base 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
备用api域名列表
https://api.bibox.tel/v1/public/queryApiDomain
U本位合约 API的REST接口使用以下HTTP方法:
- GET 用于获取行情或私有数据
- POST 用于提交委托等操作
- DELETE 用于撤销委托等操作
U本位合约 API的REST接口所需的参数应根据以下规则附加于请求中:
- GET类型的接口参数应附加于Query String中
- POST类型的接口参数应以JSON格式附加于Request Body中
- DELETE类型的接口参数应以JSON格式附加于Request Body中
Response
U本位合约 API的响应数据都以JSON格式返回,具体格式请参考各接口的描述。
Error
U本位合约 API的错误以如下JSON格式返回:
{
"error": error code,
"message": "error message"
}
其中,error表示错误的类型,message包含错误产生的原因或如何避免错误的提示。具体的错误类型请参考Error章节的内容。
Time or Timestamp
U本位合约 API接口参数和响应数据中所涉及的时间值都是UNIX时间,单位为毫秒。
分仓限制
api不支持分仓。
流量限制
Bibox对来自于同一IP的请求做以下访问限制:
- Access Limits 访问频率限制
- Usage Limits CPU用量限制
- Access Limits访问频率限制
- 同一IP每10秒最多10000次请求,超出限制的请求会收到-2101错误。
- 用户可以根据需要在10秒内以任意频率发送最多10000次请求,可以大约每10ms发送一次,也可以在1秒内连续发送10000次,然后等待9秒。
- Usage Limits用量限制
- 同一IP每10秒最多消耗10000点CPU 时间,超出限制的请求会收到-2102错误。
- 不同API消耗的CPU时间不同,这取决于API如何访问数据。
- 在本文中, 每个API接口访问数据的方式会以“缓存”, “数据库”的形式标明。访问缓存的API消耗的CPU时间较少,访问数据库的API消耗的CPU时间较多。根据用户发送的参数,API可能混合访问缓存和数据库,甚至多次访问数据库,这会增加API消耗的CPU时间。
- 每次API请求消耗的CPU时间会包含在响应头Bibox-Usage中,其格式为t1:t2:t3,其中,t1表示本次API请求消耗的CPU时间,t2表示最近10秒内当前IP消耗的CPU时间,t3表示最近10秒内当前IP剩余的可用CPU时间。
Authentication
完整例子
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);
}
}
}
}
身份验证
- 私有接口用于访问账户、委托等私有信息,在请求时需要附加签名,以满足Bibox进行身份验证。本节将描述如何创建签名。
生成Api Key
- 要创建签名,首先需要生成Api Key和Secret Key组合。请牢记在此过程中生成的Secret Key,因为该值仅显示一次,如果忘记了Secret Key,请删除该Api Key,并生成新的Api Key和Secret Key组合。
HTTP 请求头
访问私有接口的请求都必需附加以下HTTP请求头:
- Bibox-Api-Key 已生成的Api Key
- Bibox-Api-Sign 签名
如果需要,也可以附加以下HTTP请求头:
- Bibox-Expire-Time
- 接口过期时间。
- 该值是以毫秒为单位的Unix时间,服务器会忽略该时间之后收到的请求,这主要用于避免网络延迟带来的影响。
- 过期时间限制在未来60秒内。
创建签名
在发送请求前,首先确定用于签名的消息体。对于GET类型的请求,过期时间加上Query String是需要签名的消息体(expireTime:queryString),对于POST和DELETE类型的请求,过期时间加上Body String是需要签名的消息体(expireTime:bodyString)。签名的具体方法如下:
- 第一步:以Secret Key作为Key对需要签名的消息体执行HmacSHA256算法
- 第二步:将以上结果转化为Hex String
- 第三步:将Hex String作为请求头Bibox-Api-Sign的值
Api Key权限
私有接口需要特定的权限才能执行。可以为Api Key授予适当的权限。如果Api Key未被授予某个接口需要的权限,那么使用该Api Key提交的请求将被拒绝。
可以授予Api Key以下权限:
- View权限允许Api Key获取私有数据。
- Trade权限允许Api Key提交或撤销委托,并允许Api Key获取交易相关的数据。
接口需要的权限将在每个接口的描述中给出。
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
- 请求路径 /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", 交易对名称
"base":"BTC",
"quote":"USDT", 计价币种
"price_scale":1, 价格小数位
"quantity_min":0.001, 最小下单量(币)
"quantity_max":100,最大下单量(币)
"quantity_increment":0.001,下单增量(币)
}
]
获取币种列表
- 请求方式 GET
- 请求路径 /v4/cbu/marketdata/pairs
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 否 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等, 可按如下形式指定多个交易对代码 /pairs?symbol=4BTC_USDT,4ETH_USDT 如果不指定 symbol 参数, 则返回全部交易对的信息 |
- 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":[ 买盘
[
委托价格,
委托量
]
],
"a":[ 卖盘
[
委托价格,
委托量
]
]
}
获取深度数据
- 请求方式 GET
- 请求路径 /v4/cbu/marketdata/order_book
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
level | int32 | 否 | 指定最多返回多少级深度 有效值 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000 默认值 100 |
price_scale | integer | 否 | 指定按价格合并深度,如指定交易对的价格最多含4位小数 price_scale=0 时返回的价格最多含4位小数, price_scale=1 时返回的价格最多含3位小数, 委托量是价格区间0.0010中全部委托量的和 price_scale=2 时返回的价格最多含2位小数, 委托量是价格区间0.0100中全部委托量的和 price_scale=3 时返回的价格最多含1位小数, 委托量是价格区间0.1000中全部委托量的和 price_scale=4 时返回的价格最多含0位小数, 委托量是价格区间1.0000中全部委托量的和 有效值 0, 1, 2, 3, 4, 5 默认值 0 |
注意: 数据按价格最优排序, 即买侧深度按价格由大到小排序, 卖侧深度按价格由小到大排序
- 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,
]
...
]
获取K线数据
- 请求方式 GET
- 请求路径 /v4/cbu/marketdata/candles
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
time_frame | string | 是 | K线数据的时间周期 有效值 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 3d, 1W或1M |
before | int64 | 否 | utc时间 限定返回K线记录的最近时间 |
after | int64 | 否 | utc时间 限定返回K线记录的最早时间 |
limit | integer | 否 | 获取K线记录的最大数量 默认值100,最大值1000 |
- 该接口支持的参数组合和数据源
- 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
返回结果按时间由早及近排序
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
- 请求路径 /v4/cbu/marketdata/tagPrices
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
time_frame | string | 是 | K线数据的时间周期 有效值 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 3d, 1W或1M |
before | int64 | 否 | utc时间 限定返回K线记录的最近时间 |
after | int64 | 否 | utc时间 限定返回K线记录的最早时间 |
limit | integer | 否 | 获取K线记录的最大数量 默认值100,最大值1000 |
- 该接口支持的参数组合和数据源
- 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
返回结果按时间由早及近排序
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
- 请求路径 /v4/cbu/marketdata/indices
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
time_frame | string | 是 | K线数据的时间周期 有效值 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 3d, 1W或1M |
before | int64 | 否 | utc时间 限定返回K线记录的最近时间 |
after | int64 | 否 | utc时间 限定返回K线记录的最早时间 |
limit | integer | 否 | 获取K线记录的最大数量 默认值100,最大值1000 |
- 该接口支持的参数组合和数据源
- 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
返回结果按时间由早及近排序
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",成交价
"q":"0.04",成交量
"s":"buy",成交方向
"t":"1652434793000",交易时间
}
...
]
获取交易记录
- 请求方式 GET
- 请求路径 /v4/cbu/marketdata/trades
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
start_time | int64 | 否 | 限定返回交易记录的最早时间 |
end_time | int64 | 否 | 限定返回交易记录的最近时间 |
before | int64 | 否 | 交易记录 id 限定返回交易记录的最大id |
after | int64 | 否 | 交易记录 id 限定返回交易记录的最大id |
limit | integer | 否 | 获取记录的最大数量 默认值100,最大值1000 |
- 该接口支持的参数组合和数据源
- 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
数据源为cache的参数组合用于获取最近1000条交易记录
数据源为database的参数组合用于获取较早的交易记录
如果用数据源为database的参数组合获取最新交易记录,其结果要比cache数据源稍有延迟 * Usage 用法举例:获取三个月内某交易对的全部交易记录
- 首先使用symbol + limit 参数组合获取最新的交易记录
- 将取到的首条记录的trade id作为before参数的值,反复使用symbol + before + limit参数组合获取更多记录,直至获取三个月内的全部交易记录后停止
返回结果按交易记录id由小到大排序
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",交易对名称
"o":31366.2,24小时开盘价
"h":32117.7,24小时最高价
"l":32117.7,24小时最低价
"p":27650.5,最新价
"q":0.075,最后一单成交数量
"v":2239.385,成交量
"a":66224658.4286,成交价值
"c":-0.1184,涨跌幅
"t":57394,成交笔数
"f":63958,起始trade id
"bp":27643.4,买一价
"bq":0.089,买一数量
"ap":27645.5,卖一价
"aq":0.01,卖一数量
}
]
获取报价数据
- 请求方式 GET
- 请求路径 /v4/cbu/marketdata/ticker
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等, 可按如下形式指定多个交易对代码 /pairs?symbol=4BTC_USDT,4ETH_USDT |
- Data Source
Cache
Market Data Streams
Overview
例子
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);
}
}
}
}
使用 Websocket 推送服务可以及时获取行情信息。
- 连接 Websocket 服务器
请使用以下 URL 连接 Websocket 服务器:
wss://market-wss.bibox360.com/cbu
在连接后,客户端可以发送以下JSON格式的请求给服务器
{
"id": 123, // 由客户端给定的请求id
"method": "..." // 请求类型
"params": [ // 请求参数列表
"...",
"...",
...
]
}
在收到请求后,服务器会发送以下JSON格式的响应给客户端
{
"id": 123, // 请求id
"result": "..." // 请求结果, "result":null 也是代表订阅成功
}
如果发生错误,服务器会发送以下错误信息给客户端
{
"id": 123, // 请求id
"error": -1000, // 错误代码
"message": "..." // 错误描述
}
同时,服务器还会发送以下JSON格式的数据流给客户端, 数据流包含市场行情的变化信息
{
"stream": "4BTC_USDT.trades", // 数据流名称
"data": ..., // 数据
}
请求:订阅数据流
{
"id": 1,
"method": "SUBSCRIBE",
"params": [
"stream name",
"stream name",
...
]
}
在连接后,请首先发送该请求给服务器,随后,服务器会在行情变化时发送相应的数据流给客户端。
"data stream name" 是数据流名称,数据流名称是以下格式的字符串。 symbol.data_type.param1.param2...
其中,symbol是交易对名称,如 4BTC_USDT、4ETH_USDT 等。 data_type是数据类型,目前仅支持以下数据类型 order_book: 深度 trades: 交易列表 candles: K线 ticker: 最新成交信息 indices: 指数价格K线 tagPrices: 标记价格K线
在data_type之后是参数列表,不同的数据类型有不同的参数列表,这些将在后续介绍
请求: 取消订阅数据流
{
"id": 1,
"method": "UNSUBSCRIBE",
"params": [
"data stream name",
"data stream name",
...
]
}
如果请求被服务器正确处理,客户端会收到以下响应:
{
"id":123,
"result":null
}
如果请求出错,客户端会收到以下错误响应:
{
"id": 123, // 请求id
"error": -1000, // 错误代码
"message": "..." // 错误描述
}
需要定时主动发送ping到推服务器,避免长时间没有消息导致服务断开
Request Methods
请求类型及参数
客户端可以发送以下请求给服务器
{
"id": 123, // 由客户端给定的请求id
"method": "..." // 请求类型
"params": [ // 请求参数列表
"...",
"...",
...
]
}
- 其中method字段的值是以下请求类型之一:
可选值 | 说明 |
---|---|
SUBSCRIBE | 1.订阅数据流 2.参数是数据流名称列表 3.在成功订阅后,服务器会在行情发生变化时发送数据流给客户端 |
UNSUBSCRIBE | 1.取消订阅数据流 2.参数是数据流名称列表 3.在成功取消订阅后,客户端不会再收到相应的数据流 |
Subscribe Order Book
订阅深度信息
发送以下请求可订阅深度信息
{
"id": 123,
"method": "SUBSCRIBE",
"params": [
"4BTC_USDT.order_book.1",
"4ETH_USDT.order_book.1",
...
]
}
- 参数
- 该请求的参数是深度流名称,格式如下:
- <symbol>.order_book.<max depth>
- <symbol> 是交易对名称,如4BTC_USDT,4ETH_USDT等
- <max depth> 是最大深度,有效值是1, 2, 5, 10, 20, 50, 100, 200, 500, 1000
数据流
// 订阅成功会返回如下数据流
{
"id":123,
"result":null
}
// 之后会返回如下数据流
{
"stream":"4APE_USDT.order_book.1",
"data":{
"i":"13890055",update id
"t":"1654826751000",时间
"b":[ 买盘
[
价格,
数量
],
[
"5.645",
"103"
]
],
"a":[ 卖盘
[
"5.646",
"902"
],
[
"5.647",
"0"
]
]
}
}
在成功订阅后,客户端会首先收到一个完整深度的数据流,之后会收到增量变化数据流,请按以下方法合成完整的深度. 数量为0,代表该深度被删除. 价格相同,则数量直接替换.
Subscribe Trades
订阅交易列表
发送以下请求可订阅交易列表
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.trades",
"4ETH_USDT.trades",
...
]
}
- 参数
- 该请求的参数是交易流名称,格式如下:
- <symbol>.trades
- <symbol> 是交易对名称,如4BTC_USDT,4ETH_USDT等
数据流
// 订阅成功会返回如下数据流
{
"id":123,
"result":null
}
// 之后会返回如下数据流
{
"stream":"4BTC_USDT.trades",
"data":[
{
"i":"128851",trade id
"p":"30479.2",成交价
"q":"0.04",成交量
"s":"buy",成交方向
"t":"1652434793000",交易时间
}
]
}
Subscribe Candles
订阅K线
发送以下请求可订阅K线
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.candles.1m",
"4ETH_USDT.candles.1h",
...
]
}
- 参数
- K线流名称格式如下:
- <symbol>.candles.<time_frame>
- <symbol> 是交易对名称,如4BTC_USDT,4ETH_USDT等
- <time_frame> 是K线周期,有效值是1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 1w, 1M
数据流
// 订阅成功会返回如下数据流
{
"id":123,
"result":null
}
// 之后会返回如下数据流
{
"stream":"4BTC_USDT.candles.1m", // 数据类别
"data":{
"t":60000,
"e":[
[
time,
open,
high,
low,
close,
volume,
amount,
first trade id,
trade count,
]
...
]
}
}
Subscribe Tickers
订阅K线
发送以下请求可订阅Ticker
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.ticker",
"4ETH_USDT.ticker",
...
]
}
- 参数
- Ticker流名称格式如下:
- <symbol>.ticker
- <symbol> 是交易对名称,如4BTC_USDT,4ETH_USDT等
数据流
// 订阅成功会返回如下数据流
{
"id":123,
"result":null
}
// 之后会返回如下数据流
{
"stream":"4BTC_USDT.ticker",
"data":{
"s":"4BTC_USDT",交易对名称
"o":31366.2,24小时开盘价
"h":32117.7,24小时最高价
"l":32117.7,24小时最低价
"p":27650.5,最新价
"q":0.075,最后一单成交数量
"v":2239.385,成交量
"a":66224658.4286,成交价值
"c":-0.1184,涨跌幅
"t":57394,成交笔数
"f":63958,起始trade id
"bp":27643.4,买一价
"bq":0.089,买一数量
"ap":27645.5,卖一价
"aq":0.01,卖一数量
}
}
Subscribe Indices
订阅指数K线
发送以下请求可订阅指数K线
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.indices.1m",
"4ETH_USDT.indices.1h",
...
]
}
- 参数
- 指数K线流名称格式如下:
- <symbol>.indices.<time_frame>
- <symbol> 是交易对名称,如4BTC_USDT,4ETH_USDT等
- <time_frame> 是K线周期,有效值是1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 1w, 1M
数据流
// 订阅成功会返回如下数据流
{
"id":123,
"result":null
}
// 之后会返回如下数据流
{
"stream":"4BTC_USDT.indices.1m", // 数据类别
"data":{
"t":60000,
"e":[
[
time,
open(ignore),
high(ignore),
low(ignore),
close,
volume(ignore),
amount(ignore),
firstTradeId(ignore),
tradeCount(ignore),
]
...
]
}
}
Subscribe Tag Prices
订阅标记价格K线
发送以下请求可订阅标记价格K线
{
"id": 123,
"method": "SUBSCRIBE"
"params": [
"4BTC_USDT.tagPrices.1m",
"4ETH_USDT.tagPrices.1h",
...
]
}
- 参数
- 标记价格K线流名称格式如下:
- <symbol>.tagPrices.<time_frame>
- <symbol> 是交易对名称,如4BTC_USDT,4ETH_USDT等
- <time_frame> 是K线周期,有效值是1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 1w, 1M
数据流
// 订阅成功会返回如下数据流
{
"id":123,
"result":null
}
// 之后会返回如下数据流
{
"stream":"4BTC_USDT.tagPrices.1m", // 数据类别
"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'
query_str = 'asset=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/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', 币种符号
b: '8247.1187293513', 账户可用余额
ff: '0', 逐仓挂单冻结
fc: '346.73844114',全仓挂单冻结
mf: '0',逐仓保证金
mc: '1396.55822362',全仓保证金
}
]
获取 API Key 对应账户中各种资产的余额, 冻结等信息
- 请求方式 GET
- 请求路径 /v4/cbu/userdata/accounts
- 权限: View, Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
asset | string | 否 | 资产代码,如 USDT 等 可按以下形式指定多个资产代码 /v4/cbu/userdata/accounts?asset=BTC,ETH 如果不指定 asset 参数, 则返回全部资产的信息 |
- 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: 币种符号
p: 交易对
T: 账单类型 1划转,2交易,3交易手续费,4资金费用,5资金费用调整,6降低风险等级减仓,7强平,8ADL系统减仓
a: 改变量
b: 余额
t: 时间
}
]
获取 API Key 对应账户的账单,包含一切改变账户余额的记录,如资金划转、交易、手续费收取等
- 请求方式 GET
- 请求路径 /v4/cbu/userdata/ledger
- 权限: View, Trade
- 请求参数(需要排序)
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
asset | string | 否 | 资产代码,如 USDT 等 可按以下形式指定多个资产代码 /v4/cbu/userdata/ledger?asset=BTC,ETH 如果不指定 asset 参数, 则返回全部资产的账单记录 |
start_time | int64 | 否 | 限定返回账单记录的最早时间 |
end_time | int64 | 否 | 限定返回账单记录的最近时间 |
before | int64 | 否 | 账单记录id 限定返回账单记录的最大id值 |
after | int64 | 否 | 账单记录id 限定返回账单记录的最小id值 |
limit | int32 | 否 | 限定返回账单记录的最大条数 默认值 100 |
start_time | int64 | 否 | 限定返回账单记录的最早时间 |
start_time | int64 | 否 | 限定返回账单记录的最早时间 |
- 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市价,2限价
s: order side。1开多,2开空,3平多,4平空
Q: 下单数量
P: 下单价格
S: 订单状态。1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
r: 失败原因
M: 失败描述
E: 已成交数量
e: 成交均价
C: 订单创建时间
U: 订单更新时间
V: update id
z: 订单冻结资产
rm: maker fee rate
rt: taker fee rate
of: 订单来源
pid: 对应仓位id
ot: 包含止盈止损委托的下单类型
f: 手续费
fb: '0',
fb0: 抵扣手续费
n: 成交笔数
F: [// 成交明细,只展示最近20条
{
i: fill id
t: time
p: price
q: quantity
l: maker or taker
f: fee
fb: 0,
fb0: fee discount
}
]
}
提交委托
- 请求方式 POST
- 请求路径 /v4/cbu/userdata/order
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
order_side | string | 是 | 委托方向,有效值 1 开多,2 开空, 3 平多, 4 平空 |
order_type | string | 是 | 委托类型,有效值 1 市价单, 2 限价单 |
client_oid | string | 否 | 委托id,有效值为int64整数的字符串,建议使用提交委托时的Unix时间戳 |
amount | decimal | 否 | 委托量 |
price | decimal | 否 | 委托限价 |
委托对象 最多包含该委托的20笔成交 如果委托有多于20笔成交,那么该对象仅包含最后20笔,其他成交请通过 fills 接口获取
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市价,2限价
s: order side。1开多,2开空,3平多,4平空
Q: 下单数量
P: 下单价格
S: 订单状态。1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
r: 失败原因
M: 失败描述
E: 已成交数量
e: 成交均价
C: 订单创建时间
U: 订单更新时间
V: update id
z: 订单冻结资产
rm: maker fee rate
rt: taker fee rate
of: 订单来源
pid: 对应仓位id
ot: 包含止盈止损委托的下单类型
f: 手续费
fb: '0',
fb0: 抵扣手续费
n: 成交笔数
}
获取指定 id 的委托
- 请求方式 GET
- 请求路径 /v4/cbu/userdata/order
- 权限: View, Trade
- 请求参数(需要排序)
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
order_id | string | 是 | 委托id 委托id可以是交易所分配的, 也可以是用户自定义的 (在提交委托时使用client_order_id参数). 当使用自定义id时, 需要在id前添加 “c-” 前缀. 例如: 提交委托时使用了自定义id “123”, 在获取委托时, 需使用 “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市价,2限价
s: order side。1开多,2开空,3平多,4平空
Q: 下单数量
P: 下单价格
S: 订单状态。1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
r: 失败原因
M: 失败描述
E: 已成交数量
e: 成交均价
C: 订单创建时间
U: 订单更新时间
V: update id
z: 订单冻结资产
rm: maker fee rate
rt: taker fee rate
of: 订单来源
pid: 对应仓位id
ot: 包含止盈止损委托的下单类型
f: 手续费
fb: '0',
fb0: 抵扣手续费
n: 成交笔数
}
...
]
获取ApiKey对应账户中符合下列条件的委托
- 全部未结算委托
- 三个月内的已结算委托, 含已拒绝, 已撤销和已成交委托
- 全部已成交委托
- 全部已撤销的部分成交委托
- 请求方式 GET
- 请求路径 /v4/cbu/userdata/orders
- 权限: View, Trade
- 请求参数(需要排序)
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
ids | string | 否 | 委托id 委托id可以是交易所分配的, 也可以是用户自定义的(在提交委托时使用client_order_id参数)。 当使用自定义id时,需要在id前添加 “c-” 前缀。 例如:提交委托时使用了自定义id “123”, 在撤销委托时,需使用 “c-123”。 可按以下形式指定多个委托id "123,124,125,c-200" |
status | string | 否 | 有效值 unsettled, settled unsettled 表示获取未结算委托,返回结果按委托创建时间倒序排序 settled 表示获取已结算委托,返回结果按委托结算时间倒序排序 默认值 unsettled |
symbol | string | 否 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 可按以下形式指定多个交易对代码 /v4/cbu/userdata/orders?symbol=4BTC_USDT,4ETH_USDT 当 status=unsettled 时, 不指定 symbol 将返回全部交易对的未结算委托 当 status=settled 时, 必须给定 symbol 参数 |
start_time | long | 否 | 限定返回委托的最近创建时间 |
end_time | long | 否 | 限定返回委托的最近创建时间 |
before | int64 | 否 | 委托更新 id 限定返回委托的最大更新id |
after | int64 | 否 | 委托更新 id 限定返回委托的最小更新id |
limit | long | 否 | 指定最多返回多少个委托 |
该接口支持的参数组合和数据源
- 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
返回的unsettled委托按创建时间由早及近排序 返回的settled委托按结算时间由早及近排序
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
{
}
撤销指定 id 的委托
- 请求方式 DELETE
- 请求路径 /v4/cbu/userdata/order
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
ids | string | 是 | 委托id 委托id可以是交易所分配的, 也可以是用户自定义的(在提交委托时使用client_order_id参数)。 当使用自定义id时,需要在id前添加 “c-” 前缀。 例如:提交委托时使用了自定义id “123”, 在撤销委托时,需使用 “c-123”。 可按以下形式指定多个委托id "123,124,125,c-200" |
如果指定id的委托已结算,或者不存在指定id的委托,会收到-3004错误。
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
{
}
撤销全部委托
- 请求方式 DELETE
- 请求路径 /v4/cbu/userdata/order
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 否 | 交易对代码 如 4BTC_USDT, 4ETH_USDT 等 |
如果请求被正确执行,返回空对象,否则返回错误信息
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
- 请求路径 /v4/cbu/userdata/fills
- 权限: View, Trade
- 请求参数(需要排序)
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
order_id | string | 否 | 交易所分配的委托id 限定仅返回指定委托的成交记录 如果不指定该参数,请指定 symbol |
symbol | string | 否 | 交易对代码 如 4BTC_USDT, 4ETH_USDT 等 限定仅返回指定交易对的成交记录 如果不指定该参数,请指定 order_id |
start_time | int64 | 否 | 限定返回成交记录的最早时间 |
end_time | int64 | 否 | 限定返回成交记录的最近时间 |
before | int64 | 否 | 成交记录 id 限定返回成交记录的最大id |
after | int64 | 否 | 成交记录 id 限定返回成交记录的最小id |
limit | int32 | 否 | 限定返回结果的最大条数 默认值 100 |
该接口支持的参数组合和数据源
- 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
返回结果按成交记录id由小到大排序
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 (分仓用),
q: 委托数量,
t: 止盈止损类型, 1止盈、2止损,
gt: 触发方式(最新成交价触发),
bt: 下单方式, 1市价,2限价,
pg: 触发价格,
pb: 委托价格,
st: 止盈止损订单状态。1未触发、2触发结束、3取消结束、4触发挂单失败、5对应的止盈(或止损)委托已经触发,当前委托自动取消,
rs: 失败原因
rsm: 失败描述,
bid: 委托单 order id
V: update id
C: create time,
U: update time
}
提交止盈止损委托
- 请求方式 POST
- 请求路径 /v4/cbu/userdata/planOrders
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
cmd | string | 是 | open |
symbol | string | 是 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
side | string | 是 | 仓位方向,有效值 1多仓、2空仓 |
plan_type | string | 是 | 止盈止损委托类型,有效值 1 止盈、2止损 |
trigger_price | decimal | 是 | 触发价 |
book_type | int | 是 | 委托类型,有效值 1市价止盈止损,2限价止盈止损 |
price | decimal | 否 | 限价委托价 |
amount | decimal | 是 | 委托数量 |
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 (分仓用),
q: 委托数量,
t: 止盈止损类型, 1止盈、2止损,
gt: 触发方式(最新成交价触发),
bt: 下单方式, 1市价,2限价,
pg: 触发价格,
pb: 委托价格,
st: 止盈止损订单状态。1未触发、2触发结束、3取消结束、4触发挂单失败、5对应的止盈(或止损)委托已经触发,当前委托自动取消,
rs: 失败原因
rsm: 失败描述,
bid: 委托单 order id
V: update id
C: create time,
U: update time
}
修改止盈止损委托
- 只能修改委托类型+委托价格+委托数量
- 请求方式 POST
- 请求路径 /v4/cbu/userdata/planOrders
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
cmd | string | 是 | change |
order_id | string | 是 | 止盈止损委托id |
book_type | int | 是 | 委托类型,有效值 1市价止盈止损,2限价止盈止损 |
price | decimal | 否 | 限价委托价 |
amount | decimal | 是 | 委托数量 |
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
{
}
撤销指定 id 的止盈止损委托
- 请求方式 DELETE
- 请求路径 /v4/cbu/userdata/planOrders
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
ids | string | 是 | 委托id 可按以下形式指定多个委托id "123,124" |
如果指定id的止盈止损委托已触发,或者不存在指定id的止盈止损委托,会收到-3004错误。
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
{
}
撤销全部止盈止损委托
- 请求方式 DELETE
- 请求路径 /v4/cbu/userdata/planOrders
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 否 | 交易对代码 如 4BTC_USDT, 4ETH_USDT 等 |
如果请求被正确执行,返回空对象,否则返回错误信息
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 (分仓用),
q: 委托数量,
t: 止盈止损类型, 1止盈、2止损,
gt: 触发方式(最新成交价触发),
bt: 下单方式, 1市价,2限价
pg: 触发价格,
pb: 委托价格,
st: 止盈止损订单状态。1未触发、2触发结束、3取消结束、4触发挂单失败、5对应的止盈(或止损)委托已经触发,当前委托自动取消,
rs: 失败原因
rsm: 失败描述,
bid: 委托单 order id
V: update id
C: create time,
U: update time
}
...
]
获取ApiKey对应账户中符合下列条件的止盈止损委托
- 全部未触发止盈止损委托
- 三个月内的止盈止损委托, 含撤销和已触发的
- 全部已触发止盈止损委托
- 请求方式 GET
- 请求路径 /v4/cbu/userdata/planOrders
- 权限: View, Trade
- 请求参数(需要排序)
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
ids | string | 否 | 委托id 委托id可以是交易所分配的, 可按以下形式指定多个委托id "123,124,125" |
status | string | 否 | 有效值 unsettled, settled unsettled 表示获取未触发止盈止损委托,返回结果按委托创建时间倒序排序 settled 表示获取已触发止盈止损委托,返回结果按委托触发时间倒序排序 默认值 unsettled |
symbol | string | 否 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 可按以下形式指定多个交易对代码 /v4/cbu/userdata/orders?symbol=4BTC_USDT,4ETH_USDT 当 status=unsettled 时, 不指定 symbol 将返回全部交易对的未结算委托 当 status=settled 时, 必须给定 symbol 参数 |
start_time | long | 否 | 限定返回委托的最近创建时间 |
end_time | long | 否 | 限定返回委托的最近创建时间 |
before | int64 | 否 | 委托更新 id 限定返回委托的最大更新id |
after | int64 | 否 | 委托更新 id 限定返回委托的最小更新id |
limit | long | 否 | 指定最多返回多少个委托 |
该接口支持的参数组合和数据源
- 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
返回的unsettled委托按创建时间由早及近排序 返回的settled委托按结算时间由早及近排序
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。1多仓,2空仓,
md: model。1全仓,2逐仓,3全仓分仓,4逐仓分仓,
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: 止损单数量,
pp: 止盈单数量,
lc: 剩余可平数量,
cc: 已平仓数量(分仓会记录),
pc: 平仓均价(分仓会记录),
C: 创建时间,
ud: update id,
U: 更新时间
}
...
]
获取ApiKey对应账户的仓位
- 请求方式 GET
- 请求路径 /v4/cbu/userdata/positions
- 权限: View, Trade
- 请求参数(需要排序)
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 否 | 交易对代码,如 4BTC_USDT, 4ETH_USDT 等 |
side | int | 否 | 仓位方向,当symbol有效时,side才有效 |
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
{
}
修改仓位模式
- 逐仓全仓模式切换
- 杠杆倍数调整
- 请求方式 POST
- 请求路径 /v4/cbu/userdata/positions
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
cmd | string | 是 | changeMode |
symbol | string | 是 | 交易对 |
mode | int | 是 | 仓位模式,有效值 1全仓,2逐仓 |
leverage_long | int | 是 | 多仓杠杆倍数 |
leverage_short | int | 是 | 空仓杠杆倍数,全仓模式模式下,该值应该等于 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
{
}
调整仓位保证金
- 逐仓模式才可以修改
- 请求方式 POST
- 请求路径 /v4/cbu/userdata/positions
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
cmd | string | 是 | changeMargin |
symbol | string | 是 | 交易对 |
side | int | 是 | 仓位方向,有效值 1多仓,2空仓 |
margin | Decimal | 是 | 保证金调整数量 |
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
{
}
平掉仓位所有持仓
- 以市价快速平仓
- 极端行情下,可能存在对手单不足导致无法全部平仓的情况
- 平仓价不会超出爆仓价范围
- 请求方式 POST
- 请求路径 /v4/cbu/userdata/positions
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
cmd | string | 是 | clear |
symbol | string | 否 | 交易对 |
side | int | 否 | 仓位方向,有效值 1多仓,2空仓 当symbol 有效时,side才有效 |
该接口支持的参数组合和数据源
- cmd=clear --> 平掉所有仓位持仓
- cmd=clear + symbol --> 平掉指定交易对所有持仓
- cmd=clear + symbol + side --> 平掉指定交易对指定仓位持仓
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
{
}
反方向开仓
- 以市价快速平掉当前持仓
- 以市价快速反方向开仓
- 开仓价、平仓价不允许超出爆仓价范围
- 极端行情下,可能会出现平仓不能完全成交的情况,这种情况下将不会继续平仓,也不会继续开仓
- 极端行情下,可能会出现开仓不能完全成交的情况,这种情况下将不会继续开仓
- 请求方式 POST
- 请求路径 /v4/cbu/userdata/positions
- 权限: Trade
- 请求参数
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
cmd | string | 是 | oppose |
symbol | string | 是 | 交易对 |
side | int | 是 | 仓位方向,有效值 1多仓,2空仓 |
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开仓,2平仓,3减仓降低风险等级, 4爆仓清空仓位, 5ADL
p: '1125899906842624053', 仓位id
sd: 1, 仓位方向,1多仓,2空仓
md: 1, 仓位模式,1全仓,2逐仓,3全仓分仓,4逐仓分仓
hc: 3000,持仓数量
hd: 20,持仓改变量
o: 1.3592983336, 开仓均价
pl: 1.3336, 用到的价格
fi: 0, 盈利
f: 0.0106688, 手续费
fb: 0,
fb0: 0, 优惠券抵扣手续费
t: 1653541169000 时间
}
...
]
获取成交记录
- 请求方式 GET
- 请求路径 /v4/cbu/userdata/dealLog
- 权限: View, Trade
- 请求参数(需要排序)
参数名称 | 参数类型 | 是否必传 | 说明 |
---|---|---|---|
symbol | string | 否 | 交易对代码 如 4BTC_USDT, 4ETH_USDT 等 限定仅返回指定交易对的成交记录 如果不指定该参数,请指定 order_id |
start_time | int64 | 否 | 限定返回成交记录的最早时间 |
end_time | int64 | 否 | 限定返回成交记录的最近时间 |
before | int64 | 否 | 成交记录 id 限定返回成交记录的最大id |
after | int64 | 否 | 成交记录 id 限定返回成交记录的最小id |
limit | int32 | 否 | 限定返回结果的最大条数 默认值 100 |
该接口支持的参数组合和数据源
- 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 = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
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,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close,
header=header)
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);
}
}
}
使用 Websocket 推送服务可以及时获取账户的余额、委托、仓位及止盈止损委托变动信息。
连接 Websocket 服务器
请使用以下 URL 连接 Websocket 服务器:
wss://user-wss.bibox360.com/cbu
在连接时,请附加以下HTTP请求头
- BIBOX-API-KEY
- BIBOX-API-SIGN
- Bibox-Expire-Time
具体方法请参考Authentication章节
数据流 在成功建立连接后,客户端将收到ApiKey对应账户的余额变动信息及委托变动信息。格式如下:
{
"stream": "account",
"data": { Account }
}
{
"stream": "position",
"data": { Position }
}
{
"stream": "order",
"data": { Order }
}
{
"stream": "planOrder",
"data": { Plan Order }
}
Account
当账户余额发生变更时,会收到account事件
{
"stream":"account",
"data":{
c: 'USDT', 币种符号
b: '8247.1187293513', 账户可用余额
ff: '0', 逐仓挂单冻结
fc: '346.73844114',全仓挂单冻结
mf: '0',逐仓保证金
mc: '1396.55822362',全仓保证金
}
}
Orders
当委托发生变更时,会收到order事件
{
"stream":"order",
"data":{
i: order id
I: client order id
m: pair
T: order type。1市价,2限价
s: order side。1开多,2开空,3平多,4平空
Q: 下单数量
P: 下单价格
S: 订单状态。1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
r: 失败原因
M: 失败描述
E: 已成交数量
e: 成交均价
C: 订单创建时间
U: 订单更新时间
V: update id
z: 订单冻结资产
rm: maker fee rate
rt: taker fee rate
of: 订单来源
pid: 对应仓位id
ot: 包含止盈止损委托的下单类型
f: 手续费
fb: '0',
fb0: 抵扣手续费
n: 成交笔数
}
}
Positions
当仓位发生变更时,会收到position事件
{
"stream":"position",
"data":{
id: position id,
ui: user id,
v: version,
m: pair symbol,
st: status,
sp: separate,
sd: side。1多仓,2空仓,
md: model。1全仓,2逐仓,3全仓分仓,4逐仓分仓,
l: leverage,
mg: margin,
hc: hold coin,
po: price open,
pa: price alert,
pf: price force,
pt: profit,
f: fee,
fb: fee bix,
fb0: fee bix0,
ps: 止损单数量,
pp: 止盈单数量,
lc: 剩余可平数量,
cc: 已平仓数量(分仓会记录),
pc: 平仓均价(分仓会记录),
C: 创建时间,
ud: update id,
U: 更新时间
}
}
Plan Orders
当止盈止损委托发生变更时,会收到 planOrder 事件
{
"stream":"planOrder",
"data":{
id: plan order id,
m: pair
s: side,
sid: source order id,
oid: other plan order id,
pid: pisition id (分仓用),
q: 委托数量,
t: 止盈止损类型, 1止盈、2止损
gt: 触发方式(最新成交价触发),
bt: 下单方式, 1市价,2限价,
pg: 触发价格,
pb: 委托价格,
st: 止盈止损订单状态。1未触发、2触发结束、3取消结束、4触发挂单失败、5对应的止盈(或止损)委托已经触发,当前委托自动取消,
rs: 失败原因
rsm: 失败描述,
bid: 委托单 order id
V: update id
C: create time,
U: update time
}
}
Fills
当委托发生成交时,会收到 fill 事件
{
"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
当有新的账单时,会收到 ledger 事件
{
"stream":"ledger",
"data":{
i: ledger id
s: 币种符号
p: 交易对
T: 账单类型 1划转,2交易,3交易手续费,4资金费用,5资金费用调整,6降低风险等级减仓,7强平,8ADL系统减仓
a: 改变量
b: 余额
t: 时间
}
}
DealLogs
当持仓量有变化时,会收到 dealLog 事件
{
"stream":"dealLog",
"data":{
i: '1125899906843599056', deal log id
m: '4STEPN_USDT', pair
y: 1, deal log type. 1开仓,2平仓,3减仓降低风险等级, 4爆仓清空仓位, 5ADL
p: '1125899906842624053', 仓位id
sd: 1, 仓位方向,1多仓,2空仓
md: 1, 仓位模式,1全仓,2逐仓,3全仓分仓,4逐仓分仓
hc: 3000,持仓数量
hd: 20,持仓改变量
o: 1.3592983336, 开仓均价
pl: 1.3336, 用到的价格
fi: 0, 盈利
f: 0.0106688, 手续费
fb: 0,
fb0: 0, 优惠券抵扣手续费
t: 1653541169000 时间
}
}
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 |