Introduction

Welcome to BitMart trader and developer documentation. These documents outline exchange functionality, market details, and APIs.

APIs are separated into two categories: trading and feed. Trading APIs require authentication and provide access to placing orders and other account information. Feed APIs provide market data and are public.

By accessing the BitMart Market Data API, you agree to be bound by the Market Data Terms of Use.

 

Legal

All APIs are used at your risk and expense. We are not responsible for any negligence, error, compromised security, malfunction, cyberattack, or other force majeure affecting this environment. You hereby release us, hold us harmless, and indemnify us from any and all damages, losses, or claims associated with your use of this environment.

 

Contact

Join our Telegram API Group.

 

Q&A

Q: Can we use multiple valid token at the same time?

A: Yes you may request multiple token and use at the same time.

Q: Do I need to request token every time before I make a functional call?

A: No you don't have to because the token expiration time is 2 hours which means you can get a token and use this token to make functional calls until the token expires. However, if you are trying to request token above rate limit (5 times per minute), you will get error back.

Q: What is the limit rate of the REST api?

A: The limit rate for token access is 5 times per minute, and the limit rate for other RESTful api is at most 1000s per second, and the api access is IP sensitive.

Q: Is there any other limit for the api?

A: Yes, our backend will evaluate user's trading behavior against the average user. The api abuse users will be banned from 1 day to 7 days.

The evaluation is based on:

  • Repeatedly "one up" or "front-run" the best Bid/Ask on the Order Book
  • Spam order creation and cancellation very quickly without executing trades
  • Low (num of Trades / num of total orders) rate, that means the cancelled orders without execution rate is far bigger than the normal user
  • BMX related pairs will be amplified judged
 

Release Notes

 

2019-08-28

  • The new Websocket is launched, and we will not maintain the old one any more. Please refer to Websocket for more detail
 

2019-02-14

  • X-BM-SIGNATURE is mandatory for placing and canceling order.
  • Trade history API is added so user can track the execution history.
  • precision parameter under Order Book API is optional.
  • symbol_id is added in Ticker API.
  • Improved trading efficiency.
 

Rest API

API endpoints are available for order management, and market query. Every request must be signed using the described authentication scheme.

 

URL

https://openapi.bitmart.com

 

Parameters

Requests parameters for POST requests (authenticated) in the "Authenticated Enpoints" section are part of the PAYLOAD, not GET parameters.

Requests parameters for GET requests (non-authenticated) are GET parameters, appended to the URL being called as follows:

/<endpoint>/?parameter=value

 

Authentication

Authenticated requests require authentication using your BitMart API key. Please login and go to Account to generate API key.

 

Generate an API Key

Before being able to sign any requests, you must have an API key which is generated by our team. We will offer the following pieces which you must remember:

  • API Key
  • API Secret
 

API Key Permissions

By default, the API key will grant you access to all the APIs listed below.

 

Getting Bearer Token (OAuth 2.0)

The client can request an access token using API key and a signed message. The client makes a request to the token enpoint by adding the following parameters using the "application/x-www-form-urlencoded" format:

Parameter Type Description
grant_type String REQUIRED. Value MUST be set to "client_credentials"
client_id String API key
client_secret String HMAC-SHA256 signed request parameter map

Please check the section for sample request Get Bearer Token.

 

Sending authenticated requests

The following headers are required when sending authenticated requests:

  • _**X-BM-AUTHORIZATION**_
  • _**X-BM-TIMESTAMP**_

_**X-BM-AUTHORIZATION**_ is the concatenated string "Bearer " + Token, where the token is issued by the authorization server.

The _**X-BM-TIMESTAMP**_ header MUST be the number of milliseconds since Unix Epoch in UTC.

Your timestamp must be within 60 seconds of the API service time or your request will be considered expired and rejected. We recommend using the time endpoint to query for the API server time if you believe there may be time skew between your server and the API servers.

 

Requests

All requests and responses are application/json content type and follow typical HTTP response status codes for success and failure.

 

Public Endpoints

 

Ping

import requests

url = "https://openapi.bitmart.com/v2/ping"

response = requests.request("GET", url)

print(response.text)

Test connectivity to the REST API.

The above command returns JSON structured like this:

{}
 

Time

import requests

url = "https://openapi.bitmart.com/v2/time"

response = requests.request("GET", url)

print(response.text)

Test connectivity to the REST API and get the current server time (in milliseconds).

The above command returns JSON structured like this:

{
   "server_time": 1527777538000
}
 

Currencies

import requests

url = "https://openapi.bitmart.com/v2/currencies"

response = requests.request("GET", url)

print(response.text)

Get a list of available currencies.

The above command returns JSON structured like this:

[
   {
      "id":"ETH",
      "name":"Ethereum",
      "withdraw_enabled":true,
      "deposit_enabled":true
   },
   ...
]
 

Symbols

import requests

url = "https://openapi.bitmart.com/v2/symbols"

response = requests.request("GET", url)

print(response.text)

Get a list of symbol names.

The above command returns JSON structured like this:

[  
   "BMX_ETH",
   "XLM_ETH",
   "MOBI_ETH",
   ...
]
 

Symbols Details

import requests

url = "https://openapi.bitmart.com/v2/symbols_details"

response = requests.request("GET", url)

print(response.text)

Get the details of all symbols.

The above command returns JSON structured like this:

[
    {
        "id":"BMX_ETH",
        "base_currency":"BMX",
        "quote_currency":"ETH",
        "quote_increment":"0.1",
        "base_min_size":"0.1",
        "base_max_size":"100000000",
        "price_min_precision":6,
        "price_max_precision":8,
        "expiration":"NA"
    },
    ...
]
 

Response Details

Key Type Description
id string Trading pair id
base_currency string Base currency
quote_currency string Quote currency
quote_increment string Minimum order quantity as well as the quantity increment
base_min_size string Minimum trade volume
base_max_size string Maximum trade volume
price_min_precision number Minimum price precision (digit) used to query price and kline
price_max_precision number Maximum price precision (digit) used to query price and kline
expiration string Expiration date for limited contracts/pairs
 

Ticker

import requests

url = "https://openapi.bitmart.com/v2/ticker?symbol=BMX_ETH"

response = requests.request("GET", url)

print(response.text)

The ticker is a high level overview of the state of the market. It shows you the current best bid and ask, as well as the last trade price. It also includes information such as daily volume and how much the price has moved over the past 24 hours.

 

Request Parameter

