English
NAV
console

Update Log

07/1/2022

Add main domain name https://api.bitget.com

Request Url rule
/api/spot/v1/public/time 20c/1s
/api/spot/v1/public/currencies 20c/1s
/api/spot/v1/public/products 20c/1s
/api/spot/v1/public/product 20c/1s
/api/spot/v1/market/ticker 20c/1s
/api/spot/v1/market/tickers 20c/1s
/api/spot/v1/market/fills 20c/1s
/api/spot/v1/market/candles 20c/1s
/api/spot/v1/market/depth 20c/1s
/api/spot/v1/account/assets 10c/1s
/api/spot/v1/account/bills 10c/1s
/api/spot/v1/account/transferRecords 20c/1s
/api/spot/v1/trade/orders 10c/1s
/api/spot/v1/trade/batch-orders 5c/1s
/api/spot/v1/trade/cancel-order 10c/1s
/api/spot/v1/trade/cancel-batch-orders 10c/1s
/api/spot/v1/trade/orderInfo 20c/1s
/api/spot/v1/trade/open-orders 20c/1s
/api/spot/v1/trade/history 20c/1s
/api/spot/v1/trade/fills 20c/1s

24/09/ 2021【WebSocket Api 】

15/09/2021 【Add transfer record interface】

05/07/2021【New creation v1 Spot trading document】

Introduction

API Introduction

Welcome to Bitget developer documentation!

This document is the only official document of Bitget API. The capabilities provided by Bitget API will be continuously updated here. Please pay attention to it in time.

You can switch to access different business APIs by clicking the upper menu, and you can switch the document language by clicking the language button on the upper right.

On the right side of the document is an example of request parameters and response results.

Update follow-up

Regarding API additions, updates, and offline information, Bitget will issue announcements in advance. It is recommended that users follow and subscribe to our announcements to obtain relevant information in a timely manner.

You can click here  to subscribe to the announcement.

Contact us

If you have any questions or suggestions, feel free to contact us:

Quick start

Prepare to integrate

If you need to use the API, please log in to the web page first, complete the API key application and permission configuration, and then develop and trade according to the details of this document.

You can click here  to create an API Key.

Each user can create 10 sets of Api Keys, and each Api Key can set two permissions for reading and trading.

The permissions are described as follows:

After the API creation is successful, please remember the following information:

SDK / Code example

SDK(Recommended)

Java | Python | Node Js | Golang | PHP

This chapter is consist of the following two aspects for the interface types:

Public interface

The public interface can be used to obtain configuration information and market data. Public requests can be called without authentication.

Private interface

The private interface can be used for order management and account management. Every private request must be signed using a canonical form of verification.

The private interface needs to be verified with your APIKey.

Access restriction

This chapter mainly focuses on access restrictions:

Rest API

If a valid APIKey is passed in, use APIKey to limit the speed; if not, use the public IP to limit the speed.

Speed limit rules: There are separate instructions on each interface. If there is no specific instruction, the speed limit of general interface is 10 times per second.

API domain

You can use the Rest API access method by yourself.

Domain REST API Recommend to use
Domain1 https://api.bitget.com International
Domain2 https://capi.bitget.com Alternate domain name

API Verification

Initiating request

The header of all REST requests must contain the following keys:

API Public parameters

side(Trade direction)

String Description
sell Sell
buy Buy

orderType(Order type)

String Description
limit Limit order
market Market order

force(Order type)

String Description
normal Do not use special type order
postOnly postOnly type of order
fok Fill Or Kill(FOK)
ioc Immediate-Or-Cancel(IOC)

status(Order status)

String Description
new Unfilled
partial-fill Partially filled
full-fill Fully filled
cancelled Cancelled

groupType(Major types of transaction)

String Description
deposit Deposit
withdraw Withdrawal
transaction Trade
transfer Transfer
other Others

bizType(Business type)

String Description
deposit Deposit
withdraw Withdrawal
buy Buy
Sell sell
transfer-in Transfer-in
transfer-out Transfer-out

status(deposit-withdrawal order status)

String Description
cancel Cancel
reject Reject
success Success
wallet-fail Wallet failed
wallet-processing Wallet processing
first-audit 1st audit
recheck 2nd audit
first-reject 1st audit rejected
recheck-reject 2nd audit rejected

type(User withdrawal address query)

String Description
chain-on On blockchain
inner-transfer Internal address

accountType

String Description
EXCHANGE spot account
OTC_SGD Otc account
CONTRACT contract account
USD_MIX Mix account
USDT_MIX USDT Futurre account

Candlestick line timeframe (granularity)

Signature

The request header of ACCESS-SIGN is obtained by encrypting timestamp + method.toUpperCase() + requestPath + "?" + queryString + body **string (+ means string connection) using the **HMAC SHA256 **method, and outputting it through **BASE64 encoding.

Description of each string of the signature

When queryString is empty, the signature format

timestamp + method.toUpperCase() + requestPath + body

 

When queryString is not empty, the signature format

timestamp + method.toUpperCase() + requestPath + "?" + queryString + body

For example

To obtain in-depth information, take btcusdt as an example:

Generate the string to be signed:

'1591089508404GET/api/spot/v1/market/depth?symbol=btcusdt_spbl&limit=20'

Place order,take btcusdt as an example:

Generate the string to be signed:

'1561022985382POST/api/spot/v3/order/order{"symbol":"btcusdt_spbl","size":"8","side":"buy","price":"1","orderType":"limit","clientOrderId":"bitget#123456"}'

 

Steps to generate the final signature

Step 1. Use the private key secretkey to encrypt the string to be signed with hmac sha256

