Bithumb Futures API Documentation
Using Bithumb Futures API
The Bithumb Futures API is based on RESTful and WebSocket.
- The base URL for the RESTful API is
https://bithumbfutures.com/
. - The URL for the WebSocket is:
https://bithumbfutures.com/<account-group>/api/pro/v1/stream
. You will have to substitute<account-group>
with your account group.
The RESTful API has JSON-encoded responses. All websocket messages are JSON-encoded.
Change Log
2020-04-05
Added three fields to WebSocket channel futures-collateral
: requestId id
, transactionType tp
, and transaction number txNum
.
2020-03-11
Added indexPrice
and markPrice
to futures/position
RESTful API.
Added idxPx
and markPx
to the futures-position
message (WebSocket).
2020-03-10
Added maxBuyNotional
and maxSellNotional
to futures/position
RESTful API. The two existing fields maxBuyOrderSize
and maxSellOrderSize
are deprecated and will be removed in the next release.
Added mbn
and msn
to the futures-position
message (WebSocket). The two existing fields mbos
and msos
are deprecated and will be removed in the next release.
Terminology
Asset / Collateral Asset
collateral asset refers to the cryptocurrency held in the account. Each collateral asset is uniquely identified by
an asset
code. For instance, Bitcoin is one collateral asset and has asset code BTC
.
Symbol / Futures Contract
Futures contract are tradable products listed on the exchange. Each futures contract is uniquely identified by a symbol
.
For instance, the symbol of the BTC perpetrual contract is BTC-PERP
.
Making REST API Calls
The RESTful APIs will always respond with JSON objects.
Authenticate a RESTful Request
Create Request
To access private data via RESTful APIs, you must include the following headers:
x-auth-key
- required, the api key as a string.x-auth-timestamp
- required, the UTC timestamp in milliseconds of your requestx-auth-signature
- required, the request signature (see Sign a Request)
The timestamp in the header will be checked against server time. If the difference is greater than 30 seconds, the request will be rejected.
Sign a Request
Signing a RESTful Request
# bash
APIPATH=user/info
APIKEY=CEcrjGyipqt0OflgdQQSRGdrDXdDUY2x
SECRET=hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk
TIMESTAMP=`date +%s%N | cut -c -13` # 1562952827927
MESSAGE=$TIMESTAMP+$APIPATH
SIGNATURE=`echo -n $MESSAGE | openssl dgst -sha256 -hmac $SECRET -binary | base64`
echo $SIGNATURE # vBZf8OQuiTJIVbNpNHGY3zcUsK5gJpwb5lgCgarpxYI=
curl -X GET -i \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "x-auth-key: $APIKEY" \
-H "x-auth-signature: $SIGNATURE" \
-H "x-auth-timestamp: $TIMESTAMP" \
https://bithumbfutures.com/api/pro/v1/info
# python 3.6+
import time, hmac, hashlib, base64
api_path = "user/info"
api_key = "CEcrjGyipqt0OflgdQQSRGdrDXdDUY2x"
sec_key = "hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk"
timestamp = int(round(time.time() * 1e3)) # 1562952827927
message = bytes(f"{timestamp}+{api_path}", 'utf-8')
secret = bytes(sec_key, 'utf-8')
signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())
header = {
"x-auth-key": api_key,
"x-auth-signature": signature,
"x-auth-timestamp": timestamp,
}
print(signature) # b'vBZf8OQuiTJIVbNpNHGY3zcUsK5gJpwb5lgCgarpxYI='
// java 1.8+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class SignatureExample {
public static void main(String[] args) {
try {
long timestamp = System.currentTimeMillis(); // 1562952827927
String api_path = "user/info";
String secret = "hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk";
String message = timestamp + "+" + api_path;
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
System.out.println(hash); // vBZf8OQuiTJIVbNpNHGY3zcUsK5gJpwb5lgCgarpxYI=
}
catch (Exception e) {
System.out.println("Error");
}
}
}
To query APIs with private data, you must include a signature using base64 encoded HMAC sha256 algorithm. The prehash string is <timestamp>+<api-path>
.
The timestamp
is the UTC timestamp in milliseconds.
API Permissions
You must specify permissions when setting up API keys. API permissions can never be changed. If you want different permissions, you would have to apply for new API keys.
There are two different permissions:
- View
- Trade
Permissions - Bird's-eye View
RESTful APIs
API | Type | View | Trade | Method / URL |
---|---|---|---|---|
Market Data | Public | GET /api/pro/v1/futures/market-data |
||
Funding Rate History | Public | GET /api/pro/v1/futures/funding-rates |
||
Futures Contract Info | Public | GET /api/pro/v1/futures/contracts |
||
Futures Collateral Info | Public | GET /api/pro/v1/futures/collateral |
||
Reference Prices | Public | GET /api/pro/v1/futures/ref-px |
||
Account Info | Private | GET /api/pro/v1/info |
||
Account Funding Payment History | Private | x | GET <account-group>/api/pro/v1/futures/funding-payments |
|
Account Contract Positions | Private | x | GET <account-group>/api/pro/futures/position |
|
Futures Collateral Balances | Private | x | GET <account-group>/api/pro/v1/futures/collateral-balance |
|
Account Futures Risk Profile | Private | x | GET <account-group>/api/pro/futures/risk |
|
Wallet Deposit/Withdrawal History | Private | x | GET /api/pro/wallet/transactions |
|
List Open Orders | Private | x | GET <account-group>/api/pro/v1/futures/order/open |
|
Place New Order | Private | x | POST <account-group>/api/pro/v1/futures/order |
|
Cancel Order | Private | x | DELETE <account-group>/api/pro/v1/futures/order |
WebSocket Requests
API | Type | View | Trade | Action |
---|---|---|---|---|
Authenticate Session | Public | x | auth |
|
Place New Order | Private | x | place-order |
|
Cancel Order | Private | x | cancel-order |
|
Cancel All Orders | Private | x | cancel-all |
|
Account Contract Positions | Private | x | futures-position |
|
Account Futures Risk Profile | Private | x | futures-risk |
Demo Code
REST APIs - Futures
Market Data (Public)
Anyone can access public market data.
Futures Collateral Assets
Futures Collateral Assets
curl -X GET https://bithumbfutures.com/api/pro/v1/futures/collateral
Sample Resonse
{
"code": 0,
"data": [
{
"asset": "USDT",
"assetName": "Tether",
"discountFactor": "1"
},
{
"asset": "BTC",
"assetName": "Bitcoin",
"discountFactor": "0.98"
}
]
}
You can get a list of assets eligible to be used as collateral with this API, along with other information needed to calculate the total collateral value of your account.
Permissions
This API is public.
HTTP Request
GET /api/pro/v1/futures/collateral
Response Content
Name | Type | Description | Sample Response |
---|---|---|---|
asset | String |
asset code | "BTC" |
assetName | String |
full name of the asset | "Bitcoin" |
discountFactor | String |
the collateral discount factor | "0.98" |
The exchange calculates the total collateral value of an account based on its adjusted USDT value (discount factor * reference price * collateral balance). The collateral value of the account is simply the sum of the adjusted USDT value of its all collateral assets.
Futures Contracts
Futures Contracts
curl -X GET https://bithumbfutures.com/api/pro/v1/futures/contracts
Sample Resonse
{
"code": 0,
"data": [
{
"symbol": "BTC-PERP",
"tradingStartTime": 1574640000000,
"collapseDecimals": "1,0.1,0.01",
"minQty": "0.000000001",
"maxQty": "1000000000",
"minNotional": "5",
"maxNotional": "100000",
"statusCode": "Normal",
"statusMessage": "",
"tickSize": "0.25",
"lotSize": "0.0001",
}
]
}
Permissions
This API is public.
HTTP Request
GET /api/pro/v1/futures/contracts
Response Content
Name | Type | Description |
---|---|---|
symbol | String |
contract symbol |
tradingStartTime | Long | UTC timestamp when the contract is available for trading |
collapseDecimals | String |
|
minQty | String |
minimum quantity allowed for an order |
maxQty | String |
maximum quantity allowed for an order |
minNotional | String |
minimum notional allowed for an order |
maxNotional | String |
maximum notional allowed for an order |
tickSize | String |
the tick size requirement for an order (a number in string format) |
lotSize | String |
the lot size requirement for an order (a number in string format) |
statusCode | String |
status code of the contract, e.g., Normal |
statusMessage | String |
When status code is not Normal , this message will contain the reason. |
Bar Info
Request
curl -X GET https://bithumbfutures/comi/pro/v1/barhist/info
Sample response
{
"code": 0,
"data": [
{
"name": "1",
"intervalInMillis": 60000
},
{
"name": "5",
"intervalInMillis": 300000
},
{
"name": "15",
"intervalInMillis": 900000
},
{
"name": "30",
"intervalInMillis": 1800000
},
{
"name": "60",
"intervalInMillis": 3600000
},
{
"name": "120",
"intervalInMillis": 7200000
},
{
"name": "240",
"intervalInMillis": 14400000
},
{
"name": "360",
"intervalInMillis": 21600000
},
{
"name": "720",
"intervalInMillis": 43200000
},
{
"name": "1d",
"intervalInMillis": 86400000
},
{
"name": "1w",
"intervalInMillis": 604800000
},
{
"name": "1m",
"intervalInMillis": 2592000000
}
]
}
HTTP Request
GET /api/pro/v1/barhist/info
This API returns a list of all bar intervals supported by the server.
Request Parameters
This API endpoint does not take any parameters.
Resposne
Name | Type | Description |
---|---|---|
name |
String |
name of the interval |
intervalInMillis |
Long |
length of the interval |
Plesae note that the one-month bar (1m
) always resets at the month start. The intervalInMillis
value for the one-month bar
is only indicative.
The value in the name
field should be your input to the Historical Bar Data API.
Historical Bar Data
Request
curl -X GET https://bithumbfutures.com/api/pro/v1/barhist?symbol=BTC-PERP&interval=1
Sample response
{
"code": 0,
"data": [{
"m": "bar",
"s": "BTC-PERP",
"data": {
"c": "9700.00",
"h": "9700.00",
"i": "1",
"l": "9700.00",
"o": "9700.00",
"ts": 1581981600000,
"v": "0.0000"
}
},
{
"m": "bar",
"s": "BTC-PERP",
"data": {
"c": "9700.00",
"h": "9700.00",
"i": "1",
"l": "9700.00",
"o": "9700.00",
"ts": 1581981660000,
"v": "0.0000"
}
}
]
}
HTTP Request
GET /api/pro/v1/barhist
This API returns a list of bars, with each contains the open/close/high/low prices of a symbol for a specific time range.
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol | String |
Yes | Contract Symbol | e.g. "BTC-PERP" |
interval | String |
Yes | a string representing the interval type. | |
to | Long |
No | Timestamp | UTC timestamp in milliseconds. If not provided, this field will be set to the current time. |
from | Long |
No | Timestamp | UTC timestamp in milliseconds. |
n | Int |
No | > 0 | default 10, number of bars to be returned, this number will be capped at 500 |
The requested time range is determined by three parameters - to
, from
, and n
- according to rules below:
from
/to
each specifies the start timestamp of the first/last bar.to
is always honored. If not provided, this field will be set to the current system time.- For
from
andto
:- if only
from
is provided, then the request range is determined by[from, to]
, inclusive. However, if the range is too wide, the server will increasefrom
so the number of bars in the response won't exceed 500. - if only
n
is provided, then the server will return the most recentn
data bars to timeto
. However, ifn
is greater than 500, only 500 bars will be returned. - if both
from
andn
are specified, the server will pick one that returns fewer bars.
- if only
Response
Name | Type | Description | Sample Value |
---|---|---|---|
m | String | message type | "bar" |
s | String | symbol | "BTC-PERP" |
data:ts | Long | bar start time in milliseconds | 1581981660000 |
data:i | String | interval | "1" |
data:o | String | open price | |
data:c | String | close price | |
data:h | String | high price | |
data:l | String | low price | |
data:v | String | volume in quote asset |
Code Sample
Please refer python code to [get bar history]{https://github.com/bithumbfutures/bithumb-futures-api-demo/blob/master/python/query-bar-hist.py}
Order Book (Depth)
Request for Order Book (Depth) Data
curl -X GET https://bithumbfutures.com/api/pro/v1/depth?symbol=BTC-PERP
Order Book (Depth) Data - Sample response
{
"code": 0,
"data": {
"m": "depth-snapshot",
"symbol": "BTC-PERP",
"data": {
"seqnum": 10190,
"ts": 1581958512759,
"asks": [
["10010", "0.0018"],
["10100", "0.001"],
],
"bids": [
["9600", "0.002"],
["9500", "0.01"],
]
}
}
}
HTTP Request
GET /api/pro/v1/depth
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol |
String | Yes | Valid symbol supported by exchange |
Response Content
data
field in response contains depth data and meta info.
Name | Type | Description |
---|---|---|
m |
String |
"depth-snapshot" |
symbol |
String |
e.g. "BTC-PERP" |
data |
Json |
actual bid and ask info. See below for detail. |
Actual depth data in data
section:
Name | Type | Description |
---|---|---|
seqnum |
Long |
a sequence number that is guaranteed to increase for each symbol. |
ts |
Long |
UTC timestamp in milliseconds when the message is generated by the server |
asks |
[String, String] |
pair of price and size of ask levels |
bids |
[String, String] |
pair of price and size of bid levels |
Demo Sample
Pleas refer to python code to take depth snapshot
Ticker
Ticker for one product
// curl -X GET 'https://bithumbfutures.com/api/pro/v1/ticker?symbol=BTC-PERP'
{
"code": 0,
"data": {
"symbol": "BTC-PERP",
"open": "9000",
"close": "9000",
"high": "9000",
"low": "9000",
"volume": "1.02",
"ask": [ "9500", "0.4" ],
"bid": [ "8500", "0.1" ]
}
}
List of Tickers for one or multiple products
// curl -X GET "https://bithumbfutures.com/api/pro/v1/ticker?symbol=BTC-PERP,"
{
"code": 0,
"data": [
{
"symbol": "BTC-PERP",
"open": "9000",
"close": "9000",
"high": "9000",
"low": "9000",
"volume": "1.02",
"ask": [ "9500", "0.4" ],
"bid": [ "8500", "0.1" ]
}
]
}
HTTP Request
GET api/pro/v1/ticker
You can get summary statistics of one or multiple symbols with this API.
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol |
String |
No | you may specify one, multiple, or all symbols of interest. See below. |
This API endpoint accepts one optional string field symbol
:
- If you do not specify
symbol
, the API will responde with tickers of all symbols in a list. - If you set
symbol
to be a single symbol, such asBTC-PERP
, the API will respond with the ticker of the target symbol as an object. If you want to wrap the object in a one-element list, append a comma to the symbol, e.g.BTC-PERP,
. - (Not supported yet) You shall specify
symbol
as a comma separated symbol list, e.g.BTC-PERP,ETH-PERP
. The API will respond with a list of tickers.
Respond Content
The API will respond with a ticker object or a list of ticker objects, depending on how you set the symbol
parameter.
Each ticker object contains the following fields:
Field | Type | Description |
---|---|---|
symbol |
String |
|
open |
String |
the traded price 24 hour ago |
close |
String |
the last traded price |
high |
String |
the highest price over the past 24 hours |
low |
String |
the lowest price over the past 24 hours |
volume |
String |
the total traded volume in quote asset over the paste 24 hours |
ask |
[String, String] |
the price and size at the current best ask level |
bid |
[String, String] |
the price and size at the current best bid level |
Code Sample
Please refer to python code to [query ticker info]{https://github.com/bithumbfutures/bithumb-futures-api-demo/blob/master/python/query-ticker.py}
Market Trades
Request
curl -X GET /api/pro/v1/trades?symbol=BTC-PERP
Sample response
{
"code": 0,
"data": {
"m": "trades",
"symbol": "BTC-PERP",
"data": [{
"bm": true,
"p": "9800",
"q": "0.0006",
"seqnum": 180143985094828828,
"ts": 1581955026966
},
{
"bm": true,
"p": "9700",
"q": "0.00310",
"seqnum": 180143985094828975,
"ts": 1581957024856
}
]
}
}
HTTP Request
GET /api/pro/v1/trades
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol |
String | Yes | Valid symbol supported by exchange | |
n |
Int | No | any positive integer, capped at 100 | number of trades to return. |
Response Content
data
field in response contains trade data and meta info.
Name | Type | Description
m
| String
| trades
symbol
| String
| trade symbol
data
| Json
| A list of trade record; see below for detail.
Trade record information in data
:
Name | Type | Description |
---|---|---|
seqnum |
Long |
the sequence number of the trade record. seqnum is always increasing for each symbol, but may not be consecutive |
p |
String |
trade price in string format |
q |
String |
trade size in string format |
ts |
Long |
UTC timestamp in milliseconds |
bm |
Boolean |
If true, the maker of the trade is the buyer. |
Code Sample
Please refer to python code to [query trades]{https://github.com/bithumbfutures/bithumb-futures-api-demo/blob/master/python/query-trades.py}
Reference Prices
Reference Prices for Futures Collateral Assets
curl -X GET https://bithumbfutures.com/api/pro/v1/futures/ref-px
Permissions
This API is public.
HTTP Request
GET /api/pro/v1/futures/ref-px
Futures Market Data
Futures Market Data for one Contract
# if only one symbol is provided, the API will respond with a single object
curl -X GET https://bithumbfutures.com/api/pro/futures/market-data?symbol=BTC-PERP
Sample Resonse
{
"code": 0,
"data": {
"symbol": "BTC-PERP",
"openInterest": "9000",
"sourceTime": 1579876668235,
"fundingRate": "0.001",
"fundingPaymentFlag": false,
"nextFundingPaymentTime": 1579874400000,
"indexPrice": "8495.01",
"markPrice": "8493.50"
}
}
Futures Market Data for one or multiple Contracts
# Appending a comma (,) and the API will respond with a list of one or more objects
curl -X GET https://bithumbfutures.com/api/pro/futures/market-data?symbol=BTC-PERP,
Sample Resonse
{
"code": 0,
"data": [
{
"symbol": "BTC-PERP",
"openInterest": "9000",
"sourceTime": 1579876668235,
"fundingRate": "0.001",
"fundingPaymentFlag": false,
"nextFundingPaymentTime": 1579874400000,
"indexPrice": "8495.01",
"markPrice": "8493.50"
}
]
}
Permissions
This API is public.
HTTP Request
GET /api/pro/v1/futures/market-data
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol | String |
No | symbols separated by comma |
By default, the API returns data for all contracts traded on the exchange. You can provide an optional
parameter symbol
to taylor the result to a specific subset of contracts.
In most cases, this API will return a list of objects. However, it you set symbol
to a single contract,
such as symbol=BTC-PERP
, the API will return the object itself instead. If you want the response to alaways
be a list of objects, append a comma (e.g. symbol=BTC-PERP,
).
Response Content
Name | Type | Description | Sample Value |
---|---|---|---|
symbol | String |
Contract symbol | "BTC-PERP" |
openInterest | String |
Open interest | "9000" |
sourceTime | Long |
UTC timestamp when market data is generated | 1579876668235 |
fundingRate | String |
Current funding rate | "0.01" |
fundingPaymentFlag | Boolean |
false |
|
nextFundingPaymentTime | Long |
UTC timestamp of the next timestamp | 1579874400000 |
indexPrice | String |
the index price | "8495.01" |
markPrice | String |
the mark price | "8493.50" |
Futures Funding Rates
Futures Funding Rates
curl -X GET https://bithumbfutures.com/api/pro/v1/futures/funding-rates
{
"code": 0,
"data": {
"page": 1,
"pageSize": 20,
"hasNext": true,
"data": [
{
"timestamp": 1578182100000,
"symbol": "BTC-PERP",
"fundingRate": "0.001"
},
{
"timestamp": 1578181800000,
"symbol": "BTC-PERP",
"fundingRate": "0.001"
},
...
]
}
}
Permissions
This API is public.
HTTP Request
GET /api/pro/v1/futures/funding-rates
Response Content
Name | Type | Description |
---|---|---|
timestamp | Long |
|
symbol | String |
|
fundingRate | String |
Private Data
Account Info
Account Info - Sample response:
{
"code": 0,
"data": {
"accountGroup": 0,
"email": "yyzzxxz@email.com",
"futuresAccount": [
"futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q"
],
"tradePermission": true,
"transferPermission": true,
"viewPermission": true,
"userUID": "U0866943712"
}
}
Permissions
This API doesn't need any permission to access.
HTTP Request
GET /api/pro/v1/info
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+info
Obtain the account information.
You can obtain your accountGroup
from this API, which you will need to include in the URL for all your private RESTful requests.
Response Content
Name | Type | Description |
---|---|---|
accountGroup | Int |
non-negative integer |
String |
||
futuresAccount | List[String] |
contains a list of your futures accounts. At the moment, the list should contain exactly one element. |
viewPermission | Boolean |
|
tradePermission | Boolean |
|
transferPermission | Boolean |
|
userUID | String |
an unique id associated with user |
You will need accountGroup
to access most private APIs. It never changes value for each account.
Collateral Balance
Futures Collateral Balance
{
"code": 0,
"data": [
{
"asset": "BTC",
"totalBalance": "0",
"availableBalance": "0",
"maxTransferrable": "0",
"priceInUSDT": "8455.705"
},
{
"asset": "USDT",
"totalBalance": "0",
"availableBalance": "0",
"maxTransferrable": "0",
"priceInUSDT": "1"
}
]
}
Permissions
You need view permission to access this API.
HTTP Request
GET <account-group>/api/pro/v1/futures/collateral-balance
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+futures/collateral-balance
Request Parameters
You don't need to specify any parameter for this API.
Response Content
Name | Type | Description | Sample Response |
---|---|---|---|
asset | String |
asset code | "USDT" |
totalBalance | String |
total balance | "0" |
availableBalance | String |
available balance | "0" |
maxTransferrable | String |
maximum transferrable amount | "0" |
priceInUSDT | String |
reference price in USDT | "1" |
Code Sample
Please refer to python code to query funding payments
Contract Position
Contract Position
{
"code": 0,
"data": [
{
"symbol": "BTC-PERP",
"position": "0.0012",
"positionNotional": "9.392250374",
"breakevenPrice": "7921.3512875",
"estLiquidationPrice": "7075.175014796",
"positionPnl": "-0.11337117",
"collateralInUse": "12.194125037",
"maxBuyOrderSize": "0.000225911",
"maxSellOrderSize": "0.016837925",
"maxBuyNotional": "1.768180713",
"maxSellNotional": "131.788346455",
"indexPrice": "7818.4225",
"markPrice": "7826.875312457"
}
]
}
Permissions
You need view permission to access this API.
HTTP Request
GET <account-group>/api/pro/futures/position
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+futures/position
Request Parameters
You don't need to specify any parameter for this API.
Response Content
Name | Type | Description | Sample Response |
---|---|---|---|
symbol | String |
contract symbol | "BTC-PERP" |
breakevenPrice | String |
break-even price | "12805.265370586" |
estLiquidationPrice | String |
estimated liquidation price | "16365.898288993" |
collateralInUse | String |
collateral in Use (in USDT) | "1350.314802427" |
maxBuyOrderSize | String |
maximum quantity allowed to buy (deprecated, use maxBuyNotional) | "44.612137464" |
maxSellOrderSize | String |
maximum quantity allowed to sell (deprecated, use maxSellNotional) | "38.962207464" |
maxBuyNotional | String |
maximum notional allowed to buy | "44.612137464" |
maxSellNotional | String |
maximum notional allowed to sell | "38.962207464" |
position | String |
contract position | "-2.8535" |
positionNotional | String |
contract position notional value in USDT | "-27006.296048541" |
positionPnl | String |
contract position profit/loss in USDT | "9533.528686427" |
indexPrice | String |
underlying index price | "7818.4225" |
markPrice | String |
contract mark price | "7826.875312457" |
Code Sample
Please refer to python code to query funding payments
Account Risk Profile
Account Risk Profile
{
"code": 0,
"data": {
"accountMarginRate": "16.606386637",
"accountValue": "13117.362712384",
"accountMaxLeverage": "20",
"collateral": "12810.31775",
"collateralInUse": "38.570454939",
"effectiveCollateral": "12810.31775",
"freeCollateral": "12771.74729506",
"currentLeverage": "0.060217795",
"effectiveInitialMarginRate": "0.05",
"effectiveMaintenanceMarginRate": "0.006",
"effectivePositionNotional": "771.409098784",
"positionNotional": "771.409098784",
"unsettledPnl": "137.126662384",
"settledPnl": "0",
"unrealizedPnlTotal": "137.126662384",
"takeoverMarginRate": "0.003",
"walletBalance": "12980.23605"
}
}
You can obtain the status of the overall account from this API.
Permissions
You need view permission to access this API.
HTTP Request
GET <account-group>/api/pro/futures/risk
Response Content
Name | Type | Description |
---|---|---|
accountMarginRate | String |
account marging rate |
accountMaxLeverage | String |
account maximum leverage |
currentLeverage | String |
account current leverage |
effectiveInitialMarginRate | String |
|
effectiveMaintenanceMarginRate | String |
|
takeoverMarginRate | String |
the minimum margin rate an account must be above to avoid been taking over |
walletBalance | String |
total USDT value of all collaterals |
collateral | String |
account total collateral value in USDT |
collateralInUse | String |
amount of collateral already in use |
effectiveCollateral | String |
|
freeCollateral | String |
|
positionNotional | String |
|
effectivePositionNotional | String |
|
unsettledPnl | String |
unsettled PnL that will be rolled into settled PnL. |
settledPnl | String |
settled profit/loss (PnL) |
Collateral
You can only increase your exposure if have free collateral. You shall post more collaterals by depositing one or more collateral assets to you account.
Notional
Profit/Loss
Funding Payment History
Funding Payment History
{
"code": 0,
"data": {
"data": [
{
"fundingRate": "0.001",
"paymentInUSDT": "26.800171872",
"symbol": "BTC-PERP",
"timestamp": 1580328000000
},
{
"fundingRate": "-0.001",
"paymentInUSDT": "-26.740689873",
"symbol": "BTC-PERP",
"timestamp": 1580324400000
}
],
"hasNext": false,
"page": 1,
"pageSize": 20
}
}
Permissions
You need view permission to access this API.
HTTP Request
GET <account-group>/api/pro/v1/futures/funding-payments
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+futures/funding-payments
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol | String |
No | symbols separated by comma | |
page | Int |
No | zero or positive integer | |
pageSize | Int |
No | positive integer |
Response Content
The response contains a list of funding payment records along with meta data for the pagination.
Each funding payment record contains the following fields:
Name | Type | Description | Sample Response |
---|---|---|---|
fundingRate | String |
funding rate applied | "0.001" |
paymentInUSDT | String |
funding payment in USDT | "26.800171872" |
symbol | String |
contract symbol | "BTC-PERP" |
timestamp | Long |
UTC Timestamp in milliseconds | 1580328000000 |
Code Sample
Please refer to python code to query funding payments
Deposit/Withdrawal History
Deposit/Withdrawal History
{
"code": 0,
"data": {
"data": [
{
"asset": "USDT",
"requestId": "cOagK5svg9ookf3cJBidbcdVbnW1daDl",
"amount": "119",
"commission": "0",
"destAddress": {"address": "0x5dc4923bd61bea0f5ecfb0db7de6b137060360bd"},
"networkTransactionId": "0x473f725ae197ea8e2828700cee7d2c9b2fe50f74c41ba38c2928d5ebfd7400cd",
"numConfirmations": 20,
"numConfirmed": 20,
"status": "confirmed",
"time": 1580657103000,
"transactionType": "deposit"
}
],
"page" : 1,
"pageSize": 20,
"hasNext" : false
}
}
You can obtain history of wallet deposit/withdrawal transactions via this API.
Permissions
You need view permission to access this API.
HTTP Request
GET /api/pro/wallet/transactions
You don't need to specify <account-group>
for this API.
Request Parameters
You can specify the following parameters:
Name | Type | Default | Description |
---|---|---|---|
asset | Optional[Int] |
Null | asset code |
page | Optional[Int] |
1 | page number, must be greater than 0. |
pageSize | Optional[Int] |
20 | page size, must be greater than 0. |
startTs | Optional[Long] |
Time.Min | start of the query range, UTC timestamp in milliseconds |
endTs | Optional[Long] |
Time.Max | end of the query range, UTC timestamp in milliseconds |
txType | Optional[String] |
Null | the transaction type filter: deposit / withdrawal |
Response Content
The data
field of the API response contains the paginated historical data. All records are sorted in reverse chronological order.
Name | Type | Description |
---|---|---|
page | Int |
page number, must be greater than 0. |
pageSize | Int |
page size, must be greater than 0. |
hasNext | Boolean |
if True, there are more records to show |
data | List[Object] |
a list of transaction records. See below for details |
Each transaction record contains the following fields:
Name | Type | Description |
---|---|---|
asset | String |
asset code |
requestId | String |
an unique identifier for the transaction |
amount | String |
amount in transaction |
commission | String |
commission charged |
destAddress | Object |
destination address ID, it usually contains an address field and an optional destTag field |
networkTransactionId | String |
the id/hash of the transaction, for transactions among exchange users, this field is "-" |
numConfirmations | Int |
deposit will be viewd as final after the number of blocks confirmed reaches this value |
numConfirmed | Int |
currently number of blocks confirmed |
status | String |
reviewing / pending / confirmed / rejected |
time | Long |
UTC Timestamp in milliseconds |
transactionType | String |
deposit / withdrawal |
Code Sample
please refer to python code to cancel batch order
Transactions History
Sample Resonse
{
"code": 0,
"data": {
"data": [
{
"time": 1574640000000,
"asset": "BTC",
"amount": "-0.129",
"txType": "Takeover",
"status": "SUCCESS",
"requestId": "09naslvPvsSLxl9A"
}
],
"hasNext": false,
"page": 1,
"pageSize": 10
}
}
Permissions
You need view permission to access this API.
HTTP Request
GET /api/pro/v1/futures/tx-history
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+futures/tx-history
HTTP Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
page | Int |
No | page number, starting from 1 | |
pageSize | Int |
No | page size, must be positive |
Response
This API returns paginated data.
Name | Type | Description |
---|---|---|
time | Long |
UTC timestamp in milliseconds |
asset | String |
asset code, e.g. BTC |
amount | String |
changed amount |
txType | String |
transaction type, such as PositionInjection, Takeover, etc |
status | String |
SUCCESS / FAIED |
requestId | String |
A unique identifier for this balance change event |
Currently, there are four possible values for status:
Takeover
CollateralConversion
PositionInjection
PositionInjectionBLP
Code Sample
Please refer to python code to get open orders
Order
Place an Order
Place Order - Successful ACK Response (Status 200, code 0)
{
"code": 0,
"data": {
"ac": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "place-order",
"info": {
"id": "16e607e2b83a8bXHbAwwoqDo55c166fa",
"orderId": "16e85b4d9b9a8bXHbAwwoqDoc3d66830",
"orderType": "Market",
"symbol": "BTC-PERP",
"timestamp": 1573576916201
},
"status": "Ack"
}
}
Place Order with
ACCEPT
respInst
{
"id": "iGwzbzWxxcHwno4b8VCvh8aaYCJaPALm",
"time": 1575403713964,
"symbol": "BTC-PERP",
"orderPrice": "7289.0",
"orderQty": "0.00082",
"orderType": "limit",
"side": "sell",
"respInst": "ACCEPT"
}
Successful ACCEPT Response (Status 200, code 0)
{
"code": 0,
"data": {
"ac": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "place-order",
"info": {
"avgPx": "0",
"cumFee": "0",
"cumFilledQty": "0",
"errorCode": "",
"feeAsset": "USDT",
"lastExecTime": 1575573998500,
"orderId": "a16ed787462fU9490877774N4KBHIVN0",
"orderQty": "0.1",
"orderType": "Limit",
"price": "7019",
"seqNum": 2323407894,
"side": "Buy",
"status": "New",
"stopPrice": "",
"symbol": "BTC-PERP",
"execInst": "NULL_VAL"
},
"status": "ACCEPT"
}
}
Place Order with
DONE
respInst
{
"id": "UHTe3uVB0KhNGatoRS10YgABwHW0fCYn",
"time": 1575348906131,
"symbol": "BTC-PERP",
"orderQty": "0.00082",
"orderType": "market",
"side": "buy",
"respInst": "DONE"
}
Successful DONE Response (Status 200, code 0)
{"code": 0,
"data": {
"ac": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "place-order",
"info": {
"avgPx": "7399.99",
"cumFee": "0.003296696",
"cumFilledQty": "0.1",
"errorCode": "",
"feeAsset": "USDT",
"id": "ROunD0hpprO2KEgkVK30FOIpPK3zuGGh",
"lastExecTime": 1575646514077,
"orderId": "a16edbd9aefaU9490877774pPK3zuGGh",
"orderQty": "0.1",
"orderType": "Market",
"price": "",
"seqNum": 2348421435,
"side": "Sell",
"status": "Filled",
"stopPrice": "",
"symbol": "BTC-PERP",
"execInst": "NULL_VAL"
},
"status": "DONE"}}
Place Order - Error Response (Status 200, code 300011)
{
"code": 300011,
"ac": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "place-order",
"message": "Not Enough Account Balance",
"reason": "INVALID_BALANCE",
"status": "Err",
"info": {
"id": "JkpnjJRuBtFpW7F7PWDB7uwBEJtUOISZ",
"symbol": "BTC-PERP"
}
}
Place a new order.
Permissions
You need trade permission to access this API.
HTTP Request
POST <account-group>/api/pro/v1/futures/order
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol | String | Yes | ||
time | Long | Yes | milliseconds since UNIX epoch in UTC | We do not process request placed more than 30 seconds ago. |
orderQty | String | Yes | Order size. Please set scale properly for each symbol. | |
orderType | String | Yes | ["market", "limit"] | Order type |
side | String | Yes | ["buy", "sell"] | |
id | String | No | >=9 chars(letter and digit number only) | Optional but recommended. We echo it back to help you match response with request. |
orderPrice | String | No | The limit price for limit order. Please set price scale properly. | |
stopPrice | String | No | Trigger price of stop limit order | |
postOnly | Boolean | No | [true, false] | |
timeInForce | String | No | ["GTC", "IOC"] | GTC: good-till-canceled; IOC: immediate-or-cancel. GTC by default. |
respInst | String | No | ["ACK", "ACCEPT", "DONE"] | Response instruction. Refer to "Response" below. "ACK" by default. |
The table below shows how to correctly configure order of different types: (o - required, x - optional)
Name | Market | Limit | StopMarket | StopLimit |
---|---|---|---|---|
id | x | x | x | x |
time | o | o | o | o |
symbol | o | o | o | o |
orderPrice | o | o | ||
orderQty | o | o | o | o |
orderType | o | o | o | o |
side | o | o | o | o |
postOnly | x | |||
stopPrice | o | o | ||
timeInForce | x |
Order Request Criteria
When placing a new limit order, the request parameters must meet all criteria defined in the Products API:
- The order notional must be within range
[minNotional, maxNotional]
. For limit orders, the order notional is defined as the product oforderPrice
andorderQty
. orderPrice
andstopPrice
must be multiples oftickSize
.orderQty
must be a multiple oflotSize
.
Response
In "Err" response, id is the id provided by user when placing order; for other responses, orderId is the id generated by server following "Order id generation method" above, and this is the id you should provide for future order query or cancel.
In case you want to cancel an order before response from server, you could figure out the orderId following Order id generation method above.
ACK
Response with 0 code
and status Ack
to indicate new order request received by our server and passed some basic order field check. This is the default response type. If awaiting async order (ACCEPT or DONE) numbers exceeds capacity 1000, then the rest async order will be ACK automatically.
data
schema:
Name | Type | Description |
---|---|---|
avgPx | String |
average fill price |
cumFee | String |
cumulated filled comission |
cumFilledQty | String |
cumulated filled qty |
errorCode | String |
Could be empty |
feeAsset | String |
Fee asset, e.g, USDT |
id | String |
id from request |
lastExecTime | String |
latest execution timestamp |
orderId | String |
order id |
orderQty | String |
order quantity |
orderType | String |
order type |
price | String |
order price |
seqNum | Long |
sequence number |
side | String |
order side |
status | String |
order status |
stopPrice | String |
stop price(could be empty) |
symbol | String |
symbol |
execInst | String |
execution instruction, POST for Post-Only orders, Liquidation for forced-liquidation orders, and NULL_VAL otherwise. |
ACCEPT
Response with 0 code
and status ACCEPT
to indicate new order request is accepted by our match engine. Return normal 'Ack' response if no 'New' status update within 5 seconds. Order status
in data
could be New
, or PendingNew
.
DONE
Response with 0 code
and status Done
to indicate the order request is partially filled, fully filled, or rejected by matching engine. Return normal 'Ack' response if no order status update within 5 seconds. Order status
in data
could be Filled
, PartiallyFilled
, Cancelled
, or Reject
, and so on.
ERR
Response with code
other than 0 and status Err
to provide detailed error information on the order request.
Name | Type | Description |
---|---|---|
code | Long |
non-zero value to indicate error |
ac | String |
FUTURES |
accountId | String |
account id |
action | String |
place-order |
message | String |
detail error message |
reason | String |
error info code, e.g. "INVALID_ORDER_ID" |
status | String |
"Err" |
info | Json |
See below for details |
info
schema:
Name | Type | Description |
---|---|---|
symbol | String |
symbol |
id | String |
id from request if provided |
Cancel an Order
Cancel Order - Successful ACK Response (Status 200, code 0)
{
"code": 0,
"data": {
"accountId": "fut1FfjKA3W1L7XZOipGKZNFBb34GRQ3",
"ac": "CASH",
"action": "cancel-order",
"status": "Ack",
"info": {
"id": "sPWweX8baCYeFsKdmqZEmHdpliWaJuGm",
"orderId": "kIXfMP72VfFDp653WoNqNGcpZCK9W7ts",
"orderType": "", // could be empty
"symbol": "BTC-PERP",
"timestamp": 1573596082932
}
}
}
Cancel Order - Error Response (Status 200, code 0)
{
"code": 300006,
"accountId": "fut1FfjKA3W1L7XZOipGKZNFBb34GRQ3",
"ac": "CASH",
"action": "cancel-order",
"status": "Err",
"message": "Invalid Client Order Id: ku30AehuWoHzMeyGEAS8heeDXpb1heOS",
"reason": "INVALID_ORDER_ID",
"info": {
"id": "ku30AehuWoHzMeyGEAS8heeDXpb1heOS",
"symbol": "BTC-PERP"
}
}
Cancel an existing open order.
Permissions
You need trade permission to access this API.
HTTP Request
DELETE <account-group>/api/pro/v1/futures/order
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
id | String | Yes | 32 chars(letter and digit number only) | Please generate unique ID for each trade; we will echo it back to help you identify the response. |
orderId | String | Yes | 32 chars order id responded by server when place order | |
symbol | String | Yes | ||
time | Long | Yes | milliseconds since UNIX epoch in UTC | We do not process request placed more than 30 seconds ago. |
Response
ACK
Response with status "Ack" to indicate the cancel order request is received by server. And you should use provided "orderId" to check cancel status in the future; we also echo back id from your request for reference purpose.
ERR
Response with status "Err" to indicate there is something wrong with the cancel order request. We echo back the coid field in your request.
Place Batch Orders
Place Batch Orders - Request Body
{
"orders": [
{
"id" : "ygpBSzn1ZKOGDQqwhwi9Jo0QWhMJIi4e",
"orderPrice" : "6000",
"orderQty" : "1",
"orderType" : "limit",
"side" : "buy",
"symbol" : "BTC-PERP",
"time" : 1582140876351,
"timeInForce": "GTC"
},
{
"id" : "FhvyPfmwUZjS4qFfPeABbgAnHmaUnphA",
"orderPrice" : "5000",
"orderQty" : "1",
"orderType" : "limit",
"side" : "buy",
"symbol" : "BTC-PERP",
"time" : 1582140876351,
"timeInForce": "GTC"
}
]
}
Place Batch Orders - Successful ACK Response (Status 200, code 0)
{
"code": 0,
"data": {
"ac": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "batch-place-order",
"info": [
{
"id" : "ygpBSzn1ZKOGDQqwhwi9Jo0QWhMJIi4e",
"orderId" : "a1705ef9d2a25362614103sdUuPlzMW",
"orderType": "Limit",
"symbol" : "BTC-PERP",
"timestamp": 1582141396352
},
{
"id" : "FhvyPfmwUZjS4qFfPeABbgAnHmaUnphA",
"orderId" : "a1705ef9d2a25362614103Pf0MooywV",
"orderType": "Limit",
"symbol" : "BTC-PERP",
"timestamp": 1582141396361
}
],
"status": "Ack"
}
}
Place Batch Orders - Error Response (Status 200, code 0)
{
"ac": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "batch-place-order",
"code": 300013,
"info": [
{
"code" : 300013,
"id" : "ygpBSzn1ZKOGDQqwhwi9Jo0QWhMJIi4e",
"message": "Some invalid order in this batch.",
"reason" : "INVALID_BATCH_ORDER",
"symbol" : "BTC-PERP"
},
{
"code" : 300001,
"id" : "FhvyPfmwUZjS4qFfPeABbgAnHmaUnphA",
"message": "Price is too low from market price.",
"reason" : "INVALID_PRICE",
"symbol" : "BTC-PERP"
}
],
"message": "Batch Order failed, please check each order info for detail.",
"reason": "INVALID_BATCH_ORDER",
"status": "Err"
}
Place multiple orders in a batch. If some order in the batch failed our basic check, then the whole batch request fail.
You may submit up to 10 orders at a time. Server will respond with error if you submit more than 10 orders.
HTTP Request
POST <account-group>/api/pro/v1/futures/order/batch
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order/batch
Response
ACK
0 for code
and status Ack
to indicate the batch order request is accepted by server. Field "info" includes server generated "order id" for each order in the batch request, and this is the id you should use for future status query.
data
schema:
Name | Type | Description |
---|---|---|
ac |
String |
FUTURES |
accountId |
String |
account Id |
action |
String |
batch-place-order |
status |
String |
Ack |
info |
List |
See below for detail |
info
schema:
Name | Type | Description |
---|---|---|
id |
String |
echo back the id in request |
orderId |
String |
server assigned order Id for this single order |
orderType |
String |
order type |
symbol |
String |
symbol in request |
timestamp |
Long |
server received timestamp |
ERR
Non 0 code
and status ERR
to indicate the batch order request is accepted by server. Field info
includes detailed order information to explain why the batch request fail for each individual order. "order id" is original order id provided by user for each order.
Error schema
Name | Type | Description |
---|---|---|
code |
Long |
0 |
ac |
String |
FUTURES |
accountId |
String |
account Id |
action |
String |
batch-place-order |
message |
String |
error message detail |
reason |
String |
short error message |
status |
String |
Err |
info |
List |
See below for detail |
info
schema:
Name | Type | Description |
---|---|---|
code |
Long |
0 |
id |
String |
echo id in request |
orderId |
String |
empty |
message |
String |
error message detail |
reason |
String |
short error message |
symbol |
String |
symbol in order |
Code Sample
Please refer to python code to place batch order
Cancel Batch Orders
Cancel Batch Orders - Request Body
{
"orders": [
{
"orderId": "a1705f147f715362614103eMn3z3tpi",
"symbol": "BTC-PERP",
"time": 1582143186943
},
{
"orderId": "a1705f147f715362614103tKdqi2kfP",
"symbol": "BTC-PERP",
"time": 1582143186943
}
]
}
Cancel Batch Orders - Successful ACK Response (Status 200, code 0)
{
"code": 0,
"data": {
"ac": "CASH",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "batch-cancel-order",
"status": "Ack",
"info": [
{
"id": "0a8bXHbAwwoqDo3b485d7ea0b09c2cd8",
"orderId": "16e61d5ff43s8bXHbAwwoqDo9d817339",
"orderType": "NULL_VAL",
"symbol": "BTC/USDT",
"timestamp": 1573619097746
},
{
"id": "0a8bXHbAwwoqDo7d303e2edf6c26d1be",
"orderId": "16e61adeee5a8bXHbAwwoqDo100e364e",
"orderType": "NULL_VAL",
"symbol": "ETH/USDT",
"timestamp": 1573619098342
}
]
}
}
Cancel Batch Orders - Error Response (Status 200, code 0)
{
"code": 300013,
"ac": "CASH",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"action": "batch-place-order",
"message": "Batch Order failed, please check each order info for detail.",
"reason": "INVALID_BATCH_ORDER",
"status": "Err",
"info": [
{
"code": 300006,
"id": "NUty15oXcNt9JAngZ1D6q6jY15LOpKPC",
"orderId": "16e61d5ff43s8bXHbAwwoqDo9d817339",
"message": "The order is already filled or canceled.",
"reason": "INVALID_ORDER_ID",
"symbol": ""
},
{
"code": 300006,
"id": "mpoL0q8cheL8PL2UstJFRzp6yuPk1sGc",
"orderId": "16e61adeee5a8bXHbAwwoqDo100e364e",
"message": "The order is already filled or canceled.",
"reason": "INVALID_ORDER_ID",
"symbol": ""
}
]
}
Cancel multiple orders in a batch. If some order in the batch failed our basic check, then the whole batch request failed.
HTTP Request
DELETE <account-group>/api/pro/v1/futures/order/batch
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order/batch
Response
ACK
Response with code
as 0 to indicate batch is successfuly received by server and pass some basic check. data
field explains order ack detail.
Order detail for each order is in info
field list.
data
schema:
Name | Type | Description |
---|---|---|
ac |
String |
CASH , MARGIN |
accountId |
String |
account Id |
action |
String |
cancel-all |
status |
String |
Ack |
info |
List |
See below for detail |
info
schema:
Name | Type | Description |
---|---|---|
id |
String |
echo back the id in request |
orderId |
String |
orderId in request to cancel |
orderType |
String |
empty |
symbol |
String |
symbol in request |
timestamp |
Long |
server received timestamp |
ERR
Response with non 0 code
and status "Err" to explain detailed failure reason for each order in the batch request. Error detail for each order is in info
field.
Error schema
Name | Type | Description |
---|---|---|
code |
Long |
0 |
ac |
String |
CASH , MARGIN |
accountId |
String |
account Id |
action |
String |
batch-cancel-order |
message |
String |
error message detail |
reason |
String |
short error message |
status |
String |
Err |
info |
List |
See below for detail |
info
schema:
Name | Type | Description |
---|---|---|
code |
Long |
0 |
id |
String |
echo id in request |
orderId |
String |
orderId in request to cancel |
message |
String |
error message detail |
reason |
String |
short error message |
symbol |
String |
symbol in order |
Code Sample
please refer to python code to cancel batch order
Cancel All Orders
Cancel All Orders - Successful ACK Response (Status 200, code 0)
{
"code": 0,
"data": {
"ac": "FUTURES",
"accountId": "fut1FfjKA3W1L7XZOipGKZNFBb34GRQ3",
"action": "cancel-all",
"info": {
"id": "",
"orderId": "",
"orderType": "NULL_VAL",
"symbol": "",
"timestamp": 1582144746160
},
"status": "Ack"
}
}
Cancel all current open orders for the account specified, and optional symbol.
HTTP Request
DELETE <account-group>/api/pro/v1/futures/order/all
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order/all
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
symbol | String | No | Valid symbol supported by exchange | If provided, only cancel all orders on this symbol; otherwise, cancel all open orders under this account. |
Response
Response include code
and data
, and status Ack
(in field data
) to indicate cancel all order request is received by server.
data
schema:
Name | Type | Description |
---|---|---|
ac | String |
CASH , MARGIN |
accountId | String |
account Id |
action | String |
cancel-all , |
info | Json |
See below for detail |
info
schema:
Name | Type | Description |
---|---|---|
id | String |
echo back the id in request |
orderId | String |
empty |
orderType | String |
empty |
symbol | String |
symbol in request |
timestamp | Long |
server received timestamp |
Code Sample
Refer to sample python code to cancel all order
Caveat
The server will process the cancel all request with best effort. Orders sent but un-acked will not be canceled. You should rely on websocket order update messages or the RESTful api to obtain the latest status of each order.
List Open Orders
Open Orders - Successful Response (Status 200, code 0)
{
"accountCategory": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"code": 0,
"data": [
{
"avgPx": "0", // Average filled price of the order
"cumFee": "0", // cumulative fee paid for this order
"cumFilledQty": "0", // cumulative filled quantity
"errorCode": "", // error code; could be empty
"feeAsset": "USDT", // fee asset
"lastExecTime": 1576019723550, // The last execution time of the order
"orderId": "s16ef21882ea0866943712034f36d83", // server provided orderId
"orderQty": "0.0083", // order quantity
"orderType": "Limit", // order type
"price": "7105", // order price
"seqNum": 8193258, // sequence number
"side": "Buy", // order side
"status": "New", // order status on matching engine
"stopPrice": "", // only available for stop market and stop limit orders; otherwise empty
"symbol": "BTC-PERP",
"execInst": "NULL_VAL" // execution instruction
}
]
}
This API returns all current open orders for the account specified.
Permissions
You need view permission to access this API.
HTTP Request
GET <account-group>/api/pro/v1/futures/order/open
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order/open
Response
Return a list of order infomation in data
field:
Name | Type | Description |
---|---|---|
avgPx | String |
average fill price |
cumFee | String |
cumulated filled comission |
cumFilledQty | String |
cumulated filled qty |
errorCode | String |
Could be empty |
feeAsset | String |
Fee asset, e.g, USDT |
lastExecTime | String |
latest execution timestamp |
orderId | String |
order id |
orderQty | String |
order quantity |
orderType | String |
order type |
price | String |
order price |
seqNum | Long |
sequence number |
side | String |
order side |
status | String |
order status |
stopPrice | String |
stop price(could be empty) |
symbol | String |
symbol |
execInst | String |
execution instruction, POST for Post-Only orders, Liquidation for forced-liquidation orders, and NULL_VAL otherwise. |
Code Sample
Please refer to python code to get open orders
Change from the previous version:
errorCode
is no longer included in the open order response. It is still included in the historical order query response.
Query Order By ID
Query Order with a single order id - Successful Response (Status 200, code 0)
// request: GET <account-group>/api/pro/v1/futures/order/status?orderId=a1707df66b8fU924549015952eXV1Pnc
{
"ac": "FUTURES",
"accountId": "futob37bbDKmzK6BDIGzufXCtg0MZk3a",
"code": 0,
"data": {
"symbol": "BTC-PERP",
"price": "9000",
"orderQty": "0.001",
"side": "Buy",
"status": "New",
"orderType": "Limit",
"avgPx": "0",
"cumFee": "0",
"cumFilledQty": "0",
"errorCode": "",
"execInst": "NULL_VAL",
"feeAsset": "USDT",
"lastExecTime": 1582661266789,
"orderId": "a1707df66b8fU924549015952eXV1Pnc",
"seqNum": 9327,
"stopPrice": ""
}
}
Query Order with a list of order ids - Successful Response (Status 200, code 0)
// request: GET <account-group>/api/pro/v1/futures/order/status?orderId=a1707df66b8fU924549015952eXV1Pnc,
{
"ac": "FUTURES",
"accountId": "futob37bbDKmzK6BDIGzufXCtg0MZk3a",
"code": 0,
"data": [
{
"symbol": "BTC-PERP",
"price": "9000",
"orderQty": "0.001",
"side": "Buy",
"status": "New",
"orderType": "Limit",
"avgPx": "0",
"cumFee": "0",
"cumFilledQty": "0",
"errorCode": "",
"execInst": "NULL_VAL",
"feeAsset": "USDT",
"lastExecTime": 1582661266789,
"orderId": "a1707df66b8fU924549015952eXV1Pnc",
"seqNum": 9327,
"stopPrice": ""
}
]
}
Query order status, either open or history order.
HTTP Request
GET <account-group>/api/pro/v1/futures/order/status
Request Parameters
Name | Type | Required | Value Range | Description |
---|---|---|---|---|
orderId | String | Yes | a single order id, or multiple order ids separated by , |
The API will respond with a list of objects in the data
field. Each object in the list contains information of a single order. There's one exception, if you
use only a single orderId, the data
field of the API response will be simplified to a single object. If you want the API to respond with a list of only one
object in this case, add a comma ,
to the orderId.
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order/status
Response
Name | Type | Description |
---|---|---|
symbol | String |
symbol |
price | String |
order price |
orderQty | String |
order quantity |
side | String |
order side |
status | String |
order status |
orderType | String |
order type |
avgPx | String |
average fill price |
cumFee | String |
cumulated filled comission |
cumFilledQty | String |
cumulated filled qty |
errorCode | String |
Could be empty |
feeAsset | String |
Fee asset, e.g, USDT |
lastExecTime | String |
latest execution timestamp |
orderId | String |
order id |
seqNum | Long |
sequence number |
stopPrice | String |
stop price(could be empty) |
execInst | String |
execution instruction, POST for Post-Only orders, Liquidation for forced-liquidation orders, and NULL_VAL otherwise. |
Code Sample
Please refer to python code to get order status
Historical Orders
List Current History Orders
Current History Orders - Successful Response (Status 200, code 0)
{
"ac": "FUTURES",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"code": 0,
"data": [
{
"seqNum": 168383,
"symbol": "BTC-PERP",
"side": "Buy",
"avgPx": "9825.235",
"cumFee": "0.080566927",
"cumFilledQty": "0.01",
"errorCode": "",
"execInst": "NULL_VAL",
"feeAsset": "USDT",
"lastExecTime": 1581708299976,
"orderId": "r170452951ca5362614103bbtcpcS7p",
"orderQty": "0.01",
"orderType": "Limit",
"price": "9950.5",
"status": "Filled",
"stopPrice": ""
}
]
}
This API returns all current history orders for the account specified. This API will only respond with most recently closed orders cached by the server. To query the full history, please use the Historical Orders API.
HTTP Request
GET <account-group>/api/pro/v1/futures/order/hist/current
Signature
You should sign the message in header as specified in Authenticate a RESTful Request section.
Prehash String
<timestamp>+order/hist/current
Request Parameters
Name | Type | Required | Description |
---|---|---|---|
n | Int |
No | maximum number of orders to be included in the response |
symbol | String |
No | symbol filter, e.g. "BTC-PERP" |
executedOnly | Boolean |
No | if True , include orders with non-zero filled quantities only. |
Response
Return a list of history orders in "data" field.
WebSocket
Guidelines
General Message Request/Handling Logic from Client Side
- Client usually initiate request with
op
parameter (followed by other required parameters). - Server usually reply message with
m
value to indicate message topic, e.g.,order
,depth
,auth
. - Private data response usually has
accountId
field, such asorder
,balance
; public data response usually containssymbol
field. - Uniquie
id
parameter is recommended for your request. We will echo it back for you to track the requests. (The only exception isdepth-snapshot
, we do not includeid
)
WebSocket Request
WSS <account-group>/api/pro/v1/stream
In order to authorize the session you must include <account-group>
in the URL. Without <account-group>
, you can
only subscribe to public data.
Keep the Connection Alive via Ping/Pong
In order to keep the websocket connection alive, you have two options, detailed below.
Method 1: Responding to Server ping messages
Method 1. keep the connection alive by responding to Server pushed ping message
<<< { "m": "ping", "hp": 3 } # Server pushed ping message
>>> { "op": "pong" } # Client responds with pong
If the server doesn't receive any client message after a while, it will send a ping
message to the client. Once the ping
message is received,
the client should promptly send a pong
message to the server. If you missed two consecutive ping
messages, the session will be disconnected.
Server Ping Message Schema
Name | Type | Description |
---|---|---|
op | String |
ping |
hp | Int |
health point: when this value decreases to 0, the session will be disconnected. |
Method 2: Sending ping messages to Server
Method 2. keep the connection alive by sending ping message to the server
>>> { "op": "ping" } # Client initiated ping message (every 30 seconds)
<<< { "m":"pong", "code":0, "ts":1574260701259, "hp": 2 } # Server responds to client ping
You can also send ping
message to the server every 15 seconds to keep the connection alive. The server will stop sending ping
message
for 30 seconds if a client initiated ping
message is received.
Server Pong Message Schema
Name | Type | Description |
---|---|---|
m | String |
pong |
code | Int |
error code, for the pong mesage, the error code is always 0 (success) |
ts | Long |
server time in UTC miliseconds |
hp | Int |
health point: when this value decreases to 0, the session will be disconnected. |
WebSocket Authentication
You must authenticate the websocket session in order to recieve private data and send account specific requests (e.g. placing new orders).
You have two options to authenticate a websocket session.
- by adding authentication data in the request header when connecting to websocket.
- by sending an
op:auth
message to the server after you have connected to websocket.
Once you successfully connect to the websocket, you will receive a connected
message:
- for authenticated websocket session:
{"op":"connected","type":"auth"}
- for unauthenticated websocket session:
{"op":"connected","type":"unauth"}
If the session is disconnected for some reason, you will receive a disconnected
message:
{"m":"disconnected","code":100005,"reason":"INVALID_WS_REQUEST_DATA","info":"Session is disconnected due to missing pong message from the client"}
Method 1 - WebSocket Authentication with Request Headers
Authenticate with Headers
# # Install wscat from Node.js if you haven't
# npm install -g wscat
APIPATH=stream
APIKEY=BclE7dBGbS1AP3VnOuq6s8fJH0fWbH7r
SECRET=fAZcQRUMxj3eX3DreIjFcPiJ9UR3ZTdgIw8mxddvtcDxLoXvdbXJuFQYadUUsF7q
TIMESTAMP=`date +%s%N | cut -c -13`
MESSAGE=$TIMESTAMP+$APIPATH
SIGNATURE=`echo -n $MESSAGE | openssl dgst -sha256 -hmac $SECRET -binary | base64`
wscat -H "x-auth-key: $APIKEY" \
-H "x-auth-signature: $SIGNATURE" \
-H "x-auth-timestamp: $TIMESTAMP" \
-c wss://bithumbfutures.com/1/api/v1/t/stream -w 1 -x '{"op":"sub", "id": "abc123", "ch": "order:futZtmicU8Ls03xldo112uxpICXulxXd"}'
This is similar to the way you authenticate any RESTful request. You need to add the following header fields to the connection request:
x-auth-key
x-auth-timestamp
x-auth-signature
The server will then check if the data is correctly signed before upgrading the connection protocol to WebSocket.
Note that if you specify these header fields, the server will reject the websocket connection request if authentication fails.
Method 2 - WebSocket Authentication by Sending the Auth Message
Authenticate by Sending the
auth
Message
# # Install wscat from Node.js if you haven't
# npm install -g wscat
APIPATH=stream
APIKEY=BclE7dBGbS1AP3VnOuq6s8fJH0fWbH7r
SECRET=fAZcQRUMxj3eX3DreIjFcPiJ9UR3ZTdgIw8mxddvtcDxLoXvdbXJuFQYadUUsF7q
TIMESTAMP=`date +%s%N | cut -c -13`
MESSAGE=$TIMESTAMP+$APIPATH
SIGNATURE=`echo -n $MESSAGE | openssl dgst -sha256 -hmac $SECRET -binary | base64`
wscat -c wss://bithumbfutures.com/1/api/pro/stream -w 1 -x "{\"op\":\"auth\", \"id\": \"abc123\", \"t\": $TIMESTAMP, "key": \"$APIKEY\", \"sig\": \"$SIGNATURE\"}"
You can also authenticate a live websocket session by sending an op:auth
message to the server.
Name | Type | Required | Description |
---|---|---|---|
op | String |
Yes | "auth" |
id | String |
No | optional id field, you may safely skip it |
t | Long |
Yes | UTC timestamp in milliseconds, use this timestamp to generate signature |
key | String |
Yes | your api key |
sig | String |
Yes | the signature is generated by signing "<timestamp>+stream" |
Authentication Response
Auth success message
{
"m": "auth",
"id": "abc123",
"code": 0
}
Auth error message
{
"m":"auth",
"id": "abc123",
"code": 200006,
"err": "Unable to find User Account Data"
}
You will receive a message for authentication result after you send authentication request.
Field | Type | Description |
---|---|---|
m | String |
"auth" |
id | String |
echo back the id if you provide one in the request |
code | Long |
Any code other than 0 indicate an error in authentication |
err | Optional[String] |
Provide detailed error message if code is not 0 |
Subscribe to Data Channels
How to Subscribe
Use
wscat
from Node.js to connect to websocket data.
# # Install wscat from Node.js if you haven't
# npm install -g wscat
npm install -g wscat
# Connect to websocket
wscat -c wss://bithumbfutures.com/0/api/pro/v1/stream -x '{"op":"sub", "ch": "depth:BTC-PERP"}'
You can also setup authorized session
@ToDo
You can subscribe/unsubscribe to one or multiple data channels.
- If the subscription is successful, you will receive at least one ack message confirming the request is successful and you will start receiving data streams.
- If the subscription is unsuccessful, you will receive one ack message with text explaining why the subscription failed.
Request Body Schema
The standard messages to subscribe to / unsubscribe from data channels is an JSON object with fields:
Name | Type | Description |
---|---|---|
op | String |
sub to subscribe and unsub to unsubscribe |
id | Optional[String] |
user specified UUID, if provided, the server will echo back this value in the response message |
ch | String |
name of the data channel with optional arguments, see below for details |
Subscribe to bbo stream for symbol
BTC-PERP
{ "op": "sub", "id": "abcd1234", "ch": "bbo:BTC-PERP" }
Subscribe to ref-px stream for symbol
BTC
{ "op": "sub", "id": "abcd1234", "ch": "ref-px:BTC" }
Subscribe to trade stream for one contract
{ "op": "sub", "id": "abcd1234", "ch": "trades:BTC-PERP" }
Unsubscribes from the depth stream for all symbols (method 1)
{ "op": "unsub", "id": "abcd1234", "ch": "depth:*" }
Unsubscribes from the depth stream for all symbols (methond 2)
{ "op": "unsub", "id": "abcd1234", "ch": "depth" }
Unsubscribes from the 1 minute bar streams for all symbols (method 1)
{ "op": "unsub", "id": "abcd1234", "ch": "bar:1:*" }
Unsubscribes from the 1 minute bar streams for all symbols (method 2)
{ "op": "unsub", "id": "abcd1234", "ch": "bar:1" }
Unsubscribes from bar streams of all frequencies for
BTC-PERP
{ "op": "unsub", "id": "abcd1234", "ch": "bar:*:BTC-PERP" }
Customize Channel content with ch
You can customize the channel content by setting ch
according to the table below:
Type | Value | Description |
---|---|---|
public | depth:<symbol> |
Updates to order book levels. |
public | bbo:<symbol> |
Price and size at best bid and ask levels on the order book. |
public | trades:<symbol> |
Market trade data |
public | bar:<interval>:<symbol> |
Bar data containing O/C/H/L prices and volume for specific time intervals |
public | ref-px:<symbol> |
Reference prices used by margin risk Calculation. |
public | ticker:<symbol> |
Ticker ??? |
public | futures-market-data |
Futures market data ??? |
Private | order:<account> |
Order Update Stream: "futures", or actual accountId for account. |
Symbol in ref-px is single asset symbol(e.g. BTC
), not trading pair symbol (e.g. BTC-PERP
), which is different from other channels.
Unsubscribe with Wildcard Character *
Using the wildcard character *
, you can unsubscribe from multiple channels with the same channel name.
Channel: Bar Data
Subscribe to
BTC-PERP
1 minute bar stream
{ "op": "sub", "id": "abc123", "ch":"bar:1:BTC-PERP" }
Unsubscribe to
BTC-PERP
1 minute bar stream
{ "op": "unsub", "id": "abc123", "ch":"bar:1:BTC-PERP" }
// Alternatively, you can unsubscribe all bar streams for BTC-PERP
{ "op": "unsub", "id": "abc123", "ch":"bar:*:BTC-PERP" }
// Or unsubscribe all 1 minute bar stream
{ "op": "unsub", "id": "abc123", "ch":"bar:1" }
// Or unsubscribe all bar stream
{ "op": "unsub", "id": "abc123", "ch":"bar" }
Bar Data Sample Message
{
"m": "bar",
"s": "BTC-PERP",
"data": {
"i": "1",
"ts": 1575398940000,
"o": "8500.25",
"c": "8510.75",
"h": "8519",
"l": "8500.25",
"v": "54.12"
}
}
Channel
bar
Message Schema
The data
field is a list containing one or more trade objects. The server may combine consecutive trades with the same price and bm
value into one aggregated item. Each trade object contains the following fields:
Name | Type | Description |
---|---|---|
seqnum | Long |
the sequence number of the trade record. seqnum is always increasing for each symbol, but may not be consecutive |
p | String |
the executed price expressed as a string |
q | String |
the aggregated traded amount expressed as string |
ts | Long |
the UTC timestamp in milliseconds of the first trade |
bm | Boolean |
if true, the buyer of the trade is the maker. |
Channel: Level 1 Order Book Data (BBO)
Subscribe to
BTC-PERP
quote stream
{ "op": "sub", "id": "abc123", "ch":"bbo:BTC-PERP" }
Unsubscribe to
BTC-PERP
quote stream
{ "op": "unsub", "id": "abc123", "ch":"bbo:BTC-PERP" }
BBO Message
{
"m": "bbo",
"ts": 1573068442532,
"symbol": "BTC-PERP",
"data": {
"bid": [
"9309.11",
"0.25"
],
"ask": [
"9309.12",
"0.5"
]
}
}
You can subscribe to updates of best bid/offer data stream only. Once subscribed, you will receive BBO message whenever the price and/or size changes at the top of the order book.
Each BBO message contains price and size data for exactly one bid level and one ask level.
Channel: Level 2 Order Book Updates
Subscribe to
BTC-PERP
depth updates stream
{ "op": "sub", "id": "abc123", "ch":"depth:BTC-PERP" }
Unsubscribe to
BTC-PERP
depth updates stream
{ "op": "unsub", "id": "abc123", "ch":"depth:BTC-PERP" }
The Depth Message
{
"m": "depth",
"symbol": "BTC-PERP",
"data": {
"ts": 1573069021376,
"seqnum": 2097965,
"asks": [
[
"0.06844",
"10760"
]
],
"bids": [
[
"0.06777",
"562.4"
],
[
"0.05",
"221760.6"
]
]
}
}
If you want to keep track of the most recent order book snapshot in its entirety, the most efficient way is to subscribe to the depth
channel.
Each depth
message contains a bids
list and an asks
list in its data
field. Each list contains a series of [price, size]
pairs that
you can use to update the order book snapshot. In the message, price
is always positive and size
is always non-negative.
- if
size
is positive and theprice
doesn't exist in the current order book, you should add a new level[price, size]
. - if
size
is positive and theprice
exists in the current order book, you should update the existing level to[price, size]
. - if
size
is zero, you should delete the level atprice
.
See Orderbook Snapshot for code examples.
Channel: Market Trades
Subscribe to
BTC-PERP
market trades stream
{ "op": "sub", "id": "abc123", "ch":"trades:BTC-PERP" }
Unsubscribe to
BTC-PERP
market trades stream
{ "op": "unsub", "id": "abc123", "ch":"trades:BTC-PERP" }
Trade Message
{
"m": "trades",
"symbol": "BTC-PERP",
"data": [
{
"p": "9100",
"q": "0.015",
"ts": 1573069903254,
"bm": false,
"seqnum": 144115188077966308
}
]
}
The data
field is a list containing one or more trade objects. The server may combine consecutive trades with the same price and bm
value into one aggregated item. Each trade object contains the following fields:
Name | Type | Description |
---|---|---|
seqnum |
Long |
the sequence number of the trade record. seqnum is always increasing for each symbol, but may not be consecutive |
p |
String |
the executed price expressed as a string |
q |
String |
the aggregated traded amount expressed as string |
ts |
Long |
the UTC timestamp in milliseconds of the first trade |
bm |
Boolean |
if true, the buyer of the trade is the maker. |
Channel: Futures Market Data
Subscribe to Futures Market Data
# Subscribe to all symbols
{"op":"sub", "ch":"futures-market-data"}
{"op":"sub", "ch":"futures-market-data:*"}
# Subscribe to one symbol
{"op":"sub", "ch":"futures-market-data:BTC-PERP"}
Futures Market Data Sample Message
{
"m": "futures-market-data",
"s": "BTC-PERP",
"data": {
"oi": "9000",
"fr": "-0.001",
"fpf": false,
"ip": "8777.155",
"mp": "8432.514108733",
"srct": 1580147455260,
"fpt": 1580144400000
}
}
Channel
futures-market-data
Message Schema
The data
field is an object with following fields:
Name | Type | Description |
---|---|---|
s | String |
symbol |
oi | String |
open interest |
fr | String |
funding rate |
fpf | Boolean |
funding payment flag |
ip | String |
index price |
mp | String |
mark price |
srct | Long |
source time |
fpt | Long |
next funding payment time |
Order Channels
Subscribe All Order-Related Channels
You can subscribe/unsubscribe to all order-related channels with one message.
To subscribe:
{"op":"sub", "id": "abcd1234", "ch":"order:futures"}
To unsubscribe:
{"op":"unsub", "id": "abcd1234", "ch":"order:futures"}
In both messages above, the id
field is optional.
Once subscribed, you will start to receive messages from all the following channels:
- order - order updates
- futures-collateral - updates in collateral balance
- futures-position - updates in contract position along with other contract-specifc data
- futures-risk - updates in overall account data
Please refer to WebSocket - Futures Balance Update Messages for implementation details.
tp - Transaction Type
The tp
field in the message shows the reason of the balance update. Below are some common :
ExecutionUpdate
- message about order status updateTakeOver
- the account has been taken over due to hightened risk exposure.PositionInjectionBLP
- position injected to Backstop Liquidity Providers (BLPs), you will only see this message if your account is registered as a BLP with the exchange.PositionInjection
- position injected to regular accounts.FundingPayment
- funding payment made to the account.FuturesPnlSettlement
- rolling position PnL into realized PnL
Identifying Balance Update Batches by execId (execution Id) and txNum (Transaction Number)
Some balance updates, such as position injection, are done in batches. The txNum
can help you identify such updates. For a batch of n update messages, the i-th message
will have txNum = n-i
- that is, the first message will have txNum = n-1
and the last message will have txNum = 0
.
Retrieve Transaciton Details
You can use execId
to retrieve balance update details using the RESTful API. See Lookup Balance Update Records by Id
Channel: Order
Order Message
{
"m": "order",
"accountId": "futNodf11Cos9iKQXAaE2Oukctj3jdMA",
"ac": "FUTURES", // account category
"execId": 229, // use this to query transaction details with RESTful APIs
"txNum": 0, // order messages will always have txNum = 0
"rid": "r1715630020d5362614103bbtcpwxnh",
"data": {
"sn": 229, // deprected, use execId
"orderId": "r1715630020d5362614103bbtcpwxnh",
"ot": "Limit", // order type
"s": "BTC-PERP", // symbol
"t": 1586288919298, // sending time (UTC)
"p": "8000", // order price
"q": "0.1", // order quantity
"sd": "Buy", // side
"st": "Filled", // status
"ap": "8000", // average filled price
"cfq": "0.1", // cummulative filled quantity
"sp": "", // stop price
"err": "", // error code
"cf": "0.52", // cummulative commission (fee)
"fa": "USDT", // fee asset
"ei": "NULL_VAL", // execution instruction
"lq": "0.1", // last filled quantity
"lp": "8000", // last filled price
"lf": "0.52", // fee/rebate of the last fill
"pos": "0.1", // contract position
"rc": "-800.52" // reference cost
}
}
Channel
order:futures
Message Schema
The data
field is an object with following fields:
Name | Type | Description |
---|---|---|
sn | Long |
deprecated, use execId |
orderId | String |
order Id |
ot | String |
order type |
s | String |
symbol |
t | Long |
sending time (UTC) |
p | String |
order price |
q | String |
order quantity |
sd | String |
side |
st | String |
status |
ap | String |
average filled price |
cfq | String |
cummulative filled quantity |
sp | String |
stop price |
err | String |
error code |
cf | String |
cummulative commission (fee) |
fa | String |
fee asset |
ei | String |
execution instruction |
lq | String |
last filled quantity |
lp | String |
last filled price |
lf | String |
fee/rebate of the last fill |
pos | String |
contract position |
rc | String |
reference cost |
Channel: Contract Position Updates
Futures Position (per-symbol data)
{
"m": "futures-position",
"accountId": "futNodf11Cos9iKQXAaE2Oukctj3jdMA",
"ac": "FUTURES",
"execId": 413208,
"txNum": 0,
"tp": "FuturePnlSettlement",
"rid": "6F31ICSCpd7yYYeG",
"data": {
"s": "BTC-PERP",
"sn": 413208, // deprecated, use execId
"pos": "0", // contract position
"rc": "0", // reference cost
"posn": "0", // position notional
"liq": "-1", // Estimated liquidation price
"bepx": "0", // breakeven price
"pnl": "0", // contract position profit/loss in USDT
"ucol": "319.5", // collateral in use (in USDT)
"mbn": "5804.865", // maximum notional allowed to buy
"msn": "0", // maximum notional allowed to sell
"mbos": "0.762994873", // deprecated, use mbn instead
"msos": "0", // deprecated, use msn instead
"idxPx": "7102.68", // index price of the underlying (BTC/USDT in this case)
"markPx": "7608", // market price of the futures contract
"posdlt": "0", // change in position
"rcdlt": "428.785" // change in reference cost
}
}
Channel
order:futures
Message Schema
The data
field is an object with following fields:
Name | Type | Description |
---|---|---|
s | String |
symbol |
sn | Long |
deprecated, use execId instead |
pos | String |
contract position |
rc | String |
reference cost |
posn | String |
position notional |
liq | String |
Estimated liquidation price |
bepx | String |
breakeven price |
pnl | String |
contract position profit/loss in USDT |
ucol | String |
collateral in use (in USDT) |
mbn | String |
maximum notional allowed to buy |
msn | String |
maximum notional allowed to sell |
mbos | String |
deprecated, use mbn instead |
msos | String |
deprecated, use msn instead |
idxPx | String |
index price of the underlying (BTC/USDT in this case) |
markPx | String |
market price of the futures contract |
posdlt | String |
change in position |
rcdlt | String |
change in reference cost |
Channel: Futures Collateral Updates
Futures Collateral
{
"m" : "futures-collateral",
"accountId": "futNodf11Cos9iKQXAaE2Oukctj3jdMA",
"ac" : "FUTURES",
"execId" : 110,
"txNum" : 0,
"tp" : "FuturesTransfer",
"rid" : "t4t3h0CkIMx91zMzNzWuzmpUcQx4aCvE", // request Id
"data": {
"a" : "USDT", // asset code
"sn" : 110, // deprected, use execId
"tb" : "196.344", // total balance
"ab" : "196.344", // available balance. This field is deprecated, for futures collaterals, ab always equals to tb.
"mt" : "0", // maximum transferrable balance
"dlt": "-10" // negative if transferring out of the futures account, positive when adding funds to the futures account
}
}
Channel
order:futures
Message Schema
The data
field is an object with following fields:
Name | Type | Description |
---|---|---|
a | String |
asset code |
sn | Long |
deprected, use execId instead |
tb | String |
total balance |
ab | String |
available balance. This field is deprecated, for futures collaterals, ab always equals to tb. |
mt | String |
maximum transferrable balance |
dlt | String |
negative if transferring out of the futures account, positive when adding funds to the futures account |
Channel: Futures Account Risk
Futures Risk (overall account data)
{
"m": "futures-risk",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"ac": "FUTURES",
"data": {
"col": "12800.39525",
"effcol": "12800.39525",
"ucol": "68.133212928",
"frcol": "12732.262037071",
"walbal": "12970.11105",
"actval": "13099.258147865",
"posn": "762.664258566",
"epn": "1362.664258566",
"clv": "0.106454857",
"amar": "9.393653036",
"tmar": "0.003",
"emmar": "0.006",
"eimar": "0.05",
"alv": "20",
"pnltot": "129.147097865",
"upnl": "129.147097865",
"spnl": "0"
}
}
Channel
order:futures
Message Schema
The data
field is an object with following fields:
Name | Type | Description |
---|---|---|
col | String |
total collateral value in USDT |
effcol | String |
effective collateral value in USDT |
ucol | String |
account overall collateral in use (in USDT) |
frcol | String |
account overall free collateral (in USDT) |
walbal | String |
total wallet balance in USDT |
actval | String |
|
posn | String |
account overall position notional value in USDT |
epn | String |
account overall effective position notional in USDT |
clv | String |
account leverage |
alv | String |
account maximum leverage |
amar | String |
account margin rate |
tmar | String |
takeover margin rate |
emmar | String |
effective maintenance margin rate |
eimar | String |
effective initial margin rate |
pnl | String |
position notional in USDT |
larMaxLev | Int |
largestOptionalMaxLeverage ??? |
upnl | String |
unrealized pnl |
rpnl | String |
realized pnl |
WebSocket - Data Request
WS: Orderbook Snapshot
Requesting the current order book snapshot
{ "op": "req", "id": "abcdefg", "action": "depth-snapshot", "args": { "symbol": "BTC-PERP" } }
Depth snapshot message
{
"m": "depth-snapshot",
"symbol": "BTC-PERP",
"id": "abcd1234",
"data": {
"seqnum": 3167819629,
"ts": 1573142900389,
"asks": [
[
"0.06758",
"585"
],
[
"0.06773",
"8732"
]
],
"bids": [
[
"0.06733",
"667"
],
[
"0.06732",
"750"
]
]
}
}
You can request the current order book via websocket by an depth-snapshot
request.
The args
schema:
Name | Data Type | Description |
---|---|---|
op | String |
req |
action | String |
depth-snapshot |
id | String |
for result match purpose |
args:symbol | String |
Symbol, e.g. BTC-PERP |
The response schema:
Name | Data Type | Description |
---|---|---|
m | String |
depth-snapshot |
symbol | String |
Symbol, e.g. BTC-PERP |
id | String |
echo back id in request |
data:seqnum | Long |
|
data:ts | Long |
UTC Timestamp in milliseconds |
data:asks | [[String, String]] |
List of (price, size) pair |
data:bids | [[String, String]] |
List of (price, size) pair |
You can following the steps below to keep track of the the most recent order book:
- Connecting to WebSocket Stream
- Subscribe to the depth update stream, see Level 2 Order Book Updates (Depth).
- Send a
depth-snapshot
request to the server. - Once you obtain the snapshot message from the server, initialize the snapshot.
- Using consequent
depth
messages to update the order book.
Please note that field seqnum
should strictly increase by 1 for each new depth update (each symbol
maintain its own seqnum
).
If you see a larger than 1 gap from previous seqnum
(for the same symbol
), then there might be data loss,
you need to repeat above steps to maintain a new order book.
The depth-snapshot
message is constructed in a consistent way with all depth
message.
Please note that the depth-snapshot
API has higher latency. The response time is usually between
1000 - 2000 milliseconds. It is intended to help you initialize the orderbook, not to be used to obtain
the timely order book data.
WS: Futures Account Risk
Request futures risk
{
"op": "req",
"action": "futures-risk",
"id": "abcd1234",
}
Futures Risk Response
{
"m": "futures-risk",
"accountId": "futZrwfTaL4Py6M05X0SnJ9QFIuj6k2Q",
"ac": "FUTURES",
"id": "abcd1234",
"data": {
"col": "12800.39525",
"effcol": "12800.39525",
"ucol": "68.133212928",
"frcol": "12732.262037071",
"walbal": "12970.11105",
"actval": "13099.258147865",
"posn": "762.664258566",
"epn": "1362.664258566",
"clv": "0.106454857",
"amar": "9.393653036",
"tmar": "0.003",
"emmar": "0.006",
"eimar": "0.05",
"alv": "20",
"pnltot": "129.147097865",
"upnl": "129.147097865",
"spnl": "0"
}
}
You can request margin risk for a symbol via websocket by an futures-risk
request.
The args
schema:
Name | Data Type | Description |
---|---|---|
op | String |
req |
action | String |
futures-risk |
id | String |
for result match purpose |
The response schema:
Name | Data Type | Description |
---|---|---|
m | String |
depth-snapshot |
accountId | String |
futures accountId |
ac | String |
FUTURES |
symbol | String |
Symbol, e.g. BTC-PERP |
id | String |
echo back id in request |
data | Json |
See data detail below |
data
field detail
Name | Data Type | Description |
---|---|---|
col | String |
|
effcol | String |
|
ucol | String |
collateral in use |
frcol | String |
free collateral |
walbal | String |
|
actval | String |
|
posn | String |
|
epn | String |
|
clv | String |
current leverage |
amar | String |
|
tmar | String |
|
emmar | String |
|
eimar | String |
|
alv | String |
|
pnltot | String |
|
upnl | String |
unsettled profit/loss |
spnl | String |
settled profit/loss |
WS: Place Order
Request to place new order
{
"op": "req",
"action": "place-Order",
"account": "FUTURES",
"args": {
"time": 1573772908483,
"id": "11eb9a8355fc41bd9bf5b08bc0d18f6b",
"symbol": "BTC-PERP",
"orderPrice": "8500",
"orderQty": "0.12",
"orderType": "limit",
"side": "buy",
"postOnly": false,
"respInst": "ACK"
}
}
Successful ACK message
{
"m": "order",
"accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
"accountCategory": "FUTURES",
"action": "place-order",
"status": "Ack",
"info": {
"symbol": "BTC-PERP",
"orderType": "Limit",
"timestamp": 1576015701441,
"id": "17e1f6809122469589ffc991523b505d",
"orderId": "s16ef1daefbe08669437121523b505d"
}
}
Error response message
{
"m": "order",
"accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
"accountCategory": "FUTURES",
"action": "place-order",
"status": "Err",
"info": {
"id": "69c482a3f29540a0b0d83e00551bb623",
"symbol": "BTC-PERP",
"code": 300011,
"message": "Not Enough Account Balance",
"reason": "INVALID_BALANCE"
}
}
Place order via websocket
Request
Make new order request follow the general websocket request rule, with proper place new order parameters as specified in rest api for args field.
see placing order via RESTful API.
Response
Respond with m field as order, and action field as place-order; status field to indicate if this is a successful Ack or failed Err.
ACK
With status field as Ack to indicate this new order request pass some basic sanity check, and has been sent to matching engine.
info field provide some detail: if you provide id in your request, it will be echoed back as id to help you identify; we also provide server side generated orderId, which is the id you should use for future track or action on the order.
ERR
With status field as Err to indicate there is some obvisous errors in your order.
info field provide some detail: if you provide id in your request, it will be echoed back as id to help you identify; we also provide error code, reason, and message detail.
WS: Cancel Order
Request to cancel existing open order
{
"op": "req",
"action": "cancel-order",
"account": "futures",
"args": {
"time": 1574165050128,
"id": "2d4c3fa1e5c249e49f990ce86aebb607",
"orderId": "16e83845dcdsimtrader00008c645f67",
"symbol": "BTC-PERP"
}
}
Successful ACK message
{
"m": "order",
"accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
"accountCategory": "FUTURES",
"action": "cancel-order",
"status": "Ack",
"info": {
"symbol": "BTC-PERP",
"orderType": "NULL_VAL",
"timestamp": 1574165050147,
"id": "7b73dcd8e8c847d5a99df5ef5ae5088b",
"orderId": "16e83845dcdsimtrader00008c645f67"
}
}
Error response message
{
"m": "order",
"accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
"accountCategory": "FUTURES",
"action": "cancel-order",
"status": "Ack",
"info": {
"code": 300006,
"id": "x@fabs",
"message": "Invalid Client Order Id: x@fabs",
"symbol": "BTC-PERP",
"reason": "INVALID_ORDER_ID"
}
}
Cancel an existing open order via websocket
Request
Make order cancelling request follow the general websocket request rule by setting action
to be cancel-orde
, with proper cancel order parameters as specified in rest api for args field.
Response
ACK
With status field as Ack to indicate this cancel order request pass some basic sanity check, and has been sent to matching engine.
info field provide some detail: if you provide id in your request, it will be echoed back as id to help you idintify; we also echo back target orderId to be cancelled.
Err
With status field as Err to indicate there is some obvisous errors in your cancel order request.
info field provide some detail: if you provide id in your request, it will be echoed back as id to help you identify; we also provide error code, reason, and message detail.
WS: Cancel All Orders
Request to cancel all existing open orders
{
"op": "req",
"action": "cancel-all",
"args": {}
}
Request to cancel existing open order related to symbol "BTC-PERP"
{
"op": "req",
"action": "cancel-all",
"account": "futures",
"args": {
"symbol": "BTC-PERP"
}
}
Successful ACK message
{
"m": "order",
"accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
"ac": "FUTURES",
"action": "cancel-all",
"status": "Ack",
"info": {
"symbol": "",
"orderType": "NULL_VAL",
"timestamp": 1574165159732,
"id": "69c482a3f29540a0b0d83e00551bb623",
"orderId": ""
}
}
Cancel all open orders on account level via websocket with optional symbol.
Request
Make general websocket request with action
field as cancel-All
and set proper account
value (futures
), and provide time value in args.
Response
With status field as Ack to indicate this cancel all order request has been received by server and sent to matching engine.
info field provide some detail: if you provide id in your request, it will be echoed back as id to help you match ack with request.