NAV Navbar
json

Changelogs

version time content
V1.0.5
2021 AUG 10
* Add a new interval fixed100ms for websocket order_book channel
* Add websocket RPC cancel_on_disconnect
V1.0.4
2021 JUL 20
* Add self_trading_mode for POST /spot/v1/orders and POST /spot/v1/amend_orders, default value is 0 (self-trading not allowed and cancel taker if self-trading happens, user can safely ignore self_trading_mode parameter if they don't care about self-trading)
* Add mmp for POST /spot/v1/amend_orders to enable editing of existing order MMP
* Remove offset parameter, and has_more page info response of GET /spot/v1/user/trades due to self-trading support.
* If user has self-trading executions, trade_id inside response of GET /spot/v1/user/trades are not unique, user will get two trade records with same trade_id and different taker/maker order_id.
V1.0.3
2021 JUL 1
* Add GET /spot/v1/system/cancel_only_status
* Add doc: GET /spot/v1/instruments output actual precisions for step/minimum values
* Add GET /spot/v1/mmp_state, POST /spot/v1/update_mmp_config, POST /spot/v1/reset_mmp, websocket mmp_frozen channel
V1.0.2
2021 JUN 15
* Returns actual price,qty,cancel_reason for order response of endpoints POST /spot/v1/orders and POST /spot/v1/amend_orders
* Add qty_min restriction. the minimum qty of base currency is now qty_min not qty_step
* Add invite-debate and invite-rebate-refund tx_type in transaction log
* The deposit failure and cancel withdrawal transaction types are changed to bad-deposit and withdraw-revert, instead of deposit-rollback and withdraw-refund
* Add descriptions about buy-market order status in doc sections of endpoint POST /spot/v1/orders
* Add cod REST API: POST /spot/v1/user_configs/cod and GET /spot/v1/user_configs/cod
V1.0.0
2021 MAY 12
* Init version

Introduction

Welcome to bit.com API. You can retrieve market data, execute trades and manage your bit.com account through bit.com API.

The document consists of three parts: table of contents for easy browsing (left), longer explanation of each API interface although they are quite self-explanatory already(middle), and example code (right)

How to contact us:

WEB: www.bit.com
support team: [email protected]
VIP server: [email protected]
Telegram:https://t.me/bitcom_exchange

Market maker projects


Market makers are welcome to participate in bit long-term market making projects.
Send the following information to: [email protected]
1. Bit account information;
2. Effective contact information except email;
The type of market maker to be applied for should be indicated in the email (multiple choices are allowed)
Application of market maker for bit spot
Application of market maker for bit delivery contract
Application of market maker for bit perpetual contract
Application of market maker for bit option contract


To encourage market makers to provide better liquidity for the platform, they can enjoy preferential transaction fees. Specific market making responsibilities and handling charges shall be provided after application.
* Bit owns the final interpretation right of the market maker project.

User Manual

We currently offerspot,future and option on bit.com.

Two methods to call API are currently offered at bit.com: Rest and Websocket.

REST endpoint consists of public and private APIs, where public API can be called directly without authentication.

Private API, on the other hand, requires API key signature authentication, Please register, set up API key and related access set ups on API page before kicking off API development.

Private API access: read,spot trade,future&option trade,wallet,block trade

API types and access details can be viewed API summary.

Websocket API is based on websocket protocol. Users need to first establish websocket connection, then send request for channel subscriptions, bit.com start pushing data (ever after) afterwards. You can always unsubscribe or disconnect if you change mind (no longer wish to be subscribed)

Subscription consists of public and private channels, where public channel can be subscribed directly without authentication. Private channel, on the other hand, requires token and authentication.

Channel types and access details can be viewed channel summary.

Spot API hosts (production)

Spot API hosts (testnet)

Spot API rate limit

In order to ensure the system efficiency, bit.com implements the API rate limits . The public interface implements IP-specified frequency limitation , and the private interface implements user-specified frequency limitation. When a breach happens, a prompt will be returned: “429 too many requests”. The individual API limits can be found on the webpage of the trading center. Users who need to increase the speed limit please contact the support team via [email protected]

Public API: 10 requests per second per IP.
Private API(spot trade):5 requests per second per user
Private API(Wallet): 1 request per second per user.
Private API(Others): 5 requests second per user.

About the type of API rate limits, please refer to API summary.

Unlogged users:100 connections per IP
Unlogged users:10 connection requests per second per IP.
Login users: 10 private connections per user.
Connected IP:disconnection triggers when subscription is not established more than 30s.

Authentication

Private API mandatory fields

If authentication fails, a prompt will be returned: “AkId is invalid” and http status code is 412

Signature algorithm

Same as derivative API

    #########
    # Python code to calc BIT.COM API signature
    #########
    import hashlib
    import hmac

    def encode_list(self, item_list):
        list_val = []
        for item in item_list:
            obj_val = self.encode_object(item)
            list_val.append(obj_val)
        output = '&'.join(list_val)
        output = '[' + output + ']'
        return output

    def encode_object(self, param_map):
        sorted_keys = sorted(param_map.keys())
        ret_list = []
        for key in sorted_keys:
            val = param_map[key]
            if isinstance(val, list):
                list_val = self.encode_list(val)
                ret_list.append(f'{key}={list_val}')
            elif isinstance(val, dict):
                # call encode_object recursively
                dict_val = self.encode_object(val)
                ret_list.append(f'{key}={dict_val}')
            elif isinstance(val, bool):
                bool_val = str(val).lower()
                ret_list.append(f'{key}={bool_val}')
            else:
                general_val = str(val)
                ret_list.append(f'{key}={general_val}')

        sorted_list = sorted(ret_list)
        output = '&'.join(sorted_list)
        return output

    def get_signature(self, http_method, api_path, param_map):
        str_to_sign = api_path + '&' + self.encode_object(param_map)
        print('str_to_sign = ' + str_to_sign)
        sig = hmac.new(self.secret_key.encode('utf-8'), str_to_sign.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
        return sig

    #########
    # END
    #########

  1. Request parameters: JSON Body for POST, query string for the rest
  2. Encode string to sign, for simple json object, sort your parameter keys alphabetically, and join them with '&' like 'param1=value1&param2=value2', then get str_to_sign = api_path + '&' + 'param1=value1&param2=value2'
  3. For nested array objects, encode each object and sort them alphabetically, join them with '&' and embraced with '[', ']', e.g. str_to_sign = api_path + '&' + 'param1=value1&array_key1=[array_item1&array_item2]', see example below.
  4. Signature = hex(hmac_sha256(str_to_sign, secret_key))
  5. Add signature field to request parameter:
    for query string, add '&signature=YOUR_SIGNATURE' for JSON body, add {'signature':YOUR_SIGNATURE}


































Example for GET request

Secret Key: eabc3108-dd2b-43df-a98d-3e2054049b73
HTTP method: GET
API Path: /v1/margins
Query string: price=8000&qty=30&instrument_id=BTC-PERPETUAL&timestamp=1588242614000

Then str_to_sign = /v1/margins&instrument_id=BTC-PERPETUAL&price=8000&qty=30&timestamp=1588242614000

> echo -n "/v1/margins&instrument_id=BTC-PERPETUAL&price=8000&qty=30&timestamp=1588242614000" | openssl dgst -sha256 -hmac "eabc3108-dd2b-43df-a98d-3e2054049b73"

> e3be96fdd18b5178b30711e16d13db406e0bfba089f418cf5a2cdef94f4fb57d

sig = hex(hmac_sha256(str_to_sign, secret_key)) = e3be96fdd18b5178b30711e16d13db406e0bfba089f418cf5a2cdef94f4fb57d

Final query string: price=8000&qty=30&instrument_id=BTC-PERPETUAL&timestamp=1588242614000&signature=e3be96fdd18b5178b30711e16d13db406e0bfba089f418cf5a2cdef94f4fb57d

Example for POST request

Secret Key: eabc3108-dd2b-43df-a98d-3e2054049b73
HTTP Method: POST
API Path: /v1/orders
JSON body:
{ "instrument_id": "BTC-27MAR20-9000-C", "order_type": "limit", "price": "0.021", "qty": "3.14", "side": "buy", "time_in_force": "gtc", "stop_price": "", "stop_price_trigger": "", "auto_price": "", "auto_price_type": "", "timestamp": 1588242614000 }

Then str_to_sign = /v1/orders&auto_price=&auto_price_type=&instrument_id=BTC-27MAR20-9000-C&order_type=limit&price=0.021&qty=3.14&side=buy&stop_price=&stop_price_trigger=&time_in_force=gtc&timestamp=1588242614000

> echo -n "/v1/orders&auto_price=&auto_price_type=&instrument_id=BTC-27MAR20-9000-C&order_type=limit&price=0.021&qty=3.14&side=buy&stop_price=&stop_price_trigger=&time_in_force=gtc&timestamp=1588242614000" | openssl dgst -sha256 -hmac "eabc3108-dd2b-43df-a98d-3e2054049b73"

> 34d9afa68830a4b09c275f405d8833cd1c3af3e94a9572da75f7a563af1ca817

sig = hex(hmac_sha256(str_to_sign, secret_key)) = 34d9afa68830a4b09c275f405d8833cd1c3af3e94a9572da75f7a563af1ca817

Final JSON body:
{ "instrument_id": "BTC-27MAR20-9000-C", "order_type": "limit", "price": "0.021", "qty": "3.14", "side": "buy", "time_in_force": "gtc", "stop_price": "", "stop_price_trigger": "", "auto_price": "", "auto_price_type": "", "timestamp": 1588242614000, "signature": "34d9afa68830a4b09c275f405d8833cd1c3af3e94a9572da75f7a563af1ca817" }

POST request json body with boolean field

For example, When calling POST /v1/orders with boolean fields:

Take post_only as example,

Example

request

string to sign

POST request json body with array field

for item in object_array:
    str_list.add(encode(item))
str_to_sign = '&'.join(str_list)

For example, When calling POST /v1/blocktrades with array fields:

Take trades as example,

And secret key is eabc3108-dd2b-43df-a98d-3e2054049b73

Example

request

string to sign

API summary

Path Method Description Scope Rate Limit Type Permission
/spot/v1/orders POST Place new order private spot trade spot trade
/spot/v1/cancel_orders POST Cancel order private spot trade spot trade
/spot/v1/amend_orders POST Amend order private spot trade spot trade
/spot/v1/update_mmp_config POST Update MMP config private spot trade spot trade
/spot/v1/reset_mmp POST Reset MMP state private spot trade spot trade
/spot/v1/user_configs/cod POST Update cod config private spot trade spot trade
/spot/v1/open_orders GET Query open orders private spot others read
/spot/v1/orders GET Query order history private spot others read
/spot/v1/user/trades GET Query user trades private spot others read
/spot/v1/accounts GET Query user account information private spot others read
/spot/v1/transactions GET Query transaction logs private spot others read
/spot/v1/ws/auth GET Get websocket access token private spot others read
/spot/v1/mmp_state GET Query Mmp State private spot others read
/spot/v1/user_configs/cod GET Get cod config private spot others read
/v1/wallet/spot-withdraw POST New withdrawal request private wallet wallet
/v1/wallet/sub-user-transfer POST New transfer request with sub users private wallet wallet
/v1/wallet/transfer POST New transfer request private wallet wallet
/v1/wallet/sub-user-transfer GET Get transfer hisroty with sub users private spot others read
/v1/wallet/transfer GET Get transfer history private spot others read
/v1/wallet/spot-withdrawals GET Get withdrawal history private spot others read
/v1/wallet/spot-deposits GET Get deposit records private spot others read
/spot/v1/system/time GET Get server time public spot public /
/spot/v1/system/version GET Get system version public spot public /
/spot/v1/system/cancel_only_status GET Get cancel only status public spot public /
/spot/v1/instruments GET Query instruments public spot public /
/spot/v1/orderbooks GET Query orderbook public spot public /
/spot/v1/market/trades GET Query market trades public spot public /
/spot/v1/klines GET Query kline data public spot public /
/spot/v1/tickers GET Query instrument ticker public spot public /

System

Get server timestamp

GET /spot/v1/system/time

curl "https://betaspot-api.bitexch.dev/spot/v1/system/time"

Response

{
  "code": 0,
  "message": "",
  "data": 1587884283175
}

Get server timestamp

Query Parameters

None

Response

Name Type Description
data string Server timestamp

Get system version

GET /spot/v1/system/version

curl "https://betaspot-api.bitexch.dev/spot/v1/system/version"

Response

{
  "code": 0,
  "message": "",
  "data": "v1.0"
}

Get API version

Query Parameters

None

Response

Name Type Description
data string Api server version

Get cancel only status

GET /spot/v1/system/cancel_only_status

curl "https://betaspot-api.bitexch.dev/spot/v1/system/cancel_only_status"

Response


{
    "code": 0,
    "message": "",
    "data": {
        "status": 0,
        "remain_ms": 0
    }
}

Get cancel-only status after system maintenance.

status
status=1: means cancel-only is in effective.
status=0: means cancel-only period is finished, the system is ready to accept orders.

remain_ms
Remain time (in milliseconds) for the cancel-only period to finish. when status=0, remain_ms is 0.

Query parameters

None

Response

Name Type Description
status integer Cancel-only status.
remain_ms integer Remain time (in milliseconds) for the cancel-only period to finish.

Market

Get currency pairs

GET /spot/v1/instruments

curl "https://betaspot-api.bitexch.dev/spot/v1/instruments"

Response

{
    "code": 0,
    "message": "",
    "data": [
        {
            "pair": "BTC-USDT",
            "base_currency": "BTC",
            "quote_currency": "USDT",
            "price_step": "0.01",
            "qty_step": "0.0005",
            "qty_min": "0.001",
            "quote_qty_step": "0.00000001",
            "quote_qty_min": "10",
            "taker_fee_rate": "0.00300000",
            "maker_fee_rate": "0.00100000",
            "groups":[
                "1",
                "10",
                "100",
                "1000"
            ]
        },
        {
            "pair": "ETH-BTC",
            "base_currency": "ETH",
            "quote_currency": "BTC",
            "price_step": "0.000001",
            "qty_step": "0.005",
            "qty_min": "0.001",
            "quote_qty_step": "0.00000001",
            "quote_qty_min": "10",
            "taker_fee_rate": "0.00300000",
            "maker_fee_rate": "0.00100000",
            "groups":[
                "1",
                "10",
                "100",
                "1000"
            ]
        }
    ]
}

Get instrument(currency pair) list

Query parameters

None

Response

Name Type Description
pair string Currency pair
base_currency string Base currency
quote_currency string Quote currency
price_step string Order price should be multiple of price_step (output actual precision)
qty_step string Order size should be multiple of qty_step (output actual precision)
qty_min string Minimum order size in base currency (output actual precision)
quote_qty_step string Buy-market order quote_qty should be multiple of quote_qty_step (output actual precision)
quote_qty_min string Minimal buy-market order quote_qty, i.e. min trading amount (output actual precision)
taker_fee_rate string Taker fee rate
maker_fee_rate string Maker fee rate
groups string array Available group values for websocket channel orderbook.{group}.{depth}, is an array of no. of price_step, example ["1", "10"]

Get orderbooks

GET /spot/v1/orderbooks

curl "https://betaspot-api.bitexch.dev/spot/v1/orderbooks?pair=BTC-USDT"

Response

{
    "code": 0,
    "message": "",
    "data": {
        "pair": "BTC-USDT",
        "timestamp": 1585299600000,
        "asks": [
            ["60000", "3.00000000"],
            ["60030", "0.70000000"],
            ["60100", "18.00000000"]
        ],
        "bids": [
            ["59992", "0.30000000"],
            ["59990", "2.00000000"],
            ["59987", "5.60000000"]
        ]
    }
}

Get orderbook by currency pair.

Query parameters

Parameter Type Required Default Description
pair string true "" Currency pair
level int false 5 No. of depth, value range [1,50]

Response

Name Type Description
pair string Currency pair
timestamp integer Timestamp
asks string Asks array [price, qty]
bids string Bids array [price, qty]

Get market trades

GET /spot/v1/market/trades

curl "https://betaspot-api.bitexch.dev/spot/v1/market/trades?pair=BTC-USDT&start_time=1617243797588&end_time=1617596597588"

Response

{
    "code": 0,
    "message": "",
    "data": [
        {
            "created_at": 1617592997588,
            "trade_id": "7",
            "pair": "BTC-USDT",
            "price": "61030.00000000",
            "qty": "0.02000000",
            "side": "sell"
        }
    ]
}

Get market trades.

Query parameters

Parameter Type Required Default Description
pair string true "" Currency pair
start_time integer false One month ago Start timestamp millisecond
end_time integer false Now End timestamp millisecond
count int false 100 Result count (default 100, max 500)

Response

Name Type Description
trade_id integer Trade ID
pair string Currency pair
created_at integer Creation timestamp of the trade
price string Price
qty string Quantity
side string Order side

Get klines

GET /spot/v1/klines

curl "https://betaspot-api.bitexch.dev/spot/v1/klines?pair=BTC-USDT&start_time=1585296000000&end_time=1585596000000&timeframe_min=30"

Response

{
    "code": 0,
    "message": "",
    "data": {
        "close": [
            60050
        ],
        "high": [
            60100
        ],
        "low": [
            60008
        ],
        "open": [
            60030
        ],
        "timestamps": [
            1585296000000
        ],
        "volume": [
            310.2
        ]
    }
}

Get klines by Currency pair. klines endpoint returns 6 time series of data: open price array, hight price array, low price array, close price array, timestamp array of each kline, and volume array.

Support timeframes:

Timeframe Name Desc
1 1 minute
3 3 minute
5 5 minute
15 15 minute
30 30 minute
60 60 minute
240 240 minute
1d daily
1w weekly
1m monthly

Query parameters

Parameter Type Required Default Description
pair string true "" Currency pair
start_time integer true Start timestamp millisecond
end_time integer true End timestamp millisecond
timeframe_min string true "" Timeframe
count int false 100 Result count (default 100, max 1000)

Response

Name Type Description
open float array Open price series
high float array High price series
low float array Low price series
close float array Close price series
timestamps float array Timestamp series
volume float array Volume series

Get tickers

GET /spot/v1/tickers

curl "https://betaspot-api.bitexch.dev/spot/v1/tickers?pair=BTC-USDT"

Response

{
    "code": 0,
    "message": "",
    "data":{
        "time":1589126498813,
        "pair":"BTC-USDT",
        "best_bid":"60050.00000000",
        "best_ask":"60020.00000000",
        "best_bid_qty":"13.50000000",
        "best_ask_qty":"21.00000000",
        "last_price":"60030.00000000",
        "last_qty":"30.00000000",
        "open24h":"60040.00000000",
        "high24h":"60100.00000000",
        "low24h":"60000.00000000",
        "price_change24h":"0.03000000",
        "volume24h":"300.00000000",
        "quote_volume24h":"18000000.00000000"
    }

}

Get ticker information by Currency pair.

Query parameters

Parameter Type Required Default Description
pair string true "" Currency pair

Response

Name Type Description
pair string Currency pair
last_price string Most recent traded price
last_qty string Most recent traded volume
open24h string Open price during previous 24 hour
high24h string Highest price during previous 24 hour
low24h string Lowest price during previous 24 hour
volume24h string Sum volume of base currency during previous 24 hour
quote_volume24h string Sum volume of quote currency during previous 24 hour
price_change24h string Price change% during previous 24 hour
best_bid string Best bid price
best_ask string Best ask price
best_bid_qty string Best bid quantity
best_ask_qty string Best ask quantity

Account

Get spot accounts

GET /spot/v1/accounts


curl -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113" "https://betaspot-api.bitexch.dev/spot/v1/accounts?timestamp=1589521383462&signature=30f7cf5c8018f5dfee515533e25a1813e9120be7898b62fb85a2f4129f3e9528"

Response

{
    "code": 0,
    "message": "",
    "data": {
        "user_id": "1001",
        "balances": [
          {
            "currency": "BTC",
            "available":"99.59591877",
            "frozen":"0.00000000"
          }
        ]
    }
}

Get user account information.

Query parameters

None

Response

Name Type Desc
user_id string User id
balances array Balance list
Name Type Desc
currency string Currency
available string Available amount
frozen string Frozen amount

Get user transactions

GET /spot/v1/transactions

curl -H "X-Bit-Access-Key: ak-8e97ac6c-8075-4a94-b2bb-38bd537619fa" "https://betaspot-api.bitexch.dev/spot/v1/transactions?currency=BTC&type=trade-recv&limit=2&timestamp=1620369292928&signature=35d76033f6e251ce85524ec4310417fd555953fff00cd33f3a94e3d27d062965" 


Response

{
    "code": 0,
    "message": "",
    "data": [
        {
            "tx_time": 1619688616411,
            "ccy": "BTC",
            "tx_type": "trade-recv",
            "change": "0.09970000",
            "balance": "0.99700000",
            "price": "58020.00000000",
            "fee_paid": "0.00030000",
            "trade_id": "557364",
            "order_id": "236142",
            "pair": "BTC-USDT",
            "order_side": "buy",
            "remark": ""
        },
        {
            "tx_time": 1619688616411,
            "ccy": "BTC",
            "tx_type": "trade-recv",
            "change": "0.09970000",
            "balance": "0.89730000",
            "price": "58000.00000000",
            "fee_paid": "0.00030000",
            "trade_id": "557363",
            "order_id": "236142",
            "pair": "BTC-USDT",
            "order_side": "buy",
            "remark": ""
        }
    ],
    "page_info": {
        "has_more": true
    }
}

Get user transactions.

Query Parameters

Parameter Type Required Default Description
currency string true "" Currency
start_time integer false One month ago Start timestamp millisecond
end_time integer false Now End timestamp millisecond
type string false "" Transaction type
offset int false 1 Page index, first page = 1
limit int false 100 Page size

Response

Name Type Desc
tx_time integer Transaction time
ccy string Currency
tx_type string Transaction type
change string Change
balance string Balance after change
price string Trade price (for trade transactions)
fee_paid string Fee paid
order_id string Order ID
trade_id string Trade ID
pair string Currency pair
order_side string Order side
remark string Remark

Enable or disable Cancel On Disconnect

POST /spot/v1/user_configs/cod

curl -X POST "https://betaspot-api.bitexch.dev/spot/v1/user_configs/cod" -H "Content-Type: application/json" -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113"  -d '{"cod":true, "timestamp": 1590572422557, "signature": "3c8c2271a58e3d11dfbd262a6be40ebdd07e8f394a002db0065068b36bc66d5a"}'

Response

{
    "code": 0,
    "message": "",
    "data": {
    }
}

Enable or disable Cancel On Disconnect. If Cancel On Disconnect is enabled, all orders of the account(web AND API) will be cancelled when all 'private' websocket connections are disconnected.

Post json body

Parameter Type Required Default Description
cod bool true "" Whether to enable Cancel On Disconnect

Response

None


Get Cancel On Disconnect configuration

GET /spot/v1/user_configs/cod

curl -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113" "https://betaspot-api.bitexch.dev/spot/v1/user_configs/cod?timestamp=1589521383462&signature=30f7cf5c8018f5dfee515533e25a1813e9120be7898b62fb85a2f4129f3e9528"

Response

{
    "code": 0,
    "message": "",
    "data": {
        "cod": true
    }
}

Get Cancel On Disconnect configuration of the account

Query parameters

None

Response

Name Type Desc
cod bool Whether to enable Cancel On Disconnect

Get Mmp State

GET /spot/v1/mmp_state

curl -H "X-Bit-Access-Key: ak-96cc0cbd-c501-448f-a32d-21228bc9648f" "https://betaspot-api.bitexch.dev/spot/v1/mmp_state?timestamp=1600050649936&signature=3a3c511ab776674c4a8db31135f22c8bf2bc5aac4eb0070c8c4d577e89e01643" 

Response

{
    "code": 0,
    "message": "",
    "data": {
        "mmp_enabled": true,
        "mmp_user_configurable": true,
        "mmp_data": [
            {
                "pair": "BTC-USDT",
                "mmp_config": {
                    "window_ms": 2000,
                    "frozen_period_ms": 10000,
                    "qty_limit": "30.00000000",
                    "delta_limit": "10.00000000"
                },
                "mmp_state": {
                    "mmp_frozen_until_ms": -1,
                    "mmp_frozen": false
                }
            }
        ]
    }
}   

Get Mmp State.

mmp_enabled
Mmp is enabled or not.

mmp_user_configurable
User can edit mmp config or not. if yes, user can change mmp config through POST /spot/v1/update_mmp_config

mmp_data
Mmp configuration & status detail for each currency pair

mmp_frozen_until_ms
mmp_frozen_until_ms indicate mmp frozen status, it's updated by backend.
mmp_frozen_until_ms > 0: frozen until this timestamp or a manual reset
mmp_frozen_until_ms = 0: frozen until a manual reset
mmp_frozen_until_ms = -1: not frozen (a manual reset sets mmp_frozen_until_ms to -1)

mmp_frozen
Indicate mmp is frozen or not.

Query parameters

None

Response

Name Type Desc
mmp_enabled bool Mmp is enabled or not
mmp_user_configurable bool User can edit mmp config or not
mmp_data array Array of mmp data (pair name, config & status detail, see below)
Name Type Desc
window_ms integer Mmp rolling windows time span (milliseconds)
frozen_period_ms integer Mmp frozen time span (milliseconds)
qty_limit string Mmp quantity limit (in base currency, e.g. BTC)
delta_limit string Mmp delta limit (in base currency, e.g. BTC)
Name Type Desc
mmp_frozen_until_ms integer Mmp frozen until timestamp (backend update automatically)
mmp_frozen bool Mmp is frozen or not

Update Mmp Config

POST /spot/v1/update_mmp_config

curl -X POST "https://betaspot-api.bitexch.dev/spot/v1/update_mmp_config" -H "Content-Type: application/json" -H "X-Bit-Access-Key: ak-96cc0cbd-c501-448f-a32d-21228bc9648f"  -d '{"pair": "BTC-USDT", "window_ms": 20000, "frozen_period_ms": 30000, "qty_limit": "1000.00000000", "delta_limit": "1000.00000000", "timestamp": 1600050944127, "signature": "661b535fa878633718922fd90b419de4b5d9ae447833876b91bc8bcc7906e0f3"}' 

Response

{
    "code": 0,
    "message": "",
    "data": "ok"
}    

Update mmp config, only when mmp.user_configurable = true, otherwise returns error.

Mmp frozen state will be triggered when qty >= qty_limit OR abs(delta) >= delta_limit.

window_ms: Mmp rolling windows time span (milliseconds)
frozen_period_ms: Mmp frozen time span (milliseconds)
qty_limit: Mmp quantity limit (in base currency, e.g. BTC)
delta_limit: Mmp delta limit (in base currency, e.g. BTC)




Post json body

Parameter Type Required Default Description
pair string true "" Currency pair
window_ms integer true 0 Mmp rolling windows time span (milliseconds)
frozen_period_ms integer true 0 Mmp frozen time span (milliseconds)
qty_limit string true "" Mmp quantity limit (in base currency, e.g. BTC)
delta_limit string true "" Mmp delta limit (in base currency, e.g. BTC)

Response

Name Type Desc
data string ok

Reset Mmp State

POST /spot/v1/reset_mmp

curl -X POST "https://betaspot-api.bitexch.dev/spot/v1/reset_mmp" -H "Content-Type: application/json" -H "X-Bit-Access-Key: ak-96cc0cbd-c501-448f-a32d-21228bc9648f"  -d '{"pair": "BTC-USDT", "timestamp": 1600050689085, "signature": "992507afc30728c2bc55d7bf7f47e76126ce3f40ddebc205594877381c4374fa"}' 

Response

{
    "code": 0,
    "message": "",
    "data": "ok"
}    

Reset mmp frozen state, then user is able to place new order.

Post json body

Parameter Type Required Default Description
pair string true "" Currency pair

Response

Name Type Desc
data string ok

Order

Place new order

POST /spot/v1/orders


curl -X POST "https://betaspot-api.bitexch.dev/spot/v1/orders" -H "Content-Type: application/json" -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113"  -d '{"pair": "BTC-USDT", "price": "60000", "qty": "3", "side": "buy", "time_in_force": "gtc", "mmp":false, "self_trading_mode": 0, "timestamp": 1589523989378, "signature": "68b658eb68f4ce529623bb4505f5c1c6408b37064a9a5f2102d08088e59d917c"}' 


Response

{
    "code": 0,
    "message": "",
    "data": {
        "order_id": "17552314",
        "created_at": 1589523803017,
        "updated_at": 1589523803017,
        "user_id": "51140",
        "pair": "BTC-USDT",
        "order_type": "limit",
        "side": "buy",
        "price": "60000",
        "qty": "3.00000000",
        "quote_qty": "0.00000000",
        "time_in_force": "gtc",
        "avg_price": "0.00000000",
        "filled_qty": "0.00000000",
        "status": "open",
        "taker_fee_rate": "0.00050000",
        "maker_fee_rate": "0.00020000",
        "cancel_reason": "",
        "label":"hedge",
        "source": "api",
        "post_only": false,
        "reject_post_only": false,
        "mmp": false
    }
}

Price logic:
* market order: price must be empty string
* limit order: price must be a valid num string

Quantity logic:
limit order and sell-market order use "qty" field to specific order size, unit is base_currency (like BTC)
buy-market order use "quote_qty" field to specific order size, unit is quote_currency (like USDT), it's actually a target trading amount

* buy-market order: quote_qty must be non-empty, qty must be empty. take BTC-USDT as example, quote_qty should be USDT amount.
* limit order or sell-market order: qty must be non-empty, quote_qty must be empty
* In order query, quote_qty is only valid for buy-market orders
* For buy-market order, order query returns filled_qty in base currency(there is no filled_quote_qty), executed amount is avg_price * filled_qty, the amount maybe less then requested quote_qty as market order is executed in ioc style.

Market order time in force should be ioc

Fee currency:
Fee currency is trade result currency,
if you buy BTC-USDT, fee currency is BTC,
if you sell BTC-USDT, fee currency is USDT,

Boolean fields:
Json body boolean field should not be quoted in string
* Correct usage: {"post_only": true}
* Wrong usage: {"post_only": "true"}



Post json body

Parameter Type Required Default Description
pair string true "" pair
qty string true "" Order size (limit order or sell-market order)
quote_qty string true "" Size in quoted currency used only for buy market order
side string true "" Order side
price string false "0.0" Order price, not required for market order
order_type string false "limit" Order type
time_in_force string false "gtc" Time in force
label string false "" User defined label
post_only bool false false Indicate post only or not
reject_post_only bool false false Indicate reject post only or not
mmp bool false false Indicate mmp or not
self_trading_mode int false 0 Self trading mode

Response

Name Type Desc
order_id string Order ID
created_at integer Create timestamp
updated_at integer Update timestamp
user_id string User ID
pair string pair
order_type string Order type
side string Order side
price string Order price
qty string Order quantity
quote_qty string Order quote quantity (only for buy-market order)
time_in_force string Time in force
avg_price string Average filled price
filled_qty string Filled qty
status string Order status
taker_fee_rate string Taker fee rate
maker_fee_rate string Maker fee rate
cancel_reason string Order cancel reason
label string User defined label
post_only bool Indicate post only or not
reject_post_only bool Indicate reject post only or not
source string Order source
mmp bool Indicate mmp or not

Cancel orders

POST /spot/v1/cancel_orders


curl -X POST "https://betaspot-api.bitexch.dev/spot/v1/cancel_orders" -H "Content-Type: application/json" -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113"  -d '{"order_id": "44092860", "timestamp": 1590572422557, "signature": "3c8c2271a58e3d11dfbd262a6be40ebdd07e8f394a002db0065068b36bc66d5a"}' 



Response

{
    "code": 0,
    "message": "",
    "data":{
        "num_cancelled": 2,
        "order_ids": [44092860]
    }
}

Filters:

Post json body

Parameter Type Required Default Description
order_id string false "" Order ID
pair string false "" Pair
label string false "" Order label

Response

Name Type Desc
num_cancelled integer number of order cancelled
order_ids array Order id array

Amend orders

POST /spot/v1/amend_orders


curl -X POST "https://betaspot-api.bitexch.dev/spot/v1/amend_orders" -H "Content-Type: application/json" -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113"  -d '{"order_id": "1206764", "price": "60010", "timestamp": 1590760362688, "signature": "a74dda0f2bdaf1e1587a5e7577a281497cb66607166bd3b7e0cc4c805c750bf1"}' 



Response

{
    "code": 0,
    "message": "",
    "data": {
        "order_id": "1206764",
        "created_at": 1589523803017,
        "updated_at": 1589523803017,
        "user_id": "51140",
        "pair": "BTC-USDT",
        "order_type": "limit",
        "side": "buy",
        "price": "60010",
        "qty": "3.00000000",
        "quote_qty": "0.00000000",
        "time_in_force": "gtc",
        "avg_price": "0.00000000",
        "filled_qty": "0.00000000",
        "status": "open",
        "taker_fee_rate": "0.00050000",
        "maker_fee_rate": "0.00020000",
        "cancel_reason": "",
        "label":"hedge",
        "source": "api",
        "post_only": false,
        "reject_post_only": false,
        "mmp": false
    }
}

Amend order.
Order id is required.
Need to provide at least one of: price, qty or mmp.

Post json body

Parameter Type Required Default Description
order_id string true "" Order ID
price string false "" New price of the order
qty string false "" New quantity of the order
mmp boolean false "" Whether the order should be included in MMP mechanism
self_trading_mode int false 0 Self trading mode

Response

Name Type Desc
order_id string Order ID
created_at integer Create timestamp
updated_at integer Update timestamp
user_id string User ID
pair string pair
order_type string Order type
side string Order side
price string Order price
qty string Order quantity
quote_qty string Order quote quantity (only for buy-market order)
time_in_force string Time in force
avg_price string Average filled price
filled_qty string Filled qty
status string Order status
taker_fee_rate string Taker fee rate
maker_fee_rate string Maker fee rate
cancel_reason string Order cancel reason
label string User defined label
post_only bool Indicate post only or not
reject_post_only bool Indicate reject post only or not
source string Order source
mmp bool Indicate mmp or not

Get open orders

GET /spot/v1/open_orders

curl -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113" "https://betaspot-api.bitexch.dev/spot/v1/open_orders?pair=BTC-USDT&i&timestamp=1589523178651&signature=2092cebba4f082f9c8718344cdad9bed83950b5fe90b3a875b708898bfd89b20" 


Response

{
    "code": 0,
    "message": "",
    "data": [{
        "order_id": "7718222",
        "created_at": 1589202185000,
        "updated_at": 1589460149000,
        "user_id": "51140",
        "pair": "BTC-USDT",
        "order_type": "limit",
        "side": "buy",
        "price": "60000",
        "qty": "3.00000000",
        "quote_qty": "0.00000000",
        "time_in_force": "gtc",
        "avg_price": "0.00000000",
        "filled_qty": "0.00000000",
        "status": "open",
        "fee": "0.00000000",
        "taker_fee_rate": "0.00050000",
        "maker_fee_rate": "0.00020000",
        "cancel_reason": "",
        "label":"hedge",
        "source": "api",
        "post_only": false,
        "reject_post_only": false,
        "mmp": false
    }]  
}

Get user open orders.

Query parameters

Parameter Type Required Default Description
pair string false "" pair

Response

Name Type Desc
order_id string Order ID
created_at integer Create timestamp
updated_at integer Update timestamp
user_id string User ID
pair string pair
order_type string Order type
side string Order side
price string Order price
qty string Order quantity
quote_qty string Order quote quantity (only for buy-market order)
time_in_force string Time in force
avg_price string Average filled price
filled_qty string Filled quantity
status string Order status
fee string Transaction fees
taker_fee_rate string Taker fee rate
maker_fee_rate string Maker fee rate
cancel_reason string Order cancel reason
label string User defined label
post_only bool Indicate post only or not
reject_post_only bool Indicate reject post only or not
source string Order source
mmp bool Indicate mmp or not

Get orders

GET /spot/v1/orders

curl -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113" "https://betaspot-api.bitexch.dev/spot/v1/orders?pair=BTC-USDT&order_id=7718222&start_time=1585270800000&end_time=1589522084000&i&timestamp=1589523178651&signature=2092cebba4f082f9c8718344cdad9bed83950b5fe90b3a875b708898bfd89b20" 


Response

{
    "code": 0,
    "message": "",
    "data": [{
        "order_id": "7718222",
        "created_at": 1589202185000,
        "updated_at": 1589460149000,
        "user_id": "51140",
        "pair": "BTC-USDT",
        "order_type": "limit",
        "side": "buy",
        "price": "60000",
        "qty": "3.00000000",
        "quote_qty": "0.00000000",
        "time_in_force": "gtc",
        "avg_price": "0.00000000",
        "filled_qty": "0.00000000",
        "status": "cancelled",
        "fee": "0.00000000",
        "taker_fee_rate": "0.00050000",
        "maker_fee_rate": "0.00020000",
        "cancel_reason": "",
        "label":"hedge",
        "source": "api",
        "post_only": false,
        "reject_post_only": false,
        "mmp": false,
    }],
    "page_info": {
        "has_more": false
    }      
}

Get user order history.

if user input order_id, other filters will be ignored.

Query parameters

Parameter Type Required Default Description
pair string false "" pair
order_id string false "" Order ID
label string false "" Order label
start_time integer false One month ago Start timestamp millisecond
end_time integer false Now End timestamp millisecond
start_id integer false Start order id
end_id integer false End order id
offset int false 1 Page index, first page = 1
limit int false 100 Page size

Response

Name Type Desc
order_id string Order ID
created_at integer Create timestamp
updated_at integer Update timestamp
user_id string User ID
pair string pair
order_type string Order type
side string Order side
price string Order price
qty string Order quantity
quote_qty string Order quote quantity (only for buy-market order)
time_in_force string Time in force
avg_price string Average filled price
filled_qty string Filled quantity
status string Order status
fee string Transaction fees
taker_fee_rate string Taker fee rate
maker_fee_rate string Maker fee rate
cancel_reason string Order cancel reason
label string User defined label
post_only bool Indicate post only or not
reject_post_only bool Indicate reject post only or not
source string Order source
mmp bool Indicate mmp or not

Get user trades

GET /spot/v1/user/trades

curl -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113" "https://betaspot-api.bitexch.dev/spot/v1/user/trades?pair=BTC-USDT&order_id=17551020&start_time=1585270800000&end_time=1589522084000&count=10&timestamp=1589523590679&signature=c4788e3a77b6000424b55067f9ba38009b34d12e482b1c80186756857c869bb5" 


Response

{
    "code": 0,
    "message": "",
    "data": [{
        "trade_id": "23210268",
        "order_id": "17551020",
        "pair": "BTC-USDT",
        "qty": "2.00000000",
        "price": "60000",
        "fee": "0.00100000",
        "fee_rate": "0.00050000",
        "side": "buy",
        "created_at": 1589521371000,
        "order_type": "limit",
        "is_taker": true
    }] 
}

Get user trades


Query parameters

Parameter Type Required Default Description
pair string false "" Currency pair
order_id string false "" Order ID
start_time integer false One month ago Start timestamp millisecond
end_time integer false Now End timestamp millisecond
start_id integer false Start Id
end_id integer false End Id
count int false 100 Trade count, max 1000

Response

Name Type Desc
order_id string Order ID
trade_id string Trade ID
pair string Currency pair
created_at integer Create timestamp
order_type string Order type
side string Order side
price string Trade price
qty string Trade quantity
fee string Transaction fees
fee_rate string Fee rate
is_taker boolean Is taker or not

Wallet

Bit.com has three types of account: spot account, derivative account and balance account. The three accounts can transfer to each other via API. Spot and derivative account surpport withdrawal via API. Sub user can't transfer and withdraw via API.

Withdraw

POST /v1/wallet/spot-withdraw

curl -X POST "https://betaapi.bitexch.dev/v1/wallet/spot-withdraw" -H "Content-Type: application/json" -H "X-Bit-Access-Key: Your Access Key" -d '{"currency": "BTC", "address": "Your address", "amount": "1.2", "pwd": "Your password", "timestamp": 1589523989378, "signature": "signature"}'

Response


{
    "code": 0,
    "message": "",
    "data": {
        "withdraw_id": "b61c2b93-8a25-44d4-9715-023cce61dc50"
    }
}

This endpoint means withdraw cash from spot account. Withdraw address need to be whitelisted first here: https://www.bit.com/propertyCenter/withdraw
Password need to be encoded to base64(sha256(pwd)). For example, if password is 123456, the encoded password will be:jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=

Query Parameter

Parameter Type Required Default Description
currency string true "" Currency, BTC
address string true "" Withdrawal address
amount string true "" Withdrawal amount
pwd string true "" Fund password
chain string false "" ETH for USDTERC, TRX for USDTTRC

Response

Name Type Description
withdraw_id string Withdraw ID, can be used in later inquires

Withdrawal history

GET /v1/wallet/spot-withdrawals

curl -H "X-Bit-Access-Key: Your Access Key" "https://betaapi.bitexch.dev/v1/wallet/spot-withdrawals?currency=BTC&limit=10&offset=0&timestamp=1589522687689&signature=signature"

Response


{
    "code": 0,
    "data": {
        "items": [{
            "address": "mfaFpdVCb6UFS5AXUhC8VGXgj9dnJ37nLP",
            "amount": "0.001",
            "code": 0,
            "confirmations": 0,
            "currency": "BTC",
            "fee": "0.00001",
            "state": "confirmed",
            "transaction_id": "52e1537002f51acbf5f52b9dfeab6a9e7cc185a669cda2573e768420b0839523",
            "created_at": 1608606000000,
            "updated_at": 1608606000000,
            "is_onchain": true
        }, {
            "address": "mfaFpdVCb6UFS5AXUhC8VGXgj9dnJ37nLP",
            "amount": "0.11",
            "code": 13100100,
            "confirmations": 0,
            "currency": "BTC",
            "fee": "0.00001",
            "state": "rejected",
            "transaction_id": "",
            "created_at": 1608606000000,
            "updated_at": 1608606000000,
            "is_onchain": false
        }]
    }
}

Retrieves the withdrawal records of spot account.

Query parameters

Parameter Type Required Default Description
currency String true "" Currency
limit int false 10 Number of requested items, Max - 50
offset int false 1 the offset for pagination
withdraw_id string false "" withdraw order id

Response

Name Type Description
code int Withdraw ID error code, 0 means normal, rest means failed
state string withdrawal state
address string Withdraw address
amount string Withdraw amount
confirmations int Confirmation counts, 0 for internal transfers since they are offchain
currency string Currency
fee string Withdraw fee
transaction_id string Transaction hash
created_at int Timestamp of the order created
updated_at int Timestamp of the order updated
is_onchain bool Whether the order is onchain

Deposits history

GET /v1/wallet/spot-deposits

curl -H "X-Bit-Access-Key: Your Access Key" "https://betaapi.bitexch.dev/v1/wallet/spot-deposits?currency=BTC&limit=10&offset=0&timestamp=1589522687689&signature=signature"

Response


{
    "code": 0,
    "data": {
        "items": [{
            "address": "mfaFpdVCb6UFS5AXUhC8VGXgj9dnJ37nLP",
            "amount": "0.001",
            "code": 0,
            "confirmations": 0,
            "currency": "BTC",
            "state": "confirmed",
            "transaction_id": "52e1537002f51acbf5f52b9dfeab6a9e7cc185a669cda2573e768420b0839523",
            "created_at": 1608606000000,
            "updated_at": 1608606000000,
            "is_onchain": true
        }]
    }
}

Retrieves the deposit records of spot account.

Query parameters

Parameter Type Required Default Description
currency String true "" Currency
limit int false 10 Number of requested items, Max - 50
offset int false 1 the offset for pagination

Response

Name Type Description
code int Deposit error code, 0 means normal, rest means failed
state string deposit state
address string Deposit address
amount string Deposit amount
confirmations int Confirmation counts, 0 for internal transfers since they are offchain
currency string Currency
transaction_id string Transaction hash
created_at int Timestamp of the order created
updated_at int Timestamp of the order updated
is_onchain bool Whether the order is onchain

Transfer

POST /v1/wallet/transfer

curl -X POST "https://betaapi.bitexch.dev/v1/wallet/transfer" -H "Content-Type: application/json" -H "X-Bit-Access-Key: Your Access Key" -d '{"currency": "BTC", "amount": "1.2", "type": 1, "timestamp": 1589523989378, "signature": "signature"}'

Response


{
    "code": 0,
    "message": ""
}

Bit.com has three types of account: spot account, derivative account and balance account. The three accounts can transfer to each other.

Post json body

Parameter Type Required Default Description
currency string true Currency, e.g. BTC
amount string true Transfer amount
type int true Transfer type, 1: spot-to-derivative, 2: derivative-to-spot, 3: spot-to-balance, 4: balance-to-spot, 5: derivative-to-balance, 6: balance-to-derivative

Transfer history

GET /v1/wallet/transfer

curl -H "X-Bit-Access-Key: Your Access Key" "https://betaapi.bitexch.dev/v1/wallet/transfer?currency=BTC&count=10&offset=0&timestamp=1589522687689&signature=signature"

Response


{
    "code": 0,
    "data": {
        "items": [{
            "status": "done",
            "currency": "BTC",
            "amount": "1.2",
            "type": 1,
            "created_at": 1608606000000,
            "id": "123"
        }, {
            "status": "done",
            "currency": "ETH",
            "amount": "1.2",
            "type": 2,
            "created_at": 1608606000000,
            "id": "124"
        }]
    }
}

Query parameters

Parameter Type Required Default Description
currency string false
limit int false 10 Number of requested items, Max - 50
offset int false 1 the offset for pagination

Response

Name Type Description
status string Transfer status, failed/done/dealing
type int 1: spot-to-derivative, 2: derivative-to-spot, 3: spot-to-balance, 4: balance-to-spot, 5: derivative-to-balance, 6: balance-to-derivative
currency string
amount string
created_at int Timestamp of the order created
order_id string transfer id

Websocket subscription

Data subscription is based on Websocket protocol. Users can send subscription requests after established Websocket connections. Connection will be auto disconnected if no subscription is initiated within 30s. All the responses will be based on the below return format.

Name Type Description
channel string Channel name
timestamp integer The timestamp (milliseconds since the Unix epoch)
data object Content

Subscription management

Request

{
    "type":"subscribe",
    "pairs":[
        "BTC-USDT",
    ],
    "channels":[
        "depth",
        "ticker",
        "kline.5",
        "order",
        "account"
    ],
    "interval": "100ms",
    "token":"be4ffcc9-2b2b-4c3e-9d47-68bf062cf651"
}

Response (success)

{
    "channel":"subscription",
    "timestamp":1587921122970,
    "data":{
        "code":0,
        "subscription":[
            "depth",
            "ticker",
            "kline.5"
        ]
    }
}

Response (failure)

{
    "channel":"subscription",
    "timestamp":1587921122970,
    "data":{
        "code":13200302,
        "message":"auth failed: invalid token"
    }
}

Users can subscribe to different channels, public and private. Private channel requires token and authentication.

Channels have different specifications, see details in the documentations below.

Users can set the push frequency with the parameter interval.
* interval=raw, the channel will push the updates immediately.
* interval=100ms, the updates within 100ms period will be aggregated and pushed out, note: if no updates within 100ms, no data will be pushed.
* interval=fixed100ms, data will be pushed every 100ms no matter has update or not (Only apply to order_book channel currently).

If the subscription request contains more than one channel and one of them failed, you will receive two separate responses.

Users can stop the feed by submitting an unsubscribe request.

Parameters

Name Type Description
type string [subscribe, unsubscribe]
channels string[] List of channels
pairs string[] List of currency pairs
interval string [raw, 100ms, fixed100ms] default value is raw
token string Authentication token for private channel

interval parameter:

Response

Name Type Description
code integer 0 means success, !=0 means failure
message string Error message, return when failed
subscription string[] Subscription list, return when successful

Authentication Token

GET /spot/v1/ws/auth

Request

curl -H "X-Bit-Access-Key: ak-ba3bd026-29e6-443b-8eb6-d2ea3b607113" "https://betaspot-api.bitexch.dev/spot/v1/ws/auth?timestamp=1588996062516&signature=9ed1dd821cc6464d2cfc5bf9614df1f22611c977b513e1ffde864a673b6915f0" 

Response

{
    "code":0,
    "message":"",
    "data":{
        "token":"be4ffcc9-2b2b-4c3e-9d47-68bf062cf651"
    }
}

To connect private websocket channels, user needs to first call GET /spot/v1/ws/auth to acquire a token, which will be used to fill in private websocket channel subscription for websocket authentication.

Each token is used for single websocket connection, user needs to acquire new token if reconnect.

For websocket connection, user only need to do authentication in first private channel subscription, subsequent private subscription do not need authenticate.

Parameters

None

Response

Name Type Description
token string private channel authentication token

Heartbeat

According to RFC 6455, Websocket protocol uses PING/PONG to indicate connection is alive.

Server sends PING to client every minute through Websocket, client responds with PONG. Connection will be closed if PONG is not received after one minute.

Client can also send PING to check if the server is still responsive.

PING/PONG are both control frames. PING's opcode is 0x9,PONG's opcode is 0xA. One can refer to this link

Channel Summary

Channel Scope Arguments Description
depth public pairs Changes to the order book
order_book.{group}.{depth} public pairs Order book based on specified group and depth
depth1 public pairs Top of order book bid/ask
ticker public pairs The most recent traded price and trading summary
kline.{resolution} public pairs Kline data
trade public pairs Trades of the specified currency pair
market_trade public Trades of all available currency pairs
account private User's account information
order private User's order information
user_trade private User's trade information
mmp_frozen private MMP frozen event

Depth Channel

Request

{
    "type":"subscribe",
    "pairs":[
        "BTC-USDT"
    ],
    "channels":[
        "depth"
    ],
    "interval": "100ms"
}

Response (snapshot)

{
    "channel":"depth",
    "timestamp":1587929552250,
    "data":{
        "type":"snapshot",
        "pair":"BTC-USDT",
        "sequence":9,
        "bids":[
            [
                "0.08000000",
                "0.10000000"
            ]
        ],
        "asks":[
            [
                "0.09000000",
                "0.20000000"
            ]
        ]
    }
}

Response (update)

{
    "channel":"depth",
    "timestamp":1587930311331,
    "data":{
        "type":"update",
        "pair":"BTC-USDT",
        "sequence":10,
        "prev_sequence":9,
        "changes":[
            [
                "sell",
                "0.08500000",
                "0.10000000"
            ]
        ]
    }
}

depth channel can have two message types: snapshot and update. Snapshot sends snapshots of the current order book. Updates sends changes of the order book.

The first message will always be a snapshot followed by updates, if there is any sort of disruption, a new snapshot will be sent follow by updates.

A snapshot includes bids and asks depths, each depth layer consists of two elements: price and quantity.

A normal update message contains sequence and prev_sequence, with the prev_sequence matching the previous update.

Changes in update is a result in a change in depth, every changes consists of three elements: side, price and quantity. Quantity=0 means a layer is been removed from the depth.

Channel Information

Channel Scope Arguments Interval
depth public pairs [raw, 100ms]

Response

Name Type Description
type string [snapshot, update]
pair string Currency pair
sequence integer Order book update sequence
asks array of [price, quantity] Asks, price and quantity are string, return when type=snapshot
bids array of [price, quantity] Bids, price and quantity are string, return when type=snapshot
prev_sequence integer Previous update sequence number, return when type=update
changes array of [side, price, quantity] Depth changes, side、price、quantity are string, quantity=0 means deletion, return when type = update

Order Book Channel

Request

{
    "type":"subscribe",
    "pairs":[
        "BTC-USDT"
    ],
    "channels":[
        "order_book.10.10"
    ],
    "interval": "100ms"
}

Response

{
    "channel":"order_book.10.10",
    "timestamp":1587930311331,
    "data":{
        "pair":"BTC-USDT",
        "sequence":3,
        "bids":[
            [
                "0.00200000",
                "0.50000000"
            ],
            [
                "0.00100000",
                "0.30000000"
            ]
        ],
        "asks":[
            [
                "0.00300000",
                "0.20000000"
            ]
        ]
    }
}

order_book pushes certain layers of an order book data based on group and depth.

An order book message includes bids and asks depths, each depth layer consists of two elements: price and quantity.

Channel Information

Channel Scope Arguments Interval
order_book.{group}.{depth} public pairs [raw, 100ms,fixed100ms]

When subscribing to orderbook channel, user will need to specify group and depth in channel

Default is group=1, depth=10

Order book price aggregation example

Assume price_step = 0.01

raw depth:
bids: [[0.13, 3], [0.19, 7], [0.26, 5], [0.77, 12.3]]

for orderbook.10.5, aggregation price level = 0.01 * 10 = 0.1
output bids: [[0.1, 10], [0.2, 5], [0.7, 12.3]]

Response

Name Type Description
pair string Currency pair
sequence integer Order book update sequence
asks array of [price, quantity] Asks, price and quantity are string
bids array of [price, quantity] Bids, price and quantity are string

Depth1 Channel

Request

{
    "type":"subscribe",
    "pairs":[
        "BTC-USDT"
    ],
    "channels":[
        "depth1"
    ],
    "interval": "100ms"
}

Response

{
    "channel":"depth1",
    "timestamp":1587932635873,
    "data":{
        "pair":"BTC-USDT",
        "best_ask":"0.08500000",
        "best_ask_qty":"0.10000000",
        "best_bid":"0.08000000",
        "best_bid_qty":"0.10000000",
    }
}

depth1 pushes top of book bid/ask information

Channel Information

Channel Scope Arguments Interval
depth1 public pairs [raw, 100ms]

Response

Name Type Description
pair string Currency pair
best_ask string Best ask price, empty if there aren't any asks
best_ask_qty string Quantity of best ask
best_bid string Best bid price, empty if there aren't any bids
best_ask_qty string Quantity of best bid

Ticker Channel

Request

{
    "type":"subscribe",
    "pairs":[
        "BTC-USDT"
    ],
    "channels":[
        "ticker"
    ],
    "interval": "100ms"
}

Response

{
    "channel":"ticker",
    "timestamp":1589126498813,
    "data":{
        "time":1589126498800,
        "pair":"BTC-USDT",
        "best_bid":"50200.50000000",
        "best_ask":"50201.00000000",
        "best_bid_qty":"2.30000000",
        "best_ask_qty":"0.80000000",
        "last_price":"50200.80000000",
        "last_qty":"0.10000000",
        "open24h":"50500.00000000",
        "high24h":"50500.00000000",
        "low24h":"50100.00000000",
        "price_change24h":"-0.00592475",
        "volume24h":"0.10000000",
        "quote_volume24h":"5020.08000000"
    }
}

ticker pushes the most recent traded price and the last 24 hrs trading summary.

Channel Information

Channel Scope Arguments Interval
ticker public pairs [raw, 100ms]

Response

Name Type Description
pair string Currency pair
last_price string Most recent traded price
last_qty string Most recent traded volume
open24h string Open price during previous 24 hour
high24h string Highest price during previous 24 hour
low24h string Lowest price during previous 24 hour
volume24h string Sum volume during previous 24 hour
quote_volume24h string Sum quote volume during previous 24 hour
price_change24h string Price change% during previous 24 hour
best_bid string Best bid price, empty if there aren't any bids
best_ask string Best ask price, empty if there aren't any asks
best_bid_qty string Quantity of best bid
best_ask_qty string Quantity of best ask
time integer Ticker timestamp (milliseconds since the Unix epoch)

Kline Channel

Request

{
    "type":"subscribe",
    "pairs":[
        "BTC-USDT"
    ],
    "channels":[
        "kline.5"
    ],
    "interval": "100ms"
}

Response

{
    "channel":"kline.5",
    "timestamp":1587979850118,
    "data":{
        "pair":"BTC-USDT",
        "tick":1587979800000,
        "open":"7737.50000000",
        "low":"7737.50000000",
        "high":"7737.50000000",
        "close":"7737.50000000",
        "volume":"0.00000000"
    }
}

kline pushed kline data. If there is no trade during the current period, the previous close will be used for open, high and low.

Channel Information

Channel Scope Arguments Interval
kline.{timeframe} public pairs [raw, 100ms]

When subscribing to kline channel, user will need to specify timeframe.

Support timeframes:

Timeframe Name Desc
1 1 minute
3 3 minute
5 5 minute
15 15 minute
30 30 minute
60 60 minute
240 240 minute
1d daily
1w weekly
1m monthly

Response

Name Type Description
pair string Currency pair
tick integer Tick starting time
open string Open price
close string Close price
high string High price
low string Low price
volume string Volume

Trade Channel

Request

{
    "type":"subscribe",
    "pairs":[
        "BTC-USDT"
    ],
    "channels":[
        "trade"
    ],
    "interval": "100ms"
}

Response

{
    "channel":"trade",
    "timestamp":1588997059735,
    "data":[
        {
            "trade_id":"2388418",
            "pair":"BTC-USDT",
            "price":"0.01800000",
            "qty":"0.10000000",
            "side":"buy",
            "created_at":1588997060000
        }
    ]
}

trade pushes trading information of the specified currency pair

Channel Information

Channel Scope Arguments Interval
trade public pairs [raw, 100ms]

Response

Name Type Description
pair string Currency pair
trade_id string Trade ID
price string Price
qty string Quantity
side string Taker trade side
created_at integer Trade timestamp (milliseconds since the Unix epoch)

Market Trade Channel

Request

{
    "type":"subscribe",
    "channels":[
        "market_trade"
    ],
    "interval": "100ms"
}

Response

{
    "channel":"market_trade",
    "timestamp":1588997059735,
    "data":[
        {
            "trade_id":"2388418",
            "pair":"BTC-USDT",
            "price":"0.01800000",
            "qty":"0.10000000",
            "side":"buy",
            "created_at":1588997060000
        }
    ]
}

market_trade pushes trading information of all available currency pairs

Channel Information

Channel Scope Arguments Interval
market_trade public [raw, 100ms]

Response

Name Type Description
pair string Currency pair
trade_id string Trade ID
price string Price
qty string Quantity
side string Taker trade side
created_at integer Trade timestamp (milliseconds since the Unix epoch)

Account Channel

Request

{
    "type":"subscribe",
    "channels":[
        "account"
    ],
    "interval": "100ms",
    "token":"6d501ded-3c40-4697-b390-218a54b9de19"
}

Response

{
    "channel":"account",
    "timestamp":1589031930115,
    "data":{
        "user_id": "1001",
        "balances": [
          {
            "currency": "BTC",
            "available":"99.59591877",
            "frozen":"0.00000000"
          }
        ]
    }
}

account pushes user's account information

Channel Information

Channel Scope Arguments Interval
account private [raw, 100ms]

Response

Name Type Description
user_id string User ID
balances array of Balance Balance list
Name Type Description
currency string Currency
available string Available amount
frozen string Frozen amount

Order Channel

Request

{
    "type":"subscribe",
    "channels":[
        "order"
    ],
    "interval": "100ms",
    "token":"6d501ded-3c40-4697-b390-218a54b9de19"
}

Response

{
    "channel":"order",
    "timestamp":1587994934089,
    "data":[
        {
            "order_id":"1590",
            "created_at":1587870609000,
            "updated_at":1587870609000,
            "user_id":"51140",
            "pair":"BTC-USDT",
            "order_type":"limit",
            "side":"buy",
            "price":"0.16000000",
            "qty":"0.50000000",
            "time_in_force":"gtc",
            "avg_price":"0.16000000",
            "filled_qty":"0.10000000",
            "status":"open",
            "fee":"0.00002000",
            "taker_fee_rate":"0.00050000",
            "maker_fee_rate":"0.00020000",
            "label":"hedge",
            "mmp": false
        }
    ]
}

order pushes user's order information

Channel Information

Channel Scope Arguments Interval
order private [raw, 100ms]

Response

Name Type Description
pair string Currency pair
order_id string Order ID
created_at integer Timestamp at order creation (milliseconds since the Unix epoch)
updated_at integer Timestamp at order update (milliseconds since the Unix epoch)
user_id string User ID
qty string Quantity
filled_qty string Filled quantity
price string Order price
avg_price string Average filled price
side string Order side
order_type string Order type
time_in_force string Order time in force
status string Order status
fee string Fee
taker_fee_rate string Taker fee rate
maker_fee_rate string Maker fee rate
label string User defined label
mmp boolean Indicate mmp order or not

User Trade Channel

Request

{
    "type":"subscribe",
    "channels":[
        "user_trade"
    ],
    "interval": "100ms",
    "token":"6d501ded-3c40-4697-b390-218a54b9de19"
}

Response

{
    "channel":"user_trade",
    "timestamp":1588997059737,
    "data":[
        {
            "trade_id":"2388418",
            "order_id":"1384232",
            "pair":"BTC-USDT",
            "qty":"0.10000000",
            "price":"0.01800000",
            "fee":"0.00005000",
            "fee_rate":"0.00050000",
            "side":"buy",
            "created_at":1588997060000,
            "is_taker":true,
            "order_type":"limit"
        }
    ]
}

user_trade pushes user trade information

Channel Information

Channel Scope Arguments Interval
user_trade private [raw, 100ms]

Response

Name Type Description
order_id string Order ID
trade_id string Trade ID
pair string Currency pair
order_type string User Order type
side string User Order side
price string Trade price
qty string Trade quantity
fee string Transaction fees
fee_rate string Fee rate
is_taker boolean Is taker or not
created_at integer Timestamp at trade creation (milliseconds since the Unix epoch)

MMP Frozen Event Channel

Request

{
    "type":"subscribe",
    "channels":[
        "mmp_frozen"
    ],
    "interval": "100ms",
    "token":"6d501ded-3c40-4697-b390-218a54b9de19"
}

Response

{
    "channel":"mmp_frozen",
    "timestamp":1599277666000,
    "data":{
        "pair":"BTC-USDT",
        "frozen_until_ms":1599277929000
    }
}

mmp_frozen pushes MMP frozen event

frozen_until_ms indicate MMP frozen status.
frozen_until_ms > 0: frozen until this timestamp or a manual reset
frozen_until_ms = 0: frozen until a manual reset

Channel Information

Channel Scope Arguments Interval
mmp_frozen private [raw, 100ms]

Response

Name Type Description
pair string Currency pair
frozen_until_ms integer MMP frozen until timestamp

Websocket RPC

Overview

Request

{
    "type":"RPC_name",
    "token":"If3Fy-o5TiOOTfvlmtryR0MTiziutYaYFkH3aRovJWWEXqCAD7CIdnbhGG5bwRqLRrGkOFEOjh0L",
    "params":{
        "param1":"hello"
    }
}

Response

{
    "type":"RPC_name",
    "result":{
        "code":0,
        "message":"",
        "data":{
            "field1":"world"
        }
    }
}

After the websocket connection is established, in addition to data subscription, it also supports RPC in JSON.

Private requests need token get from rest API and authentication at the first time. For details please link to Authentication Token.

Parameters

Name Type Description
type string Request type
token string Private request authentication token
params object Parameters

Response

Name Type Description
type string Request type
result object Result

result object

Name Type Description
code integer Error code
message string Error message
data object Response data

Enable or disable Cancel On Disconnect

Request

{
    "type":"cancel_on_disconnect",
    "token":"If3Fy-o5TiOOTfvlmtryR0MTiziutYaYFkH3aRovJWWEXqCAD7CIdnbhGG5bwRqLRrGkOFEOjh0L",
    "params":{
        "scope":"connection",
        "enable":true
    }
}

Response

{
    "type":"cancel_on_disconnect",
    "result":{
        "code":0,
        "message":"",
        "data":""
    }
}

When a COD-Enabled websocket connection is dropped, all open orders of the user will be canceled. Differences between rest API account_configs/cod and this interface:

Request Information

Request Type Scope
cancel_on_disconnect private

Parameters

Name Type Description
scope string COD scope, currently only support connection
enable bool true=enable COD ,false=disable COD

Response

None

Constant definitions

Order side

Order side Description
buy Buy
sell Sell

Order type

OrderType Description
limit Limit order
market Market order

Order status

Status Description
pending Order initial state
open Order active state
filled Order fully filled
cancelled Order is cancelled

Order time in force

Status Description
gtc Good till cancel
fok Fill or kill
ioc Immediate or cancel

Transaction log type

Tx log type Description
trade-pay Paying out cash for a trade
trade-recv Receiving cash of a trade
fee-collection Collecting fee
deposit Deposit
bad-deposit Deposit rollback
withdraw Withdraw
withdraw-revert Withdraw refund
transfer-in Fund transfer in
transfer-out Fund transfer out
invite-rebate Invite rebate
invite-rebate-refund Revert the invite rebate awarded

Order source

Order source Description
api From API
web From Web GUI
app From mobile app

Self trading mode

Self-trading mode Description
0 Cancel taker(default)
1 Cancel maker
2 Allow match

Errors

Error Handling

A clarification of bit.com trading APIs:


When calling the trading APIs of bit.com to, e.g. placing, editing, cancelling orders, the caller will get one of the following four types of results:

  1. A response indicating the request was successful
  2. A response indicating the request had been rejected
  3. A response indicating failed to get the processing result of the request
  4. Failed to receive a response (should be handled similarly to type 3, see below)

A result of type 3. happens when the frontend web servers of bit.com failed to receive a response from the matching engine in time (due to a network issue or a timeout). The response can be in the form of

  1. A HTTP response with status "504 - Gateway Timeout", when the failure was at the gateway layer.
  2. A HTTP response with status "200 - OK", but the JSON error code = 18500000 (Rpc timeout)
  3. Other forms of network errors if the failure was even before the gateway of bit.com.

When a result of type 3 happens, it is unknown to the caller whether the sent request has been received/processed/rejected by the matching engine. Therefore, the caller has to make another call checking the state of the order or the account to find out.

Error code list

Bit.com API error codes:

Error Code Description
0 Success (no error)
18100100 General Error
18100101 Invalid Order Request
18100102 Invalid Order Side
18100103 Invalid Order Price
18100104 Invalid Order Quantity
18100105 Invalid Order Type
18100106 Invalid Time In Force
18100107 Get Position Error
18100109 Get Underlying Price Fail
18100110 Place Order Error
18100111 Marshal Order Error
18100112 Submit Order Request Error
18100113 Invalid Order ID
18100114 Get Order Error
18100115 Order Not Found
18100116 Submit Order Cancel Error
18100117 Invalid Order Status Parameter
18100119 Get Trade Error
18100131 Bad Transfer Request
18100132 Invalid Transfer Quantity
18100133 Create Transfer Error
18100134 Get User Trade Error
18100135 Get Transfer Error
18100137 Get Account Error
18100138 Get Trades Error
18100143 Get Ticks Error
18100146 Update Account Error
18100147 Get Transaction Log Error
18100148 Audit Account Error
18100149 Delivery Information Error
18100150 Exceed Max Open Order By Account
18100151 Exceed Max Open Order By Instrument
18100152 Get Open Order Count Error
18100154 Update Access Token Error
18100157 Bad Config Error
18100158 Update Config Error
18100159 Get Fee Rate Error
18100160 Invalidate Parameters Error
18100161 Get Orderbook Error
18100162 Get Index Error
18100163 Big Account Information Error
18100164 Get Uc Transfer Record Error
18100165 Invalid User Error
18100166 Insurance Account Error
18100167 Insurance Log Error
18100168 Fee Account Error
18100169 Fee Log Error
18100170 Get Delivery Error
18100171 Get Insurance Data Error
18100172 Invalid Depth Error
18100173 Invalid Expired Error
18100174 Get Orderbook Summary Error
18100175 Get Settlement Error
18100176 Get Trading View Data Error
18100177 Get User Error
18100178 Save User Error
18100180 Invalid Order Cancel Request
18100181 Get Instrument Error
18100185 Invalid Instrument
18100186 Close Position Request Error
18100187 Get Order Margin Error
18100188 Get Limit Price Error
18100189 Invalid Stop Price
18100190 Get Open Stop Order Count Error
18100191 Exceed Max Open Stop Order
18100192 Invalid Order Stop Price
18100193 Invalid Order Trigger Type
18100194 Save Stop Order Failed
18100199 Insufficient Balance Error
18100200 Invalid Transaction Type Error
18100201 Get Index Data Error
18100202 Invalid Argument Error
18100204 Invalid Page Parameter Error
18100205 Get Market Summary Error
18100206 System Account Error
18100210 Invalid Operator Id Error
18100211 Get Takeover Records Error
18100212 Invalid Operator User Ids
18100213 Start Takeover
18100214 Invalid Account Id
18100215 Exit Admin Takeover
18100216 Link Admin To Account
18100217 Unlink Admin From Account
18100218 Calc Portfolio Margin
18100223 Get Takeover Orders Error
18100224 Invalid Amend Order Request Error
18100225 Auto Price Error
18100226 Takeover Switch User Id Error
18100227 Account Is Locked Error
18100228 Get Bankruptcy Error
18100229 Filled Bankruptcy Request Error
18100230 Exceed Max Stop Order Error
18100231 Invalid Stop Order Status Error
18100232 Verification Code Mail Error
18100233 Verification Code Phone Error
18100234 Rpc Error: Order not active
18100235 Fill Bankruptcy Error
18100236 Invalid Order Role
18100237 No Block Order Permission
18100238 Self Trading Error
18100239 Illegal Valid Time Error
18100240 Invalid Block Order Request
18100241 Accept Block Order Error
18100242 Reject Block Order Error
18100244 Reduce Only Error
18100245 Block Trade Service Stop Error
18100246 Get Stop Trigger Price Error
18100247 Get Open Order Size Error
18100248 Get Position Size Error
18100253 Get Bonus Error
18100254 Marketing Refund Request Error
18100255 Refund Error
18100256 Get Active Error
18100257 Get Account Configuration Error
18100258 Invalid User Kyc Level Error
18100259 Duplicate Bonus Error
18100260 Calc Position Summary Error
18100261 Exceed Account Delta Error
18100262 Withdraw Request Error
18100263 Withdraw Error
18100264 Invalid User Defined String
18100265 Invalid Blocktrade Source
18100266 Send Captcha Error
18100267 Invalid Captcha Error
18100268 Invalid Number String
18100269 Exceed Max Position Error
18100270 Exceed Max Open Quantity Error
18100271 Get Block Order Error
18100272 Duplicated Blocktrade Key
18100273 Creat Bonus Active Error
18100274 Bonus Total Limit Error
18100275 Invalid Batch Order Request
18100276 Invalid Batch Order Count Request
18100277 Rpc New Batch Order Error
18100278 Fetch Db Timeout
18100279 Takeover Not Allowed
18100280 Invalid Batch Order Amend Request
18100281 Not Found In Open Orders
18100282 Rpc Batch Amend Error
18100285 Mmp error
18100304 Invalid Channel Error
18100305 Invalid Category Error
18100306 Invalid Interval Error
18100401 Invalid Address
18100402 Address Not Whitelisted
18100403 Invalid Fund Password
18100404 Withdrawal Order Not Exist
18100405 KYT Rejected
18100406 Withdraw Too Frequently
18100407 Withdraw Limit Exceeded
18100408 Withdraw Amount Less Than Minimum Amount
18100800 Get UserConfig Error
18200300 Rate Limit Exceed
18200301 Login Error
18200302 Authentication Error, auth code:
17002012: no permission to access this endpoint
17002011: invalid IP address
17002010: signature error
17002014: timestamp expired
17002006: internal error
18200303 Exceed Max Connection Error
18300300 Not Part In Competition
18300301 Register Competition Failed
18300302 Registered Competition
18400300 Cancel Only Period
18500000 Rpc timeout error (API result in uncertain state, see above info)