Signature = hmac_sha256(secretkey, Message)

 

Step 2. Base64 encoding for Signature.

Signature = base64.encode(Signature)

 

Request interaction

All requests are based on the Https protocol, and the Content-Type in the request header information needs to be standardized as:'application/json'.

Request interaction description

Success

HTTP status code 200 indicates a successful response and may contain content. If the response contains content, it will be displayed in the corresponding return content.

Common error codes

Standard Specification

Timestamp

The unit of ACCESS-TIMESTAMP in the request signature is milliseconds. The timestamp of the request must be within 30 seconds of the API service time, otherwise the request will be considered expired and rejected. If there is a large deviation between the local server time and the API server time, we recommend that you update the http header by querying the API server time.

Frequency limiting rules

If the request is too frequent, the system will automatically limit the request and return the “429 too many requests” status code in the http header.

· Public interface: such as the market information interface, the standardized frequency limit is 2 seconds with max. 20 requests.

· Authorization interface: restrict the call of the authorization interface through apikey, refer to the frequency limitation rule of each interface for frequency limitation.

Request format

There are currently only two request methods in formats: GET and POST

RestAPI

Basic configuration interface

Obtain server time

Speed limit rule: 20 times/2s

HTTP Request

Obtain server time

Return data:

{
    "code": "00000",
    "msg": "success",
    "requestTime": 1622097118135,
    "data": 1622097118134
}

Coin basic information

Speed limit rule: 20 times/2s

HTTP Request 

Obtain all coins information on the platform

Return data:

{
    "code":"00000",
    "msg":"success",
    "requestTime":1622097139437,
    "data":[
        {
            "coinId":"1",
            "coinName":"BTC",
            "transfer":"true",
            "chains":[
                {
                    "chain":null,
                    "needTag":"false",
                    "withdrawAble":"true",
                    "rechargeAble":"true",
                    "withdrawFee":"0.005",
                    "depositConfirm":"1",
                    "withdrawConfirm":"1",
                    "minDepositAmount":"0.001",
                    "minWithdrawAmount":"0.001",
                    "browserUrl":"https://blockchair.com/bitcoin/testnet/transaction/"
                }
            ]
        },
        {
            "coinId":"2",
            "coinName":"USDT",
            "transfer":"true",
            "chains":[
                {
                    "chain":"ERC20",
                    "needTag":"false",
                    "withdrawAble":"true",
                    "rechargeAble":"true",
                    "withdrawFee":"0.01",
                    "depositConfirm":"12",
                    "withdrawConfirm":"1",
                    "minDepositAmount":"0.1",
                    "minWithdrawAmount":"0.1",
                    "browserUrl":"https://ropsten.etherscan.io/tx/"
                }
            ]
        }
    ]
}

Return value description

Return string String description
coinId Coin ID
coinName Coin name
transfer Whether can be transferred
chains
> chain Chain name
> needTag Whether need to tag
> withdrawAble Whether can be withdrawn
> rechargeAble Whether can deposit
> withdrawFee Withdrawal fee
> depositConfirm Deposit no. of confirmation block
> withdrawConfirm Withdrawal no. of confirmation block
> minDepositAmount Min. deposit amount
> minWithdrawAmount Min. withdrawal amount
> browserUrl Blockchain browser

Basic configuration information of trading pairs

Speed ​​limit rule: 20 times/2s

HTTP Request 

obtain basic configuration information of all trading pairs

Return data:

{
    "code":"00000",
    "msg":"success",
    "requestTime":1622097197283,
    "data":[
        {
            "symbol":"BTCUSDT_SPBL",
            "baseCoin":"BTC",
            "quoteCoin":"USDT",
            "minTradeAmount":"0.0001",
            "maxTradeAmount":"10000",
            "takerFeeRate":"0.001",
            "makerFeeRate":"0.001",
            "priceScale":"4",
            "quantityScale":"8",
            "status":"online"
        },
        {
            "symbol":"EOSUSDT_SPBL",
            "baseCoin":"EOS",
            "quoteCoin":"USDT",
            "minTradeAmount":"1",
            "maxTradeAmount":"1",
            "takerFeeRate":"1",
            "makerFeeRate":"1",
            "priceScale":"1",
            "quantityScale":"1",
            "status":"online"
        }
    ]
}

Return value description

Return string String description
symbol Trading pair
baseCoin Base coin
quoteCoin Denomination coin
minTradeAmount Min. trading amount
maxTradeAmount Max. trading amount
takerFeeRate Taker transaction fee rate
makerFeeRate Maker transaction fee rate
priceScale Pricing scale
quantityScale Quantity scale
status Status

Single trading pair to obtain information

Speed limit rule: 20 times/2s

HTTP Request 

obtain all ticker information

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Name of trading pair

Return data:

{
    "code":"00000",
    "msg":"success",
    "requestTime":1622097197283,
    "data":[
        {
            "symbol":"BTCUSDT_SPBL",
            "symbolName":"BTCUSDT",
            "baseCoin":"BTC",
            "quoteCoin":"USDT",
            "minTradeAmount":"0.0001",
            "maxTradeAmount":"10000",
            "takerFeeRate":"0.001",
            "makerFeeRate":"0.001",
            "priceScale":"4",
            "quantityScale":"8",
            "status":"online"
        }
    ]
}

Return value description

Return string String description
symbol Trading pair
symbolName Trading pair name
baseCoin Base coin
quoteCoin Denomination coin
minTradeAmount Min. trading amount
maxTradeAmount Max. trading amount
takerFeeRate Taker transaction fee rate
makerFeeRate Maker transaction fee rate
priceScale Pricing scale
quantityScale Quantity scale
status Status