Parameter Type Description
symbol query Trading pair symbol (optional, if not passed in, return all products' ticker information)

The above command returns JSON structured like this:

{  
    "volume":"17603607.6",
    "ask_1":"0.00010030",
    "base_volume":"1765.0",
    "lowest_price":"0.00009900",
    "bid_1":"0.00009901",
    "highest_price":"0.00011000",
    "ask_1_amount":"211",
    "current_price":"0.00009944",
    "fluctuation":"-0.0058",
    "symbol_id":"BMX_ETH",
    "url":"https://www.bitmart.com/trade?symbol=BMX_ETH",
    "bid_1_amount":"95"
}
 

Response Details

Key Type Description
symbol_id string Trading pair symbol
volume string Trading volume
base_volume string Target volume
highest_price string Highest price within 24 hr
lowest_price string Lowest price within 24 hr
current_price string Current price
ask_1 string Asked price
ask_1_amount string Asked amount
bid_1 string Bid price
bid_1_amount string Bid amount
fluctuation string Price change within 24 hr
url string Trading url at bitmart.com
 

Steps

import requests

url = "https://openapi.bitmart.com/v2/steps"

response = requests.request("GET", url)

print(response.text)

Get a list of available steps (in minutes) that could be used to query k-line data.

The above command returns JSON structured like this:

[
   1,
   3,
   5,
   15,
   30,
   45,
   60,
   120,
   180,
   240,
   1440,
   10080,
   43200
]
 

K-line

import requests

url = "https://openapi.bitmart.com/v2/symbols/BMX_ETH/kline?step=15&from=1525760116000&to=1525769116000"

response = requests.request("GET", url)

print(response.text)

Get the k-line data of a specific trading pair.

 

Request Parameters

Parameter Type Description
symbol path Trading pair symbol
from query Start time of k-line data (in milliseconds)
to query End time of k-line data (in milliseconds)
step query Steps of sampling (in minutes, default 1 min)

The above command returns JSON structured like this:

[  
    {  
        "timestamp":1525761000000,
        "open_price":"0.010130",
        "highest_price":"0.010130",
        "lowest_price":"0.010130",
        "current_price":"0.010130",
        "volume":"0.000000"
    },
    {  
        "timestamp":1525761900000,
        "open_price":"0.010130",
        "highest_price":"0.010130",
        "lowest_price":"0.010130",
        "current_price":"0.010130",
        "volume":"0.000000"
    },
    {  
        "timestamp":1525763700000,
        "open_price":"0.010130",
        "highest_price":"0.010130",
        "lowest_price":"0.010130",
        "current_price":"0.010130",
        "volume":"0.000000"
    },
    ...
]
 

Response Details

Key Type Description
data array Response data
current_price string Current price
timestamp numeric Corrresponding timestamp (in milliseconds)
volume string Trading volume
highest_price string Highest price
lowest_price string Lowest price
open_price string Open price
 

Order Book

import requests

url = "https://openapi.bitmart.com/v2/symbols/BMX_ETH/orders?precision=6"

response = requests.request("GET", url)

print(response.text)

Get the full order book.

 

Request Parameters

Parameter Type Description
symbol path Trading pair symbol
precision query Price precision whose range is defined in symbol details

precision is optional. If not passed in, use price_max_precision returned from symbols details API.

The above command returns JSON structured like this:

{  
   "buys":[
      {
         "amount":"4800.00",
         "total":"4800.00",
         "price":"0.000767",
         "count":"1"
      },
      {
         "amount":"99996475.79",
         "total":"100001275.79",
         "price":"0.000201",
         "count":"1"
      },
      ...
   ],
   "sells":[
      {
         "amount":"100.00",
         "total":"100.00",
         "price":"0.007000",
         "count":"1"
      },
      {
         "amount":"6997.00",
         "total":"7097.00",
         "price":"1.000000",
         "count":"1"
      },
      ...
   ]
}
 

Response Details

Key Type Description
amount string This is the number of coins offered at a specific price point.
total string This is the cumulation number of coins that offered to a specific price point.
price string This is the offer price by a trader or traders at a specific price point.
count string This is the total number of orders at that level.
buys array Array of 'buy' type orders
sells array Array of 'sell' type orders
 

Trade History

import requests

url = "https://openapi.bitmart.com/v2/symbols/BMX_ETH/trades"

response = requests.request("GET", url)

print(response.text)

Get a list of the most recent trades for the given symbol.

 

Request Parameter

Parameter Type Description
symbol path Trading pair symbol

The above command returns JSON structured like this:

[  
   {
      "amount":"0.05768509",
      "order_time":1527057452000,
      "price":"0.004811",
      "count":"11.99",
      "type":"buy"
   },
   ...
]
 

Response Details

Key Type Description
amount string This is the number of coins offered at a specific price point.
order_time number Order time (in milliseconds)
price string This is the offer price by a trader or traders at a specific price point.
count string This is the total number of orders traded at that that level.
type String Order type (buy or sell)
 

Authenticated Endpoints

 

Bearer Token

Get bearer token issued by the authorization server.

 

HMAC SHA256 signature

HMAC SHA256 signature will be used as the value of client_secret header.

[linux]$ echo -n "6591f7c2491db0a23a1d8ad6911c825e:8c08d9d5c3d15b105dbddaf96e427ac6:mymemo" | openssl dgst -sha256 -hmac "8c08d9d5c3d15b105dbddaf96e427ac6"
(stdin)= 18b9beb027d9ee75202655f37344ea5829c5c0d66a0781bf642bb3e944cf5019

Here is a step-by-step example of how to generate client_secret from the Linux command line using echo, openssl and curl.

Key Value
API Key 6591f7c2491db0a23a1d8ad6911c825e
API Secret 8c08d9d5c3d15b105dbddaf96e427ac6
memo mymemo (memo is the name that user gave when the API was created, you can check the name by logging into bitmart.com and check API List under Account)
Key Value
grant_type client_credentials
client_id 6591f7c2491db0a23a1d8ad6911c825e
client_secret 18b9beb027d9ee75202655f37344ea5829c5c0d66a0781bf642bb3e944cf5019 (HMAC SHA256 signed payload)
import requests
import json
import hmac
import hashlib

def create_sha256_signature(key, message): 
    return hmac.new(key, message, hashlib.sha256).hexdigest()

def get_access_token(api_key, api_secret, memo):
    url = "https://openapi.bitmart.com/v2/authentication"
    message = api_key + ':' + api_secret + ':' + memo
    data = {"grant_type": "client_credentials", "client_id": api_key, "client_secret": create_sha256_signature(api_secret, message)}
    response = requests.post(url, data = data)
    print(response.content)
    accessToken = response.json()['access_token']
    return accessToken

if __name__ == '__main__':
    access_token = get_access_token(api_key, client_secret, memo)
    print access_token

package main

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

var (
    api_key    = "6591f7c2491db0a23a1d8ad6911c825e"
    api_secret = "8c08d9d5c3d15b105dbddaf96e427ac6"
    memo       = "mymemo"
    endpoint   = "https://openapi.bitmart.com"
)

type Token struct {
    AccessToken string  `json:"access_token"`
    ExpiresIn   float64 `json:"expires_in"`
}

# params should utf8 encoded
func create_sha256_signature(key string, message string) string {
    mac := hmac.New(sha256.New, []byte(key))
    _, err := mac.Write([]byte(message))
    if err != nil {
        panic(err)
    }
    return hex.EncodeToString(mac.Sum(nil))
}

func get_access_token(api_key string, api_secret string, memo string) string {
    auth_url := endpoint + "/v2/authentication"
    message := fmt.Sprintf("%s:%s:%s", api_key, api_secret, memo)

    data := url.Values{}
    data.Set("grant_type", "client_credentials")
    data.Set("client_id", api_key)
    data.Set("client_secret", create_sha256_signature(api_secret, message))

    buf := bytes.NewBuffer([]byte(data.Encode()))

    res, err := http.Post(auth_url, "application/x-www-form-urlencoded", buf)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    token := Token{}
    err = json.Unmarshal(body, &token)
    if err != nil {
        panic(err)
    }

    return token.AccessToken
}

func main() {
    access_token := get_access_token(api_key, api_secret, memo)
    fmt.Println(access_token)
}

The above command returns JSON structured like this:

{
   "access_token":"m261aeb5bfa471c67c6ac41243959ae0dd408838cdc1a47e945305dd558e2fa78",
   "expires_in":7200
}
 

Response Details

Key Type Description
access_token string Bearer token
expires_in numeric Token expiration time (in seconds)。
 

Wallet Balances

import requests

url = "https://openapi.bitmart.com/v2/wallet"

// timestamp is in milliseconds and the authorization header is "Bearer " + token
headers = {"X-BM-TIMESTAMP": xxx, "X-BM-AUTHORIZATION": "Bearer xxxx-here-is-the-access-token"}

response = requests.get(url, headers=headers)

print(response.text)
func main() {
    access_token := get_access_token(api_key, api_secret, memo)

    URL := endpoint + "/v2/wallet"

    req, _ := http.NewRequest("GET", URL, nil)

    req.Header.Add("X-Bm-Timestamp", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
    req.Header.Add("X-Bm-Authorization", "Bearer "+access_token)

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

Get user wallet balances.

The above command returns JSON structured like this:

[
   {
        "id": "BTC"
        "available": 10,
        "name": "Bitcoin",
        "frozen": 0,
    }, 
    ...
]
 

Response Details

Key Type Description
id string short name of the currency.
name string full name of the currency.
available string amount of available currency.
frozen string amount of frozen currency.
 

Place a New Order

Create a new order.

 

HMAC SHA256 signature

HMAC SHA256 signature will be used as the value of X-BM-SIGNATURE header. We highly recommend to sign the payload in case the request body is hacked. Be aware that the order of request parameters in the signed payload must be the same as the order of parameters in the post body.

[linux]$ echo -n "amount=1&price=1&side=buy&symbol=BMX_ETH" | openssl dgst -sha256 -hmac "8c08d9d5c3d15b105dbddaf96e427ac6"
(stdin)= 2302088e474141fc7b498d0fa96c9cc2eda39a5a24fd1495d469d0a72e5fd483

Here is a sample from the Linux command line request using echo, openssl and curl.

Parameter Type Description
symbol string Trade paire symbol name like BMX_ETH
side string buy or sell
amount string decimal string value
price string decimal string value

The parameters should be sorted base on alphabetic order, which is amount, price, side and symbol. Please see the example.

import requests
import hmac
import hashlib
from urllib import urlencode

url = "https://openapi.bitmart.com/v2/orders"

// timestamp is in milliseconds and the authorization header is "Bearer " + token
// X-BM-SIGNATURE is the HMAC SHA256 signature of the request parameters encrypted by API Secret

secret = "***"
headers = {"X-BM-TIMESTAMP": ***, "X-BM-AUTHORIZATION": "***", "Content-Type": "application/json"}

// notice: the price and amount should be formatted as *.******, not scientific notation
// amount = format(amount, ".10f")
// price = format(price, ".10f")
data = {"symbol": "BMX_ETH", "amount": 1,"price": 1,"side": "buy"}

// notice: the parameters should be sorted in alphabetical order
sorted_data = sorted(data.items(), key=lambda d: d[0], reverse=False)
message = str(urlencode(sorted_data))
signed_message = hmac.new(secret, message, hashlib.sha256).hexdigest()

// if you are using python 3, it will be a little different to sign the message
// you can use: 
// signed_message = hmac.new(bytes(secret, "utf-8"), bytes(message, "utf-8"), hashlib.sha256).hexdigest()

// add signed_message to the headers
headers["X-BM-SIGNATURE"] = signed_message

data = json.dumps(data)

response = requests.post(url, data=data, headers=headers)

print(response.text)
func main() {
    amount := 1.0
    price := 1.0
    side := "buy"
    symbol := "BMX_ETH"

    access_token := get_access_token(api_key, api_secret, memo)

    URL := endpoint + "/v2/orders"

    jsdata, err := json.Marshal(map[string]interface{}{
        "amount": amount,
        "price":  price,
        "side":   side,
        "symbol": symbol,
    })
    if err != nil {
        panic(err)
    }

    buf := bytes.NewBuffer(jsdata)

    message := fmt.Sprintf(
        "amount=%s&price=%s&side=%s&symbol=%s",
        strconv.FormatFloat(amount, 'f', -1, 64),
        strconv.FormatFloat(price, 'f', -1, 64),
        side,
        symbol,
    )

    req, _ := http.NewRequest("POST", URL, buf)

    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("X-Bm-Timestamp", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
    req.Header.Add("X-Bm-Authorization", "Bearer "+access_token)
    req.Header.Add("X-Bm-Signature", create_sha256_signature(api_secret, message))

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

The request payload JSON structured like this:

{
   "symbol":"BMX_ETH",
   "amount":1,
   "price":1,
   "side":"buy"
}

The above command returns JSON structured like this:

{
   "entrust_id":1223181
}
 

Response Details

Key Type Description
entrust_id string Order id
 

Cancel an Order

Cancel a specific order.

 

HMAC SHA256 signature

HMAC SHA256 signature will be used as the value of X-BM-SIGNATURE header. We highly recommend to sign the payload in case the request body is hacked.

[linux]$ echo -n "entrust_id=1223181" | openssl dgst -sha256 -hmac "8c08d9d5c3d15b105dbddaf96e427ac6"
(stdin)= de4ed768cea4eb2f0fe081009eab1f41c5fd6ff6ed53768df7fe252472c257b3

Here is a sample request from the Linux comman line using echo, openssl and curl.

Key Value
entrust_id 1223181
import requests
import hmac
import hashlib
from urllib import urlencode

entrust_id = ***
url = "https://openapi.bitmart.com/v2/orders/%s" % entrust_id

// timestamp is in milliseconds and the authorization header is "Bearer " + token
// X-BM-SIGNATURE is the HMAC SHA256 signature of the request parameters encrypted by API Secret

secret = "***"
headers = {"X-BM-TIMESTAMP": ***, "X-BM-AUTHORIZATION": "***"}

data = {"entrust_id": entrust_id}

// notice: the parameters should be sorted in alphabetical order
sorted_data = sorted(data.items(), key=lambda d: d[0], reverse=False)
message = str(urlencode(sorted_data))
signed_message = hmac.new(secret, message, hashlib.sha256).hexdigest()

// add signed_message to the headers
headers["X-BM-SIGNATURE"] = signed_message

response = requests.delete(url, headers=headers)

print(response.text)
func main() {
    entrust_id := "1223181"
    access_token := get_access_token(api_key, api_secret, memo)

    URL := endpoint + "/v2/orders/"
    URL += entrust_id

    message := fmt.Sprintf("entrust_id=%s", entrust_id)

    req, _ := http.NewRequest("DELETE", URL, nil)

    req.Header.Add("X-Bm-Timestamp", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
    req.Header.Add("X-Bm-Authorization", "Bearer "+access_token)
    req.Header.Add("X-Bm-Signature", create_sha256_signature(api_secret, message))

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

The above command returns JSON structured like this:

{}
 

Request Parameter

Key Type Description
entrust_id path Order id
 

Cancel All Orders

import requests

url = "https://openapi.bitmart.com/v2/orders?symbol=BMX_ETH&side=buy"

// timestamp is in milliseconds and the authorization header is "Bearer " + token
headers = {"X-BM-TIMESTAMP": xxx, "X-BM-AUTHORIZATION": "xxx"}

response = requests.delete(url, headers=headers)

print(response.text)
func main() {
    access_token := get_access_token(api_key, api_secret, memo)

    URL := endpoint + "/v2/orders?symbol=BMX_ETH&side=buy"

    req, _ := http.NewRequest("DELETE", URL, nil)

    req.Header.Add("X-Bm-Timestamp", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
    req.Header.Add("X-Bm-Authorization", "Bearer "+access_token)

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

Cancel orders for given condintions.

The above command returns JSON structured like this:

{}
 

Request Parameter

Parameter Type Description
symbol query Trading pair symbol
side query buy or sell
 

Order Details

import requests

url = "https://openapi.bitmart.com/v2/orders/1223181"

// timestamp is in milliseconds and the authorization header is "Bearer " + token
headers = {"X-BM-TIMESTAMP": xxx, "X-BM-AUTHORIZATION": "xxx"}

response = requests.get(url, headers=headers)

print(response.text)
func main() {
    access_token := get_access_token(api_key, api_secret, memo)

    URL := endpoint + "/v2/orders/1223181"

    req, _ := http.NewRequest("GET", URL, nil)

    req.Header.Add("X-Bm-Timestamp", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
    req.Header.Add("X-Bm-Authorization", "Bearer "+access_token)

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

Get an order details.

The above command returns JSON structured like this:

{
   "entrust_id":1223181,
   "symbol":"BMX_ETH",
   "timestamp":1528060666000,
   "side":"buy",
   "price":"1.000000",
   "fees":"0.1",
   "original_amount":"1",
   "executed_amount":"1",
   "remaining_amount":"0",
   "status":3
}
 

Request Parameter

Parameter Type Description
entrust_id path Order id
 

Status Type

Status Description
0 All orders
1 Pending orders
2 Partially successful orders
3 Success orders
4 Canceled orders
5 Pending and partially successful orders
6 Success and canceled orders
 

Response Details

Key Type Description
entrust_id string Order id
symbol string Trading pair symbol
timestamp string Order create time (in milliseconds)
side string 'buy' or 'sell'
price string Price of the order
fees string Fees of the order
original_amount string Order amount
executed_amount string Successful amount
remaining_amount string Remaining amount
 

List Orders

import requests

url = "https://openapi.bitmart.com/v2/orders?symbol=BMX_ETH&status=0&offset=0&limit=100"

// timestamp is in milliseconds and the authorization header is "Bearer " + token
headers = {"X-BM-TIMESTAMP": xxx, "X-BM-AUTHORIZATION": "xxx"}

response = requests.get(url, headers=headers)

print(response.text)
func main() {
    access_token := get_access_token(api_key, api_secret, memo)

    URL := endpoint + "/v2/orders?symbol=BMX_ETH&status=1&offset=0&limit=100"

    req, _ := http.NewRequest("GET", URL, nil)

    req.Header.Add("X-Bm-Timestamp", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
    req.Header.Add("X-Bm-Authorization", "Bearer "+access_token)

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

Get a list of user orders.

 

Request Parameter

Parameter Type Description
symbol query Trading pair symbol
status query Integer enum, please check the table below
offset query Current page, which starts from 0
limit query Maximum size of the results in one page

However, for high-volume trading it is strongly recommended that you maintain your own list of open orders and use one of the streaming market data feeds to keep it updated. You should poll the open orders endpoint once when you start trading to obtain the current state of any open orders.

 

Status Type

Status Description
1 Pending orders
2 Partially successful orders
3 Success orders
4 Canceled orders
5 Pending and partially successful orders
6 Success and canceled orders

The above command returns JSON structured like this:

{
   "orders":[
      {
         "entrust_id":1223181,
         "symbol":"BMX_ETH",
         "timestamp":1528060666000,
         "side":"buy",
         "price":"1.000000",
         "fees":"0.1",
         "original_amount":"1",
         "executed_amount":"1",
         "remaining_amount":"0",
         "status":3
      },
      ...
   ],
   "total_pages":1,
   "total_orders":1,
   "current_page":0,
}
 

Response Details

Key Type Description
orders array List of orders
entrust_id string Order id
symbol string Trading pair symbol
timestamp string Order create time (in milliseconds)
side string 'buy' or 'sell'
price string Price of the order
fees string Fees of the order
original_amount string Order amount
executed_amount string Successful amount
remaining_amount string Remaining amount
total_pages string Total number of pages in that status (Deprecated)
total_orders string Total number of orders in that status (Deprecated)
current_page string Current page number
status string Integer enum, please check the table above
 

User Trade History

import requests

url = "https://openapi.bitmart.com/v2/trades?symbol=BMX_ETH&limit=10&offset=0"

// timestamp is in milliseconds and the authorization header is "Bearer " + token
headers = {"X-BM-TIMESTAMP": xxx, "X-BM-AUTHORIZATION": "xxx"}

response = requests.get(url, headers=headers)

print(response.text)
func main() {
    access_token := get_access_token(api_key, api_secret, memo)

    URL := endpoint + "/v2/trades?symbol=BMX_ETH&limit=10&offset=0"

    req, _ := http.NewRequest("GET", URL, nil)

    req.Header.Add("X-Bm-Timestamp", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
    req.Header.Add("X-Bm-Authorization", "Bearer "+access_token)

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

Get user trade history.

 

Request Parameter

Parameter Type Description
symbol query Trading pair symbol
entrust_id query Order id when placed
offset query Current page, which starts from 0
limit query Maximum size of the results in one page

entrust_id is optional too. However, if entrust_id is passed in, offset and limit will have no effect.

The above command returns JSON structured like this:

{
    "total_trades": 216,
    "total_pages": 22,
    "current_page": 0,
    "trades": [
        {
            "symbol": "BMX_ETH",
            "amount": "1.0",
            "fees": "0.0005000000",
            "trade_id": 2734956,
            "price": "0.00013737",
            "active": true,
            "entrust_id": 5576623,
            "timestamp": 1545292334000
        },
        {
            "symbol": "BMX_ETH",
            "amount": "100.0",
            "fees": "0.0500000000",
            "trade_id": 2664776,
            "price": "0.00013472",
            "active": true,
            "entrust_id": 5389422,
            "timestamp": 1543964304000
        },
        ...
    ]
}
 

Response Details

Key Type Description
trades array List of orders
entrust_id string Order id
trade_id string Trade history id
symbol string Trading pair symbol
timestamp string Execution time (in milliseconds)
active boolean Order status
entrustType int Order Type 0:BUY 1:SELL
price string Executed price
fees string Executed fee
amount string Executed amount
total_pages string Total number of pages (Deprecated)
total_trades string Total number of trades (Deprecated)
current_page string Current page number
 

Errors

A successful response is indicated by HTTP status code 200 and may contain an optional body. If the response has a body it will be documented under each resource below.

Unless otherwise stated, errors to bad requests will respond with HTTP 4xx or status codes. The body will also contain a message parameter indicating the cause. Your language’s http library should be configured to provide message bodies for non-2xx requests so that you can read the message field from the body.

Common error codes

Status Code Reason
400 Bad Request - Invalid request format
401 Unauthorized - Invalid API Key
403 Forbidden - You do not have access to the request resource
404 Not Found
500 Internal Server Error - We had a problem with our server
 

Websocket

Real-time market data updates provide the fastest insight into order flow and trades. This however means that you are responsible for reading the message stream and using the message relevant for your needs which can include building real-time order books or tracking real-time trades.

 

URL

wss://ws-manager.bitmart.com

 

Protocol Overview

The websocket feed uses a bidirectional protocol, which encodes all messages as JSON objects.

Error messages: Most failure cases will cause an error message (a message with the field "message") to be emitted. This can be helpful for implementing a client or debugging issues.

 

Subscribe

A sample subscription message looks like:

{
    "subscribe": "depth",
    "symbol":55,
    "precision": 6
}

Subsequent subscribe messages will add to the list of subscriptions. For example

{
    "code": 0,
    "data": {
        "buys": [{
            "amount": "1.33",
            "count": "1",
            "price": "0.015710",
            "total": "1.33"
        }],
        "sells": [{
            "amount": "14.03",
            "count": "1",
            "price": "0.015730",
            "total": "14.03"
        }]
    },
    "time":1534141852,
    "version":"20180810001",
    "pre_version":"20180810000"
    "precision": 6,
    "subscribe": "depth",
    "symbol": 53
}

To begin receiving feed messages, you must first send a subscribe message to the server indicating which channels and products to receive. This message is mandatory — you will be disconnected if no subscribe has been received within 5 seconds.

Once a subscribe message is received, the server will respond with a subscription message along with the channel you are subscribed to.

If you want to unsubscribe from channel/product pair, send an unsubscribe. The structure is equvalent to subscribe messages.

Once unsubscription succeed, you will no longer receive subsequent subscription messages of the pair.

 

Channels

 

According Channel

Mesage return like below

{
    "code": 0,
    "data": {
        "total24HourVolume": "154547896.36 CNY",
        "totalCoin": "7192819944.43 CNY",
        "totalTrade": 78,
        "time":1534141852 
    },
    "local": "zh_CN",
    "subscribe": "according"
}

Subscribe

{"subscribe": "according","local": "zh_CN"}

Unsubscribe

{"subscribe": "according_cancel","local": "zh_CN"}

 

Price Channel

Mesage return like below

{
    "code": 0,
    "data": {
        "c": "6274.37",
        "fluctuation": "0.0245", 
        "h": "6465.00",
        "increase": "1",
        "l": "6080.00",
        "o": "6124.49",
        "rate": "43100.53",
        "sign": "CNY",
        "v": "5775350.53",
        "time":1534141852
    },
    "version":"20180810001",
    "pre_version":"20180810000",
    "local": "zh_CN",
    "subscribe": "price",
    "symbol": 55
}

Subscribe

{"subscribe": "price","symbol": 55, "local": "zh_CN"}

{"subscribe": "price", "symbol": "55|22|33", "local": "zh_CN"}

Unsubscribe

{"subscribe": "price_cancel","symbol": 55,"local": "zh_CN"}

 

Market Channel

Parameter Description
event value of ping, addChannel, cancelChannel
binary binary compression 0-no 1-true
type subscribe type, value of kline, depth, ticker
product product type value of spot, futures
quote price coin like USD,USDT,BTC,ETH,BMX
base base coin
period kline step
sign currency sign like CNY JPY GBP HKD CAD USD EUR KRW AUD
 

Subscribe Examples:

Subscribe all symbol tickers

{event:'addChannel',parameters:{product:"spot","binary":"0","type":"all_ticker","sign":"CNY"}}

*Unsubscribe all symbol tickers

{event:'cancelChannel',parameters:{product:"spot","binary":"0","type":"all_ticker","sign":"CNY"}}

Subscribe single symbol ticker

{event:'addChannel',parameters:{product:"spot","binary":"0","quote":"usdt","type":"all_ticke","sign":"CNY"}}

Unsubscribe single symbol ticker

{event:'cancelChannel',parameters:{product:"spot","binary":"0","quote":"usdt","type":"all_ticker","sign":"CNY"}}

 

Depth Channel

Mesage return like below

{
    "code": 0,
    "data": {
        "buys": [{
            "amount": "1.33",
            "count": "1",
            "price": "0.015710",
            "total": "1.33"
        }],
        "sells": [{
            "amount": "14.03",
            "count": "1",
            "price": "0.015730",
            "total": "14.03"
        }]
    },
    "time":1534141852,
    "version":"20180810001",
    "pre_version":"20180810000"
    "precision": 6,
    "subscribe": "depth",
    "symbol": 53
}

Subscribe

{"subscribe": "depth","symbol": 55,"precision": 6}

Unsubscribe

{"subscribe": "depth_cancel","symbol": 55,"precision": 6}

 

Trade Channel

Mesage return like below

{
    "symbol":118,
    "code":0,
    "data":{
        "trades":[
            {
                "isBuy":"1",
                "amount":"8.90016491",
                "count":"3359.25",
                "price":"0.00264945",
                "time":1542337219109,
                "version":"",
                "pre_version":""
            }
        ]
    },
    "subscribe":"trade",
    "firstSubscribe":"1",
    "precision":4,
    "uuid":"51f79e6b-53fb-471c-bb81-4f5aa3b5210c"
}

Subscribe

{"subscribe":"trade", "symbol":12, "precision": 0}

Unsubscribe

{"subscribe":"trade_cancel", "symbol":12, "precision": 0}

 

Kline Channel

Mesage return like below

{
"subscribe":"kline",
"symbol": 12,
"step": "3",
"code": 0,
"data":{
    "o":"0.0000100", 
    "h":"0.0000100",
    "l":"0.0000100", 
    "v":"0.0000100", 
    "c":"0.0000100", 
    "t": 12312231,
    "ot":12312231,
    "ct":12312231
    }
}

Subscribe

{"subscribe":"kline", "symbol": 12, "step": 3}

Unsubscribe

{"subscribe":"kline_cancel", "symbol": 12, "step": 3}

step:

1 => 1 min

3 => 3 min

5 => 5 min

15 => 15 min

30 => 30 min

45 => 45 min

60 => 1 hour

120 => 2 hour

180 => 3 hour

240 => 4 hour

1d => 1 day

1w => 1 week

1m => 1 month

 

Notify Channel

Notify new order

{
    "code": 0,
    "subscribe":"notify",
    "uid":100,
    "data":{
        "event":"new_entrust",
        "symbol": 12,
        "entrustId": 12,
        "time": 13333333,
        "version":"20180810001",
        "pre_version":"20180810000"
    }
}

Notify order cancelled


{
    "code": 0,
    "subscribe":"notify",
    "uid":100,
    "data":{
        "event":"cancel_entrust",
        "symbol": 12,
        "entrustId": 12,
        "time": 13333333,
        "version":"20180810001",
        "pre_version":"20180810000"
    }
}

Notifiy order finish

{
    "code": 0,
    "subscribe":"notify",
    "uid":100,
    "data":{
        "event":"trade_success",
        "symbol": 12,
        "entrustId": 12,
        "time": 13333333,
        "version":"20180810001",
        "pre_version":"20180810000"
    }
}

Subscribe

{"subscribe":"notify", "token":"123123dsfsd123"}

 

User Orders Channel

Retrieve the user's transaction information (login authentication required).

Example send

{
"op": "subscribe",
"token":"GnHvFd5XBQc3iPqXv83siDaef4Ln9Pyv19gywmBuTiVh/FO4bv3IcmhW/Fu/JO0ZGTg1/FqR6tIt3HB0dp9RtB8DvsjvlfB7LY/P3xafsBTfD7pz9TBrHOlOPhQmO6QRn2ES8sV+d2t/Npz15IDC0rNV90j8o0nV2SW8O+otOwNvqn5OEktNJdn6yAfBDnkfJx7cH/NgG4t5n+KwhbYP2auHA/RWOoR3G4/9naa1F+Yo+gfZeLcO0MaNFMoB4FfDkAAolimsIV/rYADypCQ0AgfLydXChksIiXVhj3dCtbH4dLaziWOxkwho1GExHQOD0jNMhGZ9WqSS3Xu1XQJjwvNLXU2VNswpDvyVA2RSOVg=",
"args": ["spot/order:BMX_USDT","spot/order:BTC_USDT"]
}

spot/order is channel name , BMX_USDT is trademapping_name

Response

Parameters Type Description
order_id String Order ID
client_oid String Client supplied order ID Numbered Mode
price String Price
count String count of the order in the unit of the quote currency
notional String Buying amount or selling quantity. Returned for market orders
trademapping_id String Trading pair ID
trademapping_name String Trading pair Name
side String 0-Buy or 1-sell
order_type String 0-limit or 1-market
timestamp String Time of order creation millisecond
filled_count String Quantity of order filled
filled_amount String Amount of order filled
margin_trade String 1 spot order. 2 margin order
entrust_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
state String Order Status(-2:Failed,-1:Canceled,0:Open ,1:Partially Filled, 2:Fully Filled,3:Submitting,4:Cancelling,)
last_fill_price String Latest Filled Price. '0' will be returned if the data is empty
last_fill_count String Latest Filled Volume. '0' will be returned if the data is empty.
last_fill_time String Latest Filled Time. The '0' will be returned if the data is empty. millisecond

Example Response

{
    "data": {
        "trademapping_id": "52",
        "side": "1",
        "last_fill_time": "1568641347329",
        "count": "500.0000000000",
        "filled_count": "500.0000000000",
        "client_oid": "spot/user-channel",
        "last_fill_price": "0.0229",
        "price": "0.0229000000",
        "margin_trade": "0",
        "last_fill_count": "500.0",
        "state": "2",
        "trademapping_name": "BMX_USDT",
        "order_id": "2458056",
        "order_type": "1",
        "filled_amount": "11.4500000000",
        "timestamp": "1568641346000",
        "entrust_type": "0"
    },
    "table": "spot/order"
}
 

WebSocket Code

Desc Code
success 0
error -1
parameter missing -8101
parameter error -8102
topic error -8103
 

AutoTrade

The following is a list of automated trading software and services that allow trading on BitMart

  • CCXT

    The CCXT library is used to connect and trade with cryptocurrency exchanges and payment processing services worldwide. It provides quick access to market data for storage, analysis, visualization, indicator development, algorithmic trading, strategy backtesting, bot programming, and related software engineering.

  • FMZ

    FMZ is an automated trading platform for cryptocurrency traders with support for many bitcoin/eth/altcoin exchange markets.

More tools are in the works. If you use a library or bot that does not currently support BitMart, ask the maintainers to Contact Support to get started with our API. Our employees are happy to help.
















NAV Navbar