Public market interface

Obtain a Ticker information

Speed ​​limit rule: 20 times/2s

HTTP Request 

obtain a Ticker information

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Contract name

Return data:

{
    "code":"00000",
    "data":{
        "symbol":"BTCUSDT",
        "high24h":"34413.1",
        "low24h":"34413.1",
        "close":"34413.1",
        "quoteVol":"0",
        "baseVol":"0",
        "usdtVol":"0",
        "ts":"1625125755277"
    },
    "msg":"success",
    "requestTime":1625125756372
}

Return value description

Return string String description
symbol Trading pair name
high24h 24h highest price
close Latest transaction price
low24h 24h lowest price
timestamp System timestamp
baseVol Base coin volume
quoteVol Denomination coin volume
usdtVol USDT volume

Obtain all Ticker information

Speed limit rule: 20 times/2s

HTTP Request

Obtain all ticker information

Return data

{
    "code":"00000",
    "data":[
      {
        "symbol":"BTCUSDT",
        "high24h":"34413.1",
        "low24h":"34413.1",
        "close":"34413.1",
        "quoteVol":"0",
        "baseVol":"0",
        "usdtVol":"0",
        "ts":"1625125755277"
    }
    ]
    "msg":"success",
    "requestTime":1625125756372
}

Return value description

Return string String description
symbol Trading pair name
high24h 24h highest price
close Latest transaction price
low24h 24h lowest price
timestamp System timestamp
baseVol Base coin volume
quoteVol Denomination coin volume
usdtVol USDT volume

Obtain transaction data

Speed ​​limit rule: 20 times/2s

HTTP Request

Obtain transaction data

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Contract name
limit String No Default is 100,Max. is 500

Return data:

{
    "code":"00000",
    "msg":"success",
    "requestTime":1622097283024,
    "data":[
        {
            "symbol":"BFTUSDT_SPBL",
            "tradeId":"781698148534505473",
            "side":"buy",
            "fillPrice":"2.38735",
            "fillQuantity":"2470.6224",
            "fillTime":"1622097282536"
        },
        {
            "symbol":"BFTUSDT_SPBL",
            "tradeId":"781698140590493697",
            "side":"sell",
            "fillPrice":"2.38649",
            "fillQuantity":"3239.7976",
            "fillTime":"1622097280642"
        }
    ]
}

Return value description

Return string String description
symbol Contract name
tradeId Filled order ID
side Trade direction
fillPrice Transaction price
fillQuantity Transaction quantity
fillTime Transaction time

Obtain candlestick line data

Speed limit rule: 20 times/2s

HTTP Request 

obtain candlestick line data

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Contract name
period String Yes Candlestick line time unit, granularity (​​refer to the following list for values)
after String No Time after
before String No Time before
limit String No Default 100

Return data:

{
    "code":"00000",
    "msg":"success",
    "requestTime":1622097356073,
    "data":[
        {
            "open":"2.34517",
            "high":"2.34771",
            "low":"2.34214",
            "close":"2.34555",
            "quoteVol":"189631.101357091",
            "baseVol":"80862.6823",
            "usdtVol":"189631.101357091",
            "ts":"1622091360000"
        },
        {
            "open":"2.34391",
            "high":"2.34903",
            "low":"2.34391",
            "close":"2.34608",
            "quoteVol":"167725.002115681",
            "baseVol":"71479.3205",
            "usdtVol":"167725.002115681",
            "ts":"1622091420000"
        }
    ]
}

Return value description

Return string String description
ts System timestamp
open Opening price
high Highest price
low Lowest price
close Closing price
baseVol Base coin volume
quoteVol Denomination coin volume
usdtVol USDT volume

Obtain market depth data

Speed limit rule: 20 times/2s

HTTP Request 

obtain market depth data

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Contract name
type String Yes Default: step0: do not merge, value: step0, step1, step2, step3, step4, step5
limit String No default 150

Return data

{
    "code":"00000",
    "msg":"success",
    "requestTime":1622102974025,
    "data":{
        "asks":[
            [
                "38084.5",
                "0.0039"
            ],
            [
                "38085.7",
                "0.0018"
            ],
            [
                "38086.7",
                "0.0310"
            ],
            [
                "38088.2",
                "0.5303"
            ]
        ],
        "bids":[
            [
                "38073.7",
                "0.4993000000000000"
            ],
            [
                "38073.4",
                "0.4500"
            ],
            [
                "38073.3",
                "0.1179"
            ],
            [
                "38071.5",
                "0.2162"
            ]
        ],
        "timestamp":"1622102974025"
    }
}

Account interface

Obtain account assets

Speed ​​limit rule: 10 times/1s

HTTP Request 

obtain account assets

Return data

{
  "code":"200",
  "message":"success",
  "data":[
    {
        "coinId":"10012",
        "coinName":"usdt",
        "available":"0",
        "frozen":"0",
        "lock":"0",
        "uTime":"1622697148"
    }
]
}

Return value description

Return string String description
coinId Coin ID
coinName Coin name
available Available assets
frozen Frozen assets
lock Locked assets
uTime Update timing

Obtain transaction detail flow

Speed ​​limit rule 10 times/1s

HTTP Request

Obtain transaction detail flow

Request parameter

Parameter name Parameter type To be a must Description
coinId Integer No Coin ID
groupType String No Transaction group type
bizType String No Business type
after String No Send in billId, the data before this billId
before String No Send in billId, the data after this billId
limit Integer No The number of returned results, the default is 100, the max. is 500

Return data

{
  "code":"200",
  "message":"success",
  "data":[{
      "cTime":"1622697148",
      "coinId":"22",
      "coinName":"usdt",
      "groupType":"deposit",
      "bizType":"transfer-in", 
      "quantity":"1",
      "balance": "1",
      "fees":"0",
      "billId":"1291"
}]
}

Return value description

Return string String description
cTime Creation time
coinId Coin Id
coinName Coin name
groupType Transaction flow type
bizType Transaction bill business type
quantity Quantity
balance Assets before transfer
fees Transaction fees
billId ID

Get transfer record

Speed limit rule 20 times/1s

HTTP Request

Request parameter

Parameter name Parameter type To be a must Description
coinId Integer No Coin ID
fromType String No Major type of bill accountType
after String No Send in billId, the data before this tradeTime
before String No Send in billId, the data after this tradeTime
limit Integer No The number of returned results, the default is 100, the max. is 500

Return data

{
    "code":"00000",
    "data":[
        {
            "coinName":"btc",
            "status":"SUCCESS",
            "toType":"USD_MIX",
            "toSymbol":"",
            "fromType":"CONTRACT",
            "fromSymbol":"BTC/USD",
            "amount":"1000.00000000",
            "tradeTime":"1631070374488"
        }
    ],
    "msg":"success",
    "requestTime":1631608142260
}

Return value description

Return string String description
coinName Coin name
status Transfer status
toType Transfer in account type
toSymbol Transfer to account Symbol
fromType Transfer out account type
amount Number of transfers
tradeTime Transfer time

Order interface

Place order

Speed limit rule: 10 times/1s

HTTP Request 

Interface for placing order

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to :/products
side String Yes Trade direction
orderType String Yes Order type limit/market
force String Yes Order type
price String No Limit pricing
quantity String Yes Order quantity
clientOrderId String No Custom id length: 40

Return data

{
    "code":"200",
    "msg":"success",
    "data":{
        "orderId":"1001",
        "clientOrderId":"hgXjh89AsxleMSw"
    }
}

Return value description

Return string String description
orderId Order ID
clientOrderId Custom ID

Batch order

Speed limit rule 50 times/2s

HTTP Request

Batch order

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to:/products
orderList List Yes order data list (length 50)
Parameter name Parameter type to be a must Description
side String Yes Order side buy/sell
orderType String Yes Order type limit/market
force String Yes order time force
price String No Limit price
quantity String Yes Order quantity
clientOrderId String No Custom id

Return data

{
    "code":"200",
    "msg":"success",
    "data":{
        "orderId":"1001",
        "clientOrderId":"hgXjh89AsxleMSw"
    }
}

Cancel order

Speed ​​limit rule 50 times/2s

HTTP Request

Cancel order

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to:/products
orderId String Yes Order ID

Return data

{

  "code":"200",
   "message":"success"

}   

Cancel order in batch (single trading pair)

Speed limit rule 50 times/2s

HTTP Request

Cancel order in batch

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to:/products
orderIds String[] Yes Order ID array

Return data

{

  "code":"200",
   "message":"success"

}   

Obtain order details

Speed ​​limit rule 20 times/2s

HTTP Request

Obtain orders based on order ID or custom ID

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to:/products
orderId String Yes Order ID
clientOrderId String Custom ID

Return data

{
  "code":"200",
  "message":"success",
"data":[{
  "accountId":"10012",
  "symbol":"btcusdt_spbl",
  "orderId":"2222222",
  "clientOrderId":"xxxxxxx",
  "price":"34245.12",
  "quantity":"1",  
  "orderType":"limit",
  "side":"buy",
  "status":"new",
  "fillPrice":"0",
  "fillQuantity":"0",
  "fillTotalAmount":"0",
  "cTime":"1622697148"
}]
}

Return value description

Return string String description
accountId Account ID
symbol Trading pair name
orderId Order ID
clientOrderId Custom ID
price Order price
quantity Order quantity
orderType Order type
side Order direction
status Order status
fillPrice Transaction price
fillQuantity Transaction quantity
fillTotalAmount Total transcation volume
cTime Creation time

Obtain unfilled order list

Speed ​​limit rule 20 times/2s

HTTP Request

Obtain list of unfilled and partially filled order without cancellation

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to:/products

Return data

{
  "code":"200",
  "message":"success",
"data":[{
  "accountId":"10012",
  "symbol":"btcusdt_spbl",
  "orderId":"2222222",
  "clientOrderId":"xxxxxxx",
  "price":"34829.12",
  "quantity":"1",  
  "orderType":"limit",
  "side":"buy",
  "status":"new",
  "fillPrice":"0",
  "fillQuantity":"0",
  "fillTotalAmount":"0",
  "cTime":"1622697148"
}]
}

Return value description

Return string String description
accountId Account ID
symbol Trading pair name
orderId Order ID
clientOrderId Custom ID
price Order price
quantity Order quantity
orderType Order type
side Order direction
status Order status
fillPrice Transaction price
fillQuantity Transaction quantity
fillTotalAmount Total transcation volume
cTime Creation time

Obtain order history list

Speed limit rule 20 times/2s

HTTP Request

Obtain all filled and cancelled orders

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to:/products
after String No Send in orderId, the data before this orderId desc
before String No Send in the orderId, the data after this orderId asc
limit Integer No The number of returned results, the default is 100, the max. is 500

Return data

{
  "code":"200",
  "message":"success",
"data":[{
  "accountId":"10012",
  "symbol":"btcusdt_spbl",
  "orderId":"2222222",
  "clientOrderId":"xxxxxxx",
  "price":"34982.12",
  "quantity":"1",  
  "orderType":"limit",
  "side":"buy",
  "status":"new",
  "fillPrice":"34982.12",
  "fillQuantity":"1",
  "fillTotalAmount":"34982.12",
  "cTime":"1622697148"
}]
}

Return value description

Return string String description
accountId Account ID
symbol Trading pair name
orderId Order ID
clientOrderId Custom ID
price Order price
quantity Order quantity
orderType Order type
side Order direction
status Order status
fillPrice Transaction price
fillQuantity Transaction quantity
fillTotalAmount Total transcation volume
cTime Creation time

Obtain transaction details

Speed ​​limit rule 20 times/2s

HTTP Request

Obtain transaction detail history

Request parameter

Parameter name Parameter type To be a must Description
symbol String Yes Trading pair, details refer to:/products
orderId String No Order ID
after String No Send in orderId, the data before this orderId desc
before String No Send in the orderId, the data after this orderId asc
limit Integer No The number of returned results, the default is 100, the max. is 500

Return data

{
  "code":"",
  "message":"",
  "data":[{
  "accountId":"1001",
  "symbol":"btcusdt_spbl",
  "orderId":"100021",
  "fillId":"102211",
  "orderType":"limit",
  "side":"buy",
  "fillPrice":"38293.12",
  "fillQuantity":"1",
  "fillTotalAmount":"38293.12",
  "cTime":"1622697148",
  "feeCcy":"btc",
  "fees":"0.0001"
}]
}

Return value description

Return string String description
accountId Account ID
symbol Trading pair name
orderId Order ID
fillId Transaction ID
orderType Order type
side Order direction
fillPrice Transaction price
fillQuantity Transaction quantity
fillTotalAmount Total transaction volume
cTime Creation time
feeCcy Coin for transaction fee
fees Transaction fees

WebSocketAPI

Overview

WebSocket is a new HTML5 protocol that achieves full-duplex data transmission between the client and server, allowing data to be transferred effectively in both directions. A connection between the client and server can be established with just one handshake. The server will then be able to push data to the client according to preset rules. Its advantages include:

It is strongly recommended that developers use WebSocket API to obtain market information and transaction depth. ​

domain WebSocket API Recommended to use
domain 1 wss://ws.bitget.com/spot/v1/stream internationality

Connect

Connection instructions:

Connection limit: 1 time per second

When subscribing to a public channel, use the address of the public service. When subscribing to a private channel, use the address of the private service

Subscription limit: 240 times per hour

If there’s a network problem, the system will automatically disable the connection.

The connection will break automatically if the subscription is not established or data has not been pushed for more than 30 seconds.

To keep the connection stable:

  1. Set a timer of N seconds whenever a response message is received, where N is less than 30.
  2. If the timer is triggered, which means that no new message is received within N seconds, send the String 'ping'.
  3. Expect a 'pong' as a response. If the response message is not received within N seconds, please raise an error or reconnect.

Login

api_key: Unique identification for invoking API. Requires user to apply one manually.

passphrase: APIKey password

timestamp: the Unix Epoch time, the unit is seconds

sign: signature string, the signature algorithm is as follows:

First concatenate timestampmethodrequestPath, and body strings, then use HMAC SHA256 method to encrypt the concatenated string with SecretKey, and then perform Base64 encoding.

secretKey: The security key generated when the user applies for APIKey, e.g. : 22582BD0CFF14C41EDBF1AB98506286D

Example of timestamp: const timestamp ='' + Date.now() / 1000

Among sign example: sign=CryptoJS.enc.Base64.Stringify(CryptoJS.HmacSHA256(timestamp +'GET'+'/users/self/verify', secretKey))

method: always 'GET'.

requestPath : always '/users/self/verify'

The request will expire 30 seconds after the timestamp. If your server time differs from the API server time, we recommended using the REST API to query the API server time and then set the timestamp.

For the description of the signature method, refer to the verification section in the API overview

Steps to generate the final signature:

Step 1. Use the private key secretkey to encrypt the string to be signed with hmac sha256

Signature = hmac_sha256(secretkey, Message)

The second step is to base64 encode the Signature

Signature = base64.encode(Signature)

If login fails, it will automatically disconnect

Request format description

{
    "op": "login",
    "args": [{
        "apiKey": "<api_key>",
        "passphrase": "<passphrase>",
        "timestamp": "<timestamp>",
        "sign": "<sign>"
    }]
}

Request Example

{
    "op": "login",
    "args": [{
        "apiKey": "bg_573af5eca856acd91c230da294ce2105",
        "passphrase": "123456",
        "timestamp": "1538054050",
        "sign": "8RCOqCJAhhEh4PWcZB/96QojLDqMAg4qNynIixFzS3E="
    }]
} 

Successful Response Example

{
    "event": "login",
    "code": "0",
    "msg": ""
} 

Failure Response Example

{
    "event": "error",
    "code": "30005",
    "msg": "error"
}

Subscribe

Subscription Instructions

Request format description

{
  "op": "subscribe",
  "args": ["<SubscriptionTopic>"]
}

WebSocket channels are divided into two categories: public and private channels.

Public channels -- include tickers channel, K-Line channel, limit price channel, order book channel, and mark price channel, etc -- do not require log in.

Private channels -- including account channel, order channel, and position channel, etc -- require log in.

Users can choose to subscribe to one or more channels, and the total length of multiple channels cannot exceed 4096 bytes.

Request Example

{
    "op": "subscribe",
    "args": [{
        "instType": "SP",
        "channel": "ticker",
        "instId": "BTCUSDT"
    }, {
        "instType": "SP",
        "channel": "candle5m",
        "instId": "BTCUSDT"
    }]
}

Request parameters

Parameter Type Required Description
op String Yes Operation, subscribe
args Array Yes List of subscribed channels
> instType String No Instrument typeSP: Spot public channel SPBL Spot private channel
> channel String Yes Channel name
> instId String No Instrument ID

Example response

{
    "event": "subscribe",
    "args": {
        "instType": "SP",
        "channel": "ticker",
        "instId": "BTCUSDT"
    }
}

Return parameters

Parameter Type Required Description
event String Yes Event, subscribe error
arg Object No Subscribed channel
> instType String No Instrument typeSP: Spot public channel SPBL Spot private channel
> channel String Yes Channel name
> instId String No Instrument ID
code String No Error code
msg String No Error message

Unsubscribe

Unsubscribe from one or more channels.

Request format description

{
  "op": "unsubscribe",
  "args": ["< SubscriptionTopic> "]
}

Request Example

{
    "op": "unsubscribe",
    "args": [{
        "instType": "SP",
        "channel": "ticker",
        "instId": "BTCUSDT"
    }, {
        "instType": "SP",
        "channel": "candle1m",
        "instId": "BTCUSDT"
    }]
}

Request parameters

Parameter Type Required Description
op String Yes Operation, unsubscribe
args Array Yes List of channels to unsubscribe from
> instType String Yes Instrument typeSP
> channel String Yes Channel name
> instId String Yes Instrument ID

Example response

{
    "event": "unsubscribe",
    "args": {
        "instType": "SP",
        "channel": "ticker",
        "instId": "BTCUSDT"
    }
} 

Return parameters

Parameter Type Required Description
event String Yes Event, unsubscribe error
arg Object Yes Unsubscribed channel
>instType String No Instrument typeSP: Spot public channel SPBL Spot private channel
> channel String Yes Channel name
> instId String Yes Instrument ID
code String No Error Code
msg String No Error Message

Checksum

This mechanism can assist users in checking the accuracy of depth data.

Merging incremental data into full data

After subscribing to the incremental load push (such as books 400 levels) of Order Book Channel, users first receive the initial full load of market depth. After the incremental load is subsequently received, update the local full load.

  1. If there is the same price, compare the amount. If the amount is 0, delete this depth data. If the amount changes, replace the original data.
  2. If there is no same price, sort by price (bid in descending order, ask in ascending order), and insert the depth information into the full load.

Calculate Checksum

Use the first 25 bids and asks in the full load to form a string (where a colon connects the price and amount in an ask or a bid), and then calculate the CRC32 value (32-bit signed integer).

Calculate Checksum

1. More than 25 levels of bid and ask
A full load of market depth (only 2 levels of data are shown here, while 25 levels of data should actually be intercepted):
"bids": [
  [ 43231.1, 4 ],
  [ 43231, 6 ]
]
"asks": [
  [ 43230.8, 9 ],
  [ 43230.7, 8 ]
]
Check string:
"43231.1:4:43231:6:43230.8:9:43230.7:8"

2. Less than 25 levels of bid or ask
A full load of market depth:
"bids": [
  [ 3366.1, 7, 0, 3 ]
]
"asks": [
  [ 3366.8, 9, 10, 3 ],
  [ 3368  , 8,  3, 4 ],
  [ 3372  , 8,  3, 4 ]
]

Check string:
"3366.1:7:3366.8:9:3368:8:3372:8"
  1. When the bid and ask depth data exceeds 25 levels, each of them will intercept 25 levels of data, and the string to be checked is queued in a way that the bid and ask depth data are alternately arranged. Such as: bid[price:amount]:ask[price:amount]:bid[price:amount]:ask[price:amount]...
  2. When the bid or ask depth data is less than 25 levels, the missing depth data will be ignored. Such as: bid[price:amount]:ask[price:amount]:asks[price:amount]:asks[price:amount]...

Public Channels

Tickers Channel

Retrieve the last traded price, bid price, ask price and 24-hour trading volume of instruments. Data will be pushed every 100 ms.

Request Example

{
    "op": "subscribe",
    "args": [{
        "instType": "SP",
        "channel": "ticker",
        "instId": "BTCUSDT"
    }]
}

Request parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> instType String Yes Instrument Type,SP
> channel String Yes Channel name, tickers
> instId String Yes Instrument ID

Successful Response Example

{
    "op": "subscribe",
    "args": [{
        "instType": "SP",
        "channel": "ticker",
        "instId": "BTCUSDT"
    }]
}

Failure Response Example

{
    "event": "error",
    "code": "30001",
    "msg": "Unrecognized request: {\"op\": \"subscribe\", \"arg\":[\"instType\":\"sp\",\"channel\" : \"ticker\", \"instId\" : \"BTCUSDT\"}]}"
} 

Response parameters

Parameter Type Required Description
event String Yes Event, subscribe unsubscribe error
arg Object No Subscribed channel
> instType String Yes Instrument Type
> channel String Yes Channel name
> instId String Yes Instrument name
code String No Error Code
msg String No Error Message

Push data parameters

Parameter Type Description
arg Object Successfully subscribed channel
> instType String Instrument Type
> channel String Channel name
> instId String Instrument ID
action String Push data action, incremental push data or full push data snapshot: full update: incremental
data Array Subscribed data
>instId String Instrument ID
>last String Last traded price
>bestAsk String Best ask price
>bestBid String Best bid price
>open24h String Open price in the past 24 hours
>high24h String Highest price in the past 24 hours
>low24h String Lowest price in the past 24 hours
>baseVol String 24h trading volume, with a unit of currency.
>quoteVol String 24h trading volume, with a unit of contact.
>ts String Ticker data generation time, Unix timestamp format in milliseconds

Candlesticks Channel

Retrieve the candlesticks data of an instrument. Data will be pushed every 500 ms.

Request Example

{
    "op": "subscribe",
    "args": [{
        "instType": "sp",
        "channel": "candle1m",
        "instId": "BTCUSDT"
    }]
}

Request parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> instType String Yes Instrument Type SP
> channel String Yes Channel Name,candle1Wcandle1Dcandle12H candle4H  candle1Hcandle30m candle15m candle5m candle1m
> instId String Yes Instrument name for example :BTCUSDT

Successful Response Example

{
    "event": "subscribe",
    "arg": {
        "instType": "sp",
        "channel": "candle1D",
        "instId": "BTCUSDT"
    }
}

Failure Response Example

{
    "event": "error",
    "code": 30003,
    "msg": "instType:sp,channel:candle1D,instId:BTC-USDT Symbol not exists" 
} 

Response parameters

Parameter Type Required Description
event String Yes Event, subscribe unsubscribe error
arg Object No Subscribed channel
> instType String Yes Instrument Type
> channel String Yes channel name
> instId String Yes Instrument name
code String No Error Code
msg String No Error Message

Push Data Example

{
    "arg": {
        "instType": "sp",
        "channel": "candle1D",
        "instId": "BTCUSDT"
    },
    "data": [
        ["1597026383085", "8533.02", "8553.74", "8527.17", "8548.26", "45247"]
    ]
} 

Push data parameters

Parameter Type Description
arg Object Successfully subscribed channel
> instType String Instrument Type
> channel String Channel name
> instId String Instrument ID
data Array Subscribed data
> ts String Data generation time, Unix timestamp format in milliseconds
> o String Open price
> h String highest price
> l String Lowest price
> c String Close price
>v String Trading volume, with a unit of contact.

Depth channel

Get depth data

books: Push the full snapshot data for the first time, push incrementally later, and push incrementally later, that is, if there is a change in depth, the data that has changed once is pushed

books5: Push 5 files of snapshot data for the first time, and then all the data will be pushed, and 5 files of data will be pushed once with in-depth changes, that is, 5 files of data will be pushed every time

book15 15 files of snapshot data are pushed for the first time, and then all of them will be pushed, and 15 files of data will be pushed once with in-depth changes, that is, 15 files of data will be pushed every time

Request Example

{
    "op": "subscribe",
    "args": [{
        "instType": "sp",
        "channel": "books5",
        "instId": "BTCUSDT"
    }]
}

Request parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> instType String Yes Instrument Type SP
> channel String Yes Channel name, books books5
> instId String Yes Instrument ID

Example Response

{
    "event": "subscribe",
    "arg": {
        "instType": "sp",
        "channel": "books5",
        "instId": "BTCUSDT"
    }
}

Failure example

{
    "event": "error",
    "code": 30003,
    "msg": "instType:sp,channel:books5,instId:BTC-USDT Symbol not exists" 
} 

Response parameters

Parameter Type Required Description
event String Yes Event,subscribe unsubscribe error
arg Object No Subscribed channel
> instType String Yes Instrument Type
> channel String Yes Channel name
> instId String Yes Instrument name
msg String No Error Message
code String No Error Code

Push data parameters

Parameter Type Description
arg Object Successfully subscribed channel
> instType String Instrument Type
> channel String Channel name
> instId String Instrument ID
action String Push data action, incremental push data or full push data snapshot: full update: incremental
data Array Subscribed data
> asks Array Order book on sell side
> bids Array Order book on buy side
> ts String Order book generation time, Unix timestamp format in milliseconds
> checksum Integer Checksum

An example of the array of asks and bids values: ["411.8", "10", "1", "4"] "411.8" is the depth price, "10" is the size

Trades Channel

Retrieve the recent trades data. Data will be pushed whenever there is a trade.

Request Example

{
    "op": "subscribe",
    "args": [{
        "instType": "sp",
        "channel": "trade",
        "instId": "BTCUSDT"
    }]
}

Request parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> instType String Yes Instrument Type
> channel String Yes Channel Name,trade
> instId String Yes Instrument ID

Successful Response Example

{
    "event": "subscribe",
    "arg": [{
        "instType": "sp",
        "channel": "trade",
        "instId": "BTCUSDT"
    }]
}

Failure Response Example

{
    "event": "error",
    "code": 30003,
    "msg": "instType:spbl,channel:trade,instId:BTC-USDT Symbol not exists" 
} 

Response parameters

Parameter Type Required Description
event String Yes Event,subscribe unsubscribe error
arg Object No Subscribed channel
> instType String Yes InstrumentType
> channel String Yes Channel Name
> instId String Yes Instrument ID
code String No Error Code
msg String No Error Message

Push data parameters

Parameter Type Description
arg Object Successfully subscribed channel
> instType String Instrument Type
> channel String Channel Name
> instId String Instrument ID
data Array Subscribed data
> ts String Filled time, Unix timestamp format in milliseconds
> px String Trade price
> sz String Trade size
> side String Trade direction, buysell

Private Channel

Account Channel

Retrieve account information. Data will be pushed when triggered by events such as placing/canceling order, and will also be pushed in regular interval according to subscription granularity.

Request Example

{
    "op": "subscribe",
    "args": [{
        "instType": "spbl",
        "channel": "account",
        "instId": "default"
    }]
}

Request parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> instType String Yes Instrument Typ,spbl
> channel String Yes Channel Name,account
> instId String Yes Currency, all is default

Successful Response Example

{
    "event": "subscribe",
    "arg": {
        "instType": "spbl",
        "channel": "account",
        "instId": "default"
    }
} 

Failure Response Example

{
    "event": "error",
    "code": 30003,
    "msg": "instType:spbl,channel:ticker,instId:BTC-USDT Symbol not exists" 
}  

Response parameters

Parameter Type Required Description
event String Yes Operation, subscribe unsubscribe error
arg Object No Subscribed channel
> instType String Yes Instrument Type
> channel String Yes Channel Name
> instId String No Currency
code String No Error Code
msg String No Error Message

Push Data Example

{
    "action": "snapshot",
    "arg": {
        "instType": "spbl",
        "channel": "account",
        "instId": "default"
    },
    "data": [{
        "coinId": "2",
        "coinName": "USDT",
        "available": "1000.0000"
    }, {
        "coinId": "1",
        "coinName": "BTC",
        "available": "1.35000"
    }]
}

Push data parameters

Parameter Type Decription
arg Object Successfully subscribed channel
> instType String Instrument Type
> channel String Channel Name
> instId String Currency
data Array Subscribed data
> coinId String Coin Id
> coinName String Coin Name
> available String balance

First push: full push.

Incremental push: push transaction changes

Order Channel

Retrieve order information. Data will not be pushed when first subscribed. Data will only be pushed when triggered by events such as placing/canceling order.

Request Example

{
    "op": "subscribe",
    "args": [{
        "channel": "orders",
        "instType": "spbl",
        "instId": "BTCUSDT_SPBL"
    }]
}

Request parameters

Parameter Type Required Description
> instId String No Instrument Id
op String Yes Operation,subscribe unsubscribe
args Array List of subscribed channels
> instType String Instrument Type,spbl
> channel String Channel Name, orders

Successful Response Example

{
    "event": "subscribe",
    "arg": {
        "channel": "orders",
        "instType": "spbl",
        "instId": "BTCUSDT_SPBL"
    }
}

Failure Response Example

{
    "event": "error",
    "code": 30003,
    "msg": "instType:spbl,channel:orders,instId:BTC-USDT Symbol not exists"
}

Response parameters

Paramters Type Required Description
event String Event,subscribe unsubscribe errror
arg Object Subscribed Data
> channel String Channel Name
> instType String Instrument Typespbl:币币
> instId String Instrument Id
code String Error Code
msg String Error Message

Push data parameters

Paramter Type Description
> channel String Channel Name
> instType String Instrument Type
> instId String Instrument Id
data Array Subscribed Data
> instId String Instrument Id
> ordId String Order Id
> clOrdId String Client-supplied order ID
> px String Order price
> sz String The original order quantity
> notional String The purchase amount, which will be returned when the market price is purchased
> ordType String Order Type market limit
> force String Categorynormaltwapadlfull_liquidationpartial_liquidation
> side String order side,buy sell
> fillPx String fill price
> tradeId String
> fillSz String fill size
> fillTime String fill time
> fillFee String last filled fee
> fillFeeCcy String last filled fee currency
> execType String Order flow type, T: taker M: maker
> accFillSz String Accumulated fill quantity
> avgPx String Average filled price. If none is filled, it will return 0.
> status String order state new' ‘partial-fillfull-fillcancelled`
> cTime String Creation time, Unix timestamp format in milliseconds
> uTime String Update time, Unix timestamp format in milliseconds
>orderFee Array fee list
>> feeCcy String Fee currency
>> fee String FeeNegative number represents the user transaction fee charged by the platform.Positive number represents rebate.

RestAPI  error code

Public error code

Error message Error code http status code
The request header "ACCESS_KEY" cannot be empty 40001 400
The request header "ACCESS_SIGN" cannot be empty 40002 400
The request header "ACCESS_TIMESTAMP" cannot be empty 40003 400
Invalid ACCESS_TIMESTAMP 40005 400
Invalid ACCESS_KEY 40006 400
Invalid Content_Type,please use“application/json”format 40007 400
Requested timestamp expired 40008 400
api verification failed 40009 400
Request is too frequent 429 429
The request header "ACCESS_PASSPHRASE" cannot be empty 40011 400
apikey/passphrase is incorrect 40012 400
User has been frozen 40013 400
Incorrect permissions 40014 400
System error 40015 400
The user must bind a mobile phone or Google authenticator 40016 400
Parameter verification failed 40017 400
Illegal IP request 40018 400

 ## Spot error code

Error message Error code http status code
Batch processing orders can only process up to 50 40912 400
OrderId or clientId must be passed one 40913 400
The contract configuration does not exist, please check the parameters 40102 400
Server upgrade, please try again later 40200 400
client_oid length is not greater than 40, and cannot be Martian characters 40305 400
wrong format 40409 400
Only check the data of the last three months 40704 400
Start time is greater than end time 40707 400
Parameter is empty 40724 400
spot service return an error 40725 400
The order does not exist 43001 400
Pending order failed 43002 400
There is no order to cancel 43004 400
Exceeded the maximum order limit of transaction volume 43005 400
The order quantity is less than the minimum transaction quantity 43006 400
The order quantity is greater than the maximum transaction quantity 43007 400
The current order price cannot be less than {0} 43008 400
The current commission price exceeds the limit {0} 43009 400
The transaction amount cannot be less than {0} 43010 400
The current order price cannot be less than {0} 43011 400
Insufficient balance 43012 400

WebSocket error code

Error Message Error Code
Channel does not exist 30001
Illegal request 30002
Invalid op 30003
User needs to log in 30004
Login failed 30005
Invalid ACCESS_KEY 30011
Invalid ACCESS_PASSPHRASE 30012
Invalid ACCESS_TIMESTAMP 30013
Request timestamp expired 30014
Invalid signature 30015