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.
 

API Describe

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

 

Host

Spot: https://openapi.bitmart.com

Future: https://api-cloud.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

 

Auth and Sign

Before using authorization APIs, you need to get an Access Token. And request these APIs with this token. To get an Access Token, first of all, you need to apply an API KEY and API SECRET.

 

Get API KEY and API SECRET

  1. Login your BitMart account, and access 'Account'->'Security Settings'-'API'-'Set'. Contract API KEY

  2. Add an Spot or future API KEY. Contract API KEY

Tips:There are two different type of API KEY, and don't mixed use please.

3、Save your API KEY and API SECRET in a safe place.

 

Get Access Token

When getting memo, API KEY and API SECRET, the next step is create a Client Secret.

Using HMAC_SHA256 to encrypt apiKey + ":" + apiSecret + ":" + memo with API SECRET as secret key.

Parameter Description
API Key 6591f7c2491db0a23a1d8ad6911c825e
API Secret 8c08d9d5c3d15b105dbddaf96e427ac6
memo mymemo (The API Name you set on the web page when getting API KEY and API SECRET)

Creating Client Secret use Linux Shell

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

Now you have haven Memo and API KEY and API SECRET and Client Secret. OK, the next is your target stuff: Access Token. You can get it by sending a request like below:

 

URL

Spot

Header: Content-Type: application/x-www-form-urlencoded

URL: POST https://openapi.bitmart.com/v2/authentication

Contract

Header: Content-Type: application/x-www-form-urlencoded

URL: POST https://api-cloud.bitmart.com/v1/authentication

 

Request Parameters

curl -H "Content-Type:application/x-www-form-urlencoded" -d "grant_type=client_credentials&client_id=xxxxxxxxxxx&client_secret=cccccccccccc"  https://api-cloud.bitmart.com/v1/authentication
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"`
}

#utf8
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)
}

Parameter Type is required Description
grant_type String Yes Constant string: client_credentials
client_id String Yes API KEY
client_secret String Yes The one you get in previous step

response json:

{
"access_token": "EQqQa7S48pkwkyIHTo1v6m2ZUqYhSNY1fr77HF2WfColvSXX3V2dr/yJVYsRK3QF/N7I++veKyIDO2SQEG+QcowtXxHeFq4Qq8o7UyBA0+g0PV6rd76hXSxZJIFLNnjbYs2Ko2kefbVZee1PJc0+IplUEqqJ8GOZ/NlxDnivqnfTMMqqHvB8/ePEW2s9Qe6Ke3SffUPsPU0E9PBMuCyhaZua6V8H3Ba5Uea4xnmXjAGw94XlI1EppOQHuXR3HCf/cx4bo0RXKnSV1hcCTjWj7yJ+TqBgRQWy+m7u9Xs8F4EyRVJvd+vJ3+XmMxbAoN1G",
"expires_in": 7200  // seconds
}
 

Sending authenticated requests

Headers in https Request:

  • X-BM-AUTHORIZATION
  • X-BM-TIMESTAMP

X-BM-AUTHORIZATION

  • Spot: Bearer+Access Token, For example: if token=xxxxx1234, then X-BM-AUTHORIZATION=Bearerxxxxx1234

  • Contract: Access Token, For example: if token=xxxxx1234, then X-BM-AUTHORIZATION=xxxxx1234

X-BM-TIMESTAMP UTC millisecond, Unix Epoch.

  • X-BM-TIMESTAMP(timestamp) within 60 seconds, or the server will refuse your request. If you don't sure if your time and BitMart server time are synchronous, we recommend to using APItime get BitMart server time.

  • Normally, request and response body content-type areapplication/json. Http Status=200 represents success, others fail[# Errors]

  • But, Some Api requests Content-Type=application/x-www-form-urlencoded; Some Api Requests need to signature Params.

 

Signature parameters

Some Api Requests need to signature Params(See the API describe), please sign the params like: 1. Sort all params values(to string) and timestamp(to string) by dictionary order.

  1. Appends the sorted params like: param1=1value1&timestamp=1585559188970&param2=2value2&param3=3value3.

  2. Sign the string Using HmacSHA256 with Client Secret as key.

  3. Put the sign string into request header: X-BM-SIGNATURE,and X-BM-TIMESTAMP equals the timestamp used in X-BM-SIGNATURE.

 

Spot API

 

API Host

https://openapi.bitmart.com

 

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

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

import requests

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

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

print(response.text)

The above command returns JSON structured like this:

{
   "server_time": 1527777538000
}
 

Currencies

Get a list of available currencies.

import requests

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

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

print(response.text)

The above command returns JSON structured like this:

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

Symbols

Get a list of symbol names.

import requests

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

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

print(response.text)

The above command returns JSON structured like this:

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

Symbols Details

Get the details of all symbols.

import requests

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

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

print(response.text)
 

Response Details

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"
    },
    ...
]
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

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

import requests

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

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

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

Response Details

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"
}
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

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

import requests

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

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

print(response.text)

The above command returns JSON structured like this:

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

K-line

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

 

Request Parameters

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)
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)
 

Response Details

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"
    },
    ...
]
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

Get the full order book.

 

Request Parameters

import requests

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

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

print(response.text)
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.

 

Response Details

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"
      },
      ...
   ]
}
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

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

 

Request Parameter

import requ#ests

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

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

print(response.text)
Parameter Type Description
symbol path Trading pair symbol
 

Response Details

The above command returns JSON structured like this:

[  
   {
      "amount":"0.05768509",
      "order_time":1527057452000,
      "price":"0.004811",
      "count":"11.99",
      "type":"buy"
   },
   ...
]
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

 

Wallet Balances

Get user 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))
}

 

Response Details

The above command returns JSON structured like this:

[
   {
        "id": "BTC"
        "available": 10,
        "name": "Bitcoin",
        "frozen": 0,
    }, 
    ...
]
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.

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"
}
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.

 

Response Details

The above command returns JSON structured like this:

{
   "entrust_id":1223181
}
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.

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

[linux]$ echo -n "entrust_id=1223181" | openssl dgst -sha256 -hmac "8c08d9d5c3d15b105dbddaf96e427ac6"
(stdin)= de4ed768cea4eb2f0fe081009eab1f41c5fd6ff6ed53768df7fe252472c257b3
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

Get an order details.

 

Request Parameter

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))
}
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

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
}
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

Get a list of user orders.

 

Request Parameter

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))
}

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
 

Response Details

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,
}
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

Get user trade history.

 

Request Parameter

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))
}
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.

 

Response Details

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
        },
        ...
    ]
}
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
 

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.

 

Host

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

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"
}

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
 

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.
















 

Contract API

BitMart supports multiple contracts.

 

API Host

https://api-cloud.bitmart.com

 

Public API

These APIs don't need an Access Token.

 

Contract List

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/contracts?exchange=bitmart

GET /contract/v1/ifcontract/contracts

 

Request Parameters

Parameter Type is required Description
contractID long No Contract ID if contractID is empty or contractID equals 0, it means get all contracts
exchange string Yes must be bitmart
 

Response Details

Response json:

 {
        "errno": "OK",
        "message": "Success",
        "data": {
            "contracts": [
                {
                    "contract": {
                        "contract_id": 1,
                        "index_id": 1,
                        "name": "BTCUSDT",
                        "display_name": "BTCUSDT contract",
                        "display_name_en": "BTCUSDT_SWAP",
                        "contract_type": 1,
                        "base_coin": "USDT",
                        "quote_coin": "BTC",
                        "price_coin": "USDT",
                        "contract_size": "1",
                        "delivery_cycle": 0,
                        "min_leverage": "1",
                        "max_leverage": "100",
                        "price_unit": "0.01",
                        "vol_unit": "1",
                        "min_vol": "1",
                        "value_unit": "0.01",
                        "max_vol": "100000",
                        "liquidation_warn_ratio": "0.85",
                        "fast_liquidation_ratio": "0.3",
                        "settle_type": 1,
                        "open_type": 3,
                        "status":3,
                        "compensate_type": 1,
                        "created_at": "2018-07-12T19:16:57Z"
                    },
                    "risk_limit": {
                        "contract_id": 1,
                        "base_limit": "10",
                        "step": "5",
                        "initial_margin": "0.1" 
                    },
                    "fee_config": {
                        "contract_id": 1,
                        "maker_fee": "0.00025",
                        "taker_fee": "0.00075",
                        "settlement_fee": "0",
                        "long_funding": "0.03",
                        "short_funding": "0.06",
                        "funding_interval": 28800,
                        "created_at": "2018-07-12T20:47:22Z"
                    }
                }
            ]
        }
   }
Key Type Description
contract_id long contract id.
index_id int contract's index id.
name string contract's name
display_name string contract's chinese display name.
display_name_en string contract's english display name.
contract_type int contract type: 1-swap, 2-futures
base_coin string base coin
quote_coin string quote coin
price_coin string price unit coin
contract_size decimal a contract values by base coin
delivery_cycle int delivery cycle, unit second
min_leverage decimal min leverage
max_leverage decimal max leverage
price_unit decimal price unit
vol_unit decimal vol unit
value_unit decimal value unit
min_vol decimal min vol
max_vol decimal max vol
liquidation_warn_ratio decimal liquidation warn ratio
fast_liquidation_ratio decimal fast liquidation ratio
settle_type int settle type 1:auto, 2:manual
open_type int open type ,1:Isolated Margin 2:Cross Margin 3:Both
status int 3 enable 4 disable 5 in settlement, stop trading 6 settlement done 7 off shelve
compensate_type int reimburse bankruptcy 1:ADL, 2:profit share
base_limit decimal basic risk limit
step decimal price step
maintenance_margin decimal maintenance margin base rate
initial_margin decimal Initial Margin base rate
maker_fee decimal maker fee rate
taker_fee decimal taker fee rate
settlement_fee decimal settlement fee, only contract_type=2-futures
long_funding decimal Long position funding rate , only contract_type=1-swap
short_funding decimal Short position funding rate , only contract_type=1-swap
funding_interval int64 funding rate settlement interval , only contract_type=1-swap
created_at string create time
 

Tickers

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/tickers?contractID=1

GET /contract/v1/ifcontract/tickers

 

Request Parameters

Parameter Type is required Description
contractID int No Contract ID if contractID is empty or contractID equals 0, it means get all contracts
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        "tickers": [
            {
                "last_price": "6277.5",
                "open": "6074.5",
                "close": "6277.5",
                "low": "6261.3",
                "high": "6279",
                "avg_price": "6274.67",,
                "volume": "20000", 
                "total_volume": "45462",
                "base_coin_volume":"163.9",
                "quote_coin_volume":"34555.38199999999999998882",
                "timestamp": 1534315695,
                "rise_fall_rate": "0.033",
                "rise_fall_value": "203",
                "contract_id": 1,
                "position_size": "374266",
                "volume_day": "45270",
                "amount24":"28520.77363",
                "index_price": "6406.53",
                "fair_basis": "0.000000690",
                "fair_value": "0.00442673",
                "fair_price": "6406.5344267",
                "rate": {
                    "quote_rate": "0.0003",
                    "base_rate": "0.0006",
                    "interest_rate": "-0.00009999" ,
                },
                "premium_index": "-0.0309530479798782534",
                "funding_rate": "0.0001",
                "next_funding_rate": "-0.0304530",
                "next_funding_at": "2018-08-15T08:00:01Z"
            }
        ]
    }
}
Key Type Description
last_price string Last trade price
open string Open price
close string Close price
low string Lowest price
high string Highest price
avg_price string Average price
volume string The number of contracts for the last trade, multiply by value of the contract to get volume in BTC
total_volume string Total number of contracts in 24 hours
base_coin_volume string Volume in base coin
quote_coin_volume string Volume in quote coin
timestamp long Timestamp
rise_fall_rate string Percentage of price change
rise_fall_value string Change in price
contract_id long Contract ID
position_size string Size of unclosed positions
volume_day string Total volume during the day
amount24 string Total traded amount in 24 hours
index_price string The price of the index
fair_basis string Fair basis
fair_value string Fair value
fair_price string Fair price
quote_rate string Interest rate of the quote coin
base_rate string Interest rate of the base coin
interest_rate string Interest rate
premium_index string Premium index
funding_rate string Current funding rates
next_funding_rate string The next expected funding rates
next_funding_at string The next funding time (UTC)
 

Kline

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/quote?contractID=1&startTime=1532610072&endTime=1532656524&unit=5&resolution=M

GET /contract/v1/ifcontract/quote

 

Request Parameters

Parameter Type is required Description
contractID int Yes Contract ID
startTime long Yes Start time
endTime long Yes End time
unit int Yes Frequency
resolution string Yes Frquency unit, M: Minute, H: Hour, D: Day
 

Response Details

Response json:

 {
     "errno": "OK",
     "message": "Success",
     "data": [
         {
             "low": "130",
             "high": "130",
             "open": "130",
             "close": "130",
             "last_price": "130",
             "avg_price": "130",
             "volume": "0",
             "base_coin_volume":"163.9", 
             "quote_coin_volume":"34555.38199999999999998882",
             "timestamp": 1532610000, 
             "rise_fall_rate": "0",
             "rise_fall_value": "0"
         }
     ]
 }
Key Type Description
low string Lowest price
high string Highest price
open string Open price
close string Close price
last_price string Last trade price
avg_price string Average price
volume string Volume
base_coin_volume string Volume in base coin
quote_coin_volume string Volume in quote coin
timestamp string Timestamp in seconds
rise_fall_rate string Percentage of price change
rise_fall_value string Change in price
 

Index Kline

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/indexquote?contractID=1&startTime=1532610072&endTime=1532656524&unit=5&resolution=M

GET /contract/v1/ifcontract/indexquote

 

Request Parameters

Parameter Type is required Description
contractID long Yes Contract id
startTime long Yes Start time
endTime long Yes End time
unit int Yes Duration
resolution string Yes Duration unit, M: Minute, H: Hour, D: Day
 

Response Details

Response json:

 {
     "errno": "OK",
     "message": "Success",
     "data": [
         {
             "low": "130",
             "high": "130",
             "open": "130",
             "close": "130",
             "last_price": "130",

             "avg_price": "130",
             "volume": "0",
             "timestamp": 1532610000, 
             "rise_fall_rate": "0",
             "rise_fall_value": "0"
         }
     ]
 }
Key Type Description
low string min price
high string max price
open string open price
close string close price
last_price string last trade price
avg_price string average price
volume string trade volume
timestamp string timestamp, second
rise_fall_rate string rise/fall rate
rise_fall_value string rise-fall difference
 

Query Trades

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/trades?contractID=1

GET /contract/v1/ifcontract/trades

 

Request Parameters

Parameter Type is required Description
contractID int Yes contract ID
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        "trades": [
            {
                "order_id": 10116361,
                "trade_id": 10116363,
                "contract_id": 1, 
                "deal_price": "16",
                "deal_vol": "10",
                "make_fee": "0.04",
                "take_fee": "0.12",
                "created_at": null,
                "way": 5, 
                "fluctuation": "0" 
            }
        ]
    }
}
Key Type Description
order_id long taker order id
trade_id long trade id
contract_id long contract id
deal_price string deal price
deal_vol string count of deal contract
make_fee string maker fee
take_fee string taker fee
created_at string create time
way string

1:buyer is taker, taker open long position, maker open short position; 2:buyer is taker, taker open long, maker close long; 3:buyer is taker, taker close short, maker open short; 4:buyer is taker, taker close short, maker close long;

5:seller is taker, taker open short, maker open long; 6:seller is taker, taker open short, maker close short; 7:seller is taker, taker close long, maker open long; 8:seller is taker, taker close long, maker close short; | | fluctuation | string | fluctuation |

Notice:

way 1~4 the buyer is taker ,5~8 the seller is taker

fluctuation, if before this trade, the newest price is 10, and this trade price is 11, then the fluctuation=1

 

Depth

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/depth?contractID=1&count=10

GET /contract/v1/ifcontract/depth

 

Request Parameters

Parameter Type is required Description
contractID long Yes Contract ID
count int No Depths
 

Response Details

Response json:

 {
     "errno": "OK",
     "message": "Success",
     "data": {
         "sells": [
             {
                 "price": "60", 
                 "vol": "20"
             }
         ],
         "buys": []
     }
 }
Key Type Description
price long Price
vol long Amount of contract
 

PNLS

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/pnls?contractID=1

GET /contract/v1/ifcontract/pnls

 

Request Parameters

Parameter Type is required Description
contractID int Yes Contract ID
 

Response Details

Response json:

{
    "errno":"OK",
    "message":"Success",
    "data":{
        "pnls":[
            {
                "contract_id":1,
                "long_pnls":[
                    {
                        "min_pnl":"-0.0379107725788900979",
                        "max_pnl":"-0.0103298131866111136",
                        "quan_tile":40
                    },
                    {
                        "min_pnl":"-0.0103298131866111136",
                        "max_pnl":"0",
                        "quan_tile":60
                    }
                ],
                "short_pnls":[
                    {
                        "min_pnl":"-49962.3980439671407168788",
                        "max_pnl":"0",
                        "quan_tile":20
                    }
                ]
            }
        ]
    }
}
Key Type Description
contract_id int Contract ID
min_pnl string Minimum PnL
max_pnl string Maximum PnL
quan_tile int 50% Quantile
 

Index List

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/indexes

GET /contract/v1/ifcontract/indexes

 

Request Parameters

none

 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": [
        {
            "index_id": 1,
            "name": "BTC", 
            "base_coin": "BTC",
            "quote_coin": "USDT",
            "brief_en": "",
            "brief_zh": "",
            "price_unit": "0.000001",
            "created_at": "2018-07-30T16:04:08Z",
            "contract": [
                {
                    // contract related with this index price
                    // refer to endpoint /contract/v1/ifcontract/contracts?contractID=1
                },
                {

                },
                {

                }
            ]
        }
    ]
}
Key Type Description
index_id int Index ID
name string Index name
base_coin string Base coin
quote_coin string Quote coin
brief_en string Short name (EN)
brief_zh string Short name (ZH)
price_unit string Number of decimals in price
created_at string Creation time
 

Funding Rate

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/fundingrate?contractID=2

GET /contract/v1/ifcontract/fundingrate

 

Request Parameters

Parameter Type is required Description
contractID long Yes ContractID
 

Response Details

Response json:

 {
     "errno": "OK",
     "message": "Success",
     "data": [
         {
             "rate": "-0.0060483184843194741",
             "timestamp": 1534320000
         },
         {
             "rate": "0.1041766553400505803",
             "timestamp": 1534291200
         }
     ]
 }
Key Type Description
rate string Funding rate
timestamp long Timestamp
 

AUTH API

These endpoints can be accessed after authentication

 

User Position

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/userPositions?contractID=1&status=3&offset=0&size=0

GET /contract/v1/ifcontract/userPositions

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID int Yes Contract ID
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        "trades": [
            {
                "order_id": 10116361, // taker order id
                "trade_id": 10116363, // trade id
                "contract_id": 1,     // Contract ID
                "deal_price": "16",   // Deal price
                "deal_vol": "10",     // Deal volume
                "make_fee": "0.04",   // Maker fee
                "take_fee": "0.12",   // Taker fee
                "created_at": null,   // Create time
                "way": 5,             // Direction
                "fluctuation": "0"    // Market impact
            }
        ]
    }
}
Key Type Description
position_id long Position ID
account_id int Account ID
contract_id long Contract ID
hold_vol string Holding volume
freeze_vol string Frozen volume
close_vol string Closed volume
hold_avg_price string Average holding price
close_avg_price string Average closing price
liquidate_price string Liquidation price
im string Initial margin
mm string Maintenance margin
realised_profit string Realised profit
earnings string Earnings
hold_fee string Holding fees
open_type int Open type, 1: Cross margin, 2: Isolated margin
position_type int Position type, 1:Long, 2: Short
status int Status, 1: Holding, 2: Under system management, 4: Closed. If status=3 in request parameters, both holding and system managed positions will show; If status=3 or 7 in request parameters, all positions will show
errno int Reason for closing 1: Closing, 2: Liquidating, 3: Closed, 4: Liquidation ended, 5: Liquidated, 6: Automatic reduction (active), 7:Automatic reduction (Passive)
created_at string Create time
updated_at string Update time

Note

** How to calculate value of a position:

a.For long positions, value = number of contracts * contract size * average open price

b.For reverse positions, value = number of contracts * contract size / average open price

Sample code: func calculatePV:

func calculatePV(vol,price,contractSize,isReverse bool) {
     if isReverse {
         pv = vol*contractSize/price
         return pv
     }
     pv = vol*contractSize*price
     return pv
 }

vol: holding position;

price: average price;

contractSize: size of contract;

isReverse: whether it is a reverse contract, refer to [Public API]->[Contract List];

** func PositionLogicType

func PositionLogicType(position,isReverse) POSITION_TYPE {
     if !isReverse {
         return position.PositionType
     }
     if position.PositionType == POSITION_TYPE_LONG {
         return POSITION_TYPE_SHORT
     }
     return POSITION_TYPE_LONG
 }

** func CalculateLiquidatePrice:

 func CalculateLiquidatePrice( position, availableAssetsVol, contractSize, takeFeeRatio, isReverse) {
     S = contractSize
     T = takeFeeRatio
     HV = position.HoldVol
     HP = position.HoldAvgPrice

// Calculate value of the position PV = calculatePV(HV, HP,S,isReverse)

// Calculate the remaining margin for the position IM = position.IM.Add(availableAssetsVol)

// restM: The loss incurred when reaching the liquidation price restM = IM.Sub(position.MM) D = 0 M = 0

if PositionLogicType(position,isReverse) == POSITION_TYPE_LONG { M = PV - restM D = HV*S*(1-T) } else { M = PV+restM D = HV*S*(1+T) } if D <= 0 { if position.PositionType == POSITION_TYPE_LONG { return 10000000000000000 } else { return 0 } }

LP = M.Div(D) // Price of a reverse contract is 1/P if isReverse { LP = 1/LP } return LP } ```

// position: A position object

// availableAssetsVol: Available balance in assets, the value is zero when type is cross margin; only needed for isolated margin

// contractSize: Contract size

// takeFeeRatio: Taker fee ratio

// isReverse: Whether it is a reverse contract

** Calculate the unrealized profit at fair price func CalculatePositionUnrealizedProfit:

// CalculatePositionUnrealizedProfit Unrealized profit

 func CalculatePositionUnrealizedProfit(
     position,
     fairPrice
     contractSize,
     isReverse)  {
     if position.PositionType == POSITION_TYPE_LONG {
         return CalculateLongPositionUnrealizedProfit(position,fairPrice,contractSize,isReverse)
     } else{
         return CalculateShortPositionUnrealizedProfit(position,fairPrice, contractSize,isReverse)
     }
 }

// func CalculateLongPositionUnrealizedProfit

 func CalculateLongPositionUnrealizedProfit(position,fairPrice,contractSize,isReverse) {
     if isReverse {
         openValue := position.HoldVol*contractSize/(position.HoldAvgPrice)
         closeValue := position.HoldVol*contractSize/(fairPrice)
         return openValue - (closeValue)
     }
     openValue := position.HoldVol*(contractSize)*(position.HoldAvgPrice)
     closeValue := position.HoldVol*(contractSize)*(fairPrice)
     return closeValue - (openValue)
 }

// func CalculateShortPositionUnrealizedProfit

 func CalculateShortPositionUnrealizedProfit( position,fairPrice,contractSize,isReverse) {
     if isReverse {
         openValue := position.HoldVol*(contractSize)/(position.HoldAvgPrice)
         closeValue := position.HoldVol*(contractSize)/(fairPrice)
         return closeValue - (openValue)
     }
     openValue := position.HoldVol*(contractSize)*(position.HoldAvgPrice)
     closeValue := position.HoldVol*(contractSize)*(fairPrice)
     return openValue- (closeValue)
 }
 

User Orders

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/userOrders?contractID=1&offset=0&size=0&status=0

GET /contract/v1/ifcontract/userOrders

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID long Yes Contract ID
offset int No Offset
size int No Size of query, 60 queries are returned if no value is passed or size=0
status int Yes Order status 1: Submitting 2: In order 4: Completed. If status=3, only submitting and in order would be returned; if status=0 or 7, all orders are returned
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        "orders": [
            {
                "order_id": 10284160,
                "contract_id": 1,
                "price": "8",
                "vol": "4",
                "done_avg_price": "0",
                "done_vol": "0",
                "way": 1,
                "category": 1,
                "open_type": 2,
                "make_fee": "0",
                "take_fee": "0",
                "origin": "", // Origin
                "created_at": "2018-07-17T07:24:13.410507Z",
                "finished_at": null,
                "status": 2,
                "errno": 0
            }
        ]
    }
}
Key Type Description
order_id long Order ID
contract_id long Contract ID
price string Price
vol string Volume
done_avg_price string Average price
done_vol string Transacted volume
way int Direction of order
category int Order type 1: Limit, 2: Market, 7: Passive
make_fee string Maker fee
take_fee string Taker fee
origin string Origin
created_at string Create time
finished_at string Finish time
status int 1: Sutmitting, 2: In order, the order is in the matching queue, done_vol is the part already traded; if done_vol is not 0, it means the order is at least partly traded. 4: Completed
errno int Reason for ending the order. 1: Canceled by user, 2: Timeout, 3: Balance not enough, 4: End of liquidation order, 5: System managed orders canceled, 6: Partly closed, 7: Automatic reduction, 8: Compensate for profits, 9: Wrong position, 10: Invalid type, 11: Existence of reverse order
 

Order Detail

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/userOrderInfo?contractID=1&orderID=10539098

GET /contract/v1/ifcontract/userOrderInfo

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID long Yes Contract ID
orderID long Yes Order ID
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        "orders": [
            {
                "order_id": 10539098,
                "contract_id": 1,
                "position_id": 10539088,
                "account_id": 10,
                "price": "16",
                "vol": "1",
                "done_avg_price": "16",
                "done_vol": "1",
                "way": 3,
                "category": 1,
                "make_fee": "0.00025",
                "take_fee": "0.012",
                "origin": "",
                "created_at": "2018-07-23T11:55:56.715305Z",
                "finished_at": "2018-07-23T11:55:56.763941Z",
                "status": 4,
                "errno": 0
            }
        ]
    }
}
Key Type Description
order_id long Order ID
contract_id long Contract ID
position_id long Position ID
account_id long Account ID
price string Price
vol string Volume
done_avg_price string Traded average price
done_vol string Traded volume
way int Order direction
category int Order type
make_fee string Maker fee
take_fee string Taker fee
origin string Origin
created_at string Create time
finished_at string Finish time
status int Status
errno int Error code
 

User Accounts

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/accounts?coinCode=USDT

GET /contract/v1/ifcontract/accounts

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
coinCode string Yes coinCode of USDT contract account
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        "trades": [
            {
                "order_id": 10116361, 
                "trade_id": 10116363,
                "contract_id": 1,    
                "deal_price": "16", 
                "deal_vol": "10",  
                "make_fee": "0.04", 
                "take_fee": "0.12", 
                "created_at": null,
                "way": 5,      
                "fluctuation": "0" 
            }
        ]
    }
}
Key Type Description
account_id int Account ID
coin_code string Coin code
freeze_vol string Frozen balance
available_vol string Available balance
cash_vol string Net cash balance
realised_vol string Realized profit
unrealised_vol string Unrealized profit
created_at string created_at
updated_at string updated_at

Note

You need to log into spot trading, before accessing contract account information

contractID and coinCode are request parameters. Contracts with multiple margin coinCode share the same contract account

So, you can access account ID with contract ID, or with coinCode. If neither is passed, all contract accounts are returned

 

User Trade

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/userTrades?contractID=1&offset=0&size=100

GET /contract/v1/ifcontract/userTrades

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID long Yes Contract ID
offset int No Offset
size int No Size of query, 60 queries are returned if no value is passed or size=0
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        "trades": [
            {
                "order_id": 10116361, // Taker order id
                "trade_id": 10116363, // Trade id
                "contract_id": 1,     // Contract ID
                "deal_price": "16",   // Deal price
                "deal_vol": "10",     // Deal volume
                "make_fee": "0.04",   // Maker fee
                "take_fee": "0.12",   // Taker fee
                "created_at": null,   // Create time
                "way": 5,             // Direction
                "fluctuation": "0"    // Market impact
            }
        ]
    }
}
Key Type Description
order_id int Taker order id
trade_id string Trade id
contract_id string Contract ID
deal_price string Deal price
deal_vol string Deal volume
make_fee string Maker fee
take_fee string Taker fee
created_at string Create time
way string Direction 1: Open long, 2:Close short, 3: Close long, 4: Open short
fluctuation string Market impact

Note

Fluctuation is market impact. If price=10 before this trade, and price=11 afterwards, then fluctuation is "1"

 

Liquidation Records

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/userLiqRecords?contractID=1&orderID=1000232

GET /contract/v1/ifcontract/userLiqRecords

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID int Yes Contract ID
orderID long No Order ID, All liquidation records if none
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
    "records": [
        {
        "order_id": 10539098,
        "contract_id": 1,
        "position_id": 10539088,
        "account_id": 10,
        "type":1, // Liquidation type, 1: Partly, 2: Liquidation, 3: ADL Active, 4: ADL Passive
        "trigger_price":"16", // Trigger price
        "order_price":"16", // Order price
        "mmr":"0.0013", // Maintenance margin at liquidation
        "subsidies":"0.018", // Subsidies
        "created_at": "2018-07-23T11:55:56.715305Z"
        }
    ]
    }
}
Key Type Description
order_id long Order ID
contract_id long Contract ID
position_id long Position ID
account_id int Account ID
type int Liquidation type, 1: Partly, 2: Liquidation, 3: ADL Active, 4: ADL Passive
trigger_price string Trigger price
order_price string Order price
mmr string Maintenance margin at liquidation
subsidies string Subsidies
created_at string created_at

Note

1.Rules of passing parameters:

a.No parameters: All liquidation records

b.Only contractID: Liquidation records for this contract

c.Only orderID: Liquidation record for an order

 

Order Trades

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/orderTrades?contractID=1&orderID=2064344648

GET /contract/v1/ifcontract/orderTrades

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID long Yes Contract ID
orderID long Yes Order ID
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    "data": {
        // List of trades, sorted by order time
        "trades": [
            {
                "order_id": 10116361, // taker order id
                "trade_id": 10116363, // trade id
                "contract_id": 1,     // Contract ID
                "deal_price": "16",   // Deal price
                "deal_vol": "10",     // Deal volume
                "make_fee": "0.04",   // Maker fee
                "take_fee": "0.12",   // Taker fee
                "created_at": null,   // Create time
                "way": 5,             // Direction
                "fluctuation": "0"    // Market impact
            }
        ]
    }
}
Key Type Description
order_id long taker order id
trade_id long trade id
contract_id ing Contract ID
deal_price string Deal price
deal_vol string Deal volume
make_fee string Maker fee
take_fee string Taker fee
created_at string Deal volume
way int Direction 1: Open long, 2: Close short, 3: Close long, 4: Open short
created_at string Create time
fluctuation string Market impact

Note

Fluctuation is market impact. If price=10 before this trade, and price=11 afterwards, then fluctuation is "1"

User must be signed in to view trade records

 

Position Fee

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/positionFee?contractID=32785&positionID=2154205116

GET /contract/v1/ifcontract/positionFee

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID int Yes Contract ID
positionID long Yes Position ID
 

Response Details

Response json:

{
    "errno": "OK",
    "message": "Success",
    // 记录数组按照时间由近及远排序
    "data": [
        {
            "contract_id": 32785, // Contract ID
            "account_id": 2071026819, // Account ID
            "position_id": 2154205116, // Position ID
            "fair_price": "0.849940605285", // Fair price
            "funding_rate": "0", // Funding rate
            "fee": "-149.8912195248", // Fee, Negative means earning the fee, Positive means paying the fee
            "vol": "1053468", // Volume
            "created_at": "2019-01-15T00:00:00.708979Z" // Creation time (UTC)
        },
        {
            "contract_id": 32785,
            "account_id": 2071026819,
            "position_id": 2154205116,
            "fair_price": "0.849940605285",
            "funding_rate": "0",
            "fee": "-261.432832752",
            "vol": "1053468",
            "created_at": "2019-01-14T16:00:01.183355Z"
        }
    ]
}
Key Type Description
contract_id ing Contract ID
account_id long Account ID
position_id long Position ID
fair_price string Fair price
funding_rate string Funding rate
fee string Fee, Negative means earning the fee, Positive means paying the fee
vol int Volume
created_at string Creation time (UTC)

Note

Records are sorted by time

 

Create Contract Account

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/createContractAccount?contractID=1

GET /contract/v1/ifcontract/createContractAccount

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Parameter Type is required Description
contractID int Yes Contract ID
 

Response Details

Response json:

{
    "errno": "OK", 
    "message": "Success",
    "data":{}
}
Key Type Description
errno int Error code
message int Error message
 

Batch Order

 
Request Endpoint
https://api-cloud.bitmart.com/contract/v1/ifcontract/batchOrders

POST /contract/v1/ifcontract/batchOrders

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Response json

{
    "orders":[
        {
           "contract_id":3,
           "category":1,
           "custom_id":1, 
           "way":4,
           "open_type":1,
           "leverage":100,
           "price":998,
           "vol":10
        },
        {
           "contract_id":3,
           "category":1,
           "custom_id":2,
           "way":4,
           "open_type":1,
           "leverage":100,
           "price":998,
           "vol":10
        }
    ],
   "nonce":1533876299 // Timestamp
}
 

Open a position

Parameter Type is required Description
contract_id long Yes
category int Yes
way int Yes
open_type int Yes
custom_id int Yes
leverage int Yes
price int Yes
vol int Yes
 

Close a position

Parameter Type is required Description
contract_id long Yes
category int Yes
position_id long Yes
way int Yes
custom_id int Yes
price int Yes
vol int Yes
 

Response Details

Response json:

Success:
{
  "errno": "OK",
  "message": "Success",
  "data": {
      "orders": [
          {
              "custom_id": 1,
              "order_id": 10540013
          },
          {
              "custom_id": 2,
              "order_id": 10540014
          }
      ]
  }
}

Failure:
{
  "errno": "OK",
  "message": "Success",
  "data": {
      "orders": [
          {
              "custom_id": 1,
              "err": {
                  "http_err":405,
                  "err_code":"LIQUIDATE_ORDER",
                  "err_msg":"Order will be liquidated"
              }
          },
          {
              "custom_id": 2,
              "order_id": 10540014
          }
      ]
  }
}
Key Type Description
custom_id int Custom ID
order_id int Order ID
 

Submit Order

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/submitOrder

POST /contract/v1/ifcontract/submitOrder

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Response json

Open a position
{
   "contract_id":1, // Contract ID
   "category":1,  // Order type
   "way":4,  // Direction
   "open_type":1, // Open type
   "leverage":10, // Leverage
   "price":16,  // Price
   "vol":10,  // Volume
   "nonce":1531796011 // Timestamp
}

Close a position
{
   "contract_id":1, // Contract ID
   "category":1,  // Order type
   "position_id":12121,  // Direction
   "way":3,  // Direction
   "price":16,  // Price
   "vol":10,  // Volume
   "nonce":1531796011 // Timestamp
}

Open a position

Parameter Type is required Description
contract_id long Yes Contract ID
category int Yes Order type
way int Yes Direction
open_type int Yes Open type
custom_id int Yes Custom ID
leverage int Yes Leverage
price int Yes Price
vol int Yes Volume

Close a position

Parameter Type is required Description
contract_id long Yes Contract ID
category int Yes Order type
position_id long Yes Position ID
way int Yes Direction
custom_id int Yes Custom ID
price int Yes Price
vol int Yes Volume

备注

category:Order type 1: Limit, 2: Market

way: Order direction 1: Open long, 2:Close short, 3: Close long, 4: Close short

open_type: Position open type 1: Cross margin, 2: Isolated margin

Note: Do not pass open_type to close a position, otherwise server would return "invalid paramaters"

 

Response Details

Response json:

{
  "errno": "OK",
  "message": "Success",
  "data": {
      "order_id": 2707217580
  }
}

Key Type Description
order_id int Order ID
 

Cancel Order

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/cancelOrders

POST /contract/v1/ifcontract/cancelOrders

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Request Parametersbody

{
    "orders":[
        {
           "contract_id":1, 
           "orders":[
                10116356,
                10116357
            ]
        }
     ],
    "nonce":1531809458
}
Parameter Type is required Description
contractID long Yes Contract ID
orders array Yes List of order ID
 

Response Details

Response json:

{
    "errno":"OK",
    "message":"Success",
    "data":{
        "succeed":[
            2707219612
        ],
        "failed":[]
    }
}
Key Type Description
succeed list List of successfully canceled orders
failed list List of failed canceled orders
 

Margin Adjust

 

Request Endpoint

https://api-cloud.bitmart.com/contract/v1/ifcontract/marginOper

POST /contract/v1/ifcontract/marginOper

 

Request Headers

See Auth and Sign for more details

 

Request Parameters

Response json

{
   "contract_id":3,  // Contract ID
   "position_id":10539974, // Position ID
   "vol":10,   // Amount of margin
   "oper_type":1, // Type of operation, 1: Add margin, 2: Reduce margin
   "nonce":1533871871 // Timestamp in seconds
}
Parameter Type is required Description
contract_id long Yes Contract ID
position_id long Yes Position ID
vol int Yes Amount of margin
oper_type int Yes Type of operation, 1: Add margin, 2: Reduce margin
nonce long Yes Timestamp in seconds
 

Response Details

Response json:

{"errno":"OK","message":"Success"}
Key Type Description
 

Contract API Return Code

Failed requests will return "Http Status 400 BAD REQUEST",and error code is in the response body

"INVALID_TIMESTAMP", "invalid timestamp" "INVALID_SIGNATURE", "invalid signature" "CLOUD_ACCOUNT_NOT_FOUND", "cloud account not found" "CLOUD_APP_NOT_FOUND", "cloud app not found" "CLOUD_TRADE_NO_NOT_FOUND", "out_trade_no not found" "CLOUD_TRADE_NO_EXISTED", "out_trade_no already existed" "CLOUD_APP_NOT_ACTIVED", "cloud app not actived" "CLOUD_APP_DISABLE", "cloud app disable" "CLOUD_ACCOUNT_COUNT_LIMIT", "cloud account count limit" "ORIGIN_UID_HAD_EXISTED", "ORIGIN_UID_HAD_EXISTED" "CLOUD_APP_NO_PUBLICK_KEY", "cloud app no publick key" "CLOUD_API_KEY_NOT_FOUND", "cloud api key not found" "INVALID_EXPIRED_TS", "invalid expired ts" "CLOUD_API_KEY_EXPIRED", "cloud api key expired" "TRANSFER_VOL_PRECISION_ERROR", "transfer vol precision error" "INVALID_IP_ERROR", "invalid ip error"

"PARSE_PARAMETER_ERROR", "parse parameter error" "CHECK_NONCE_ERROR", "check nonce error" "CHECK_VER_ERROR", "check ver error" "NOT_FOUND_FUNC_ERROR", "not found func error"

BAD_REQUEST, "Invalid request" UNAUTHORIZED, "unauthorized" FORBIDDEN, "forbidden" NO_PERMISSION, "no permission" INTERNAL_SERVER_ERROR, "server error" NOT_FOUND, "not found" INVALID_PARAMETER, "Invalid parameter" INVALID_REQUEST_TYPE, "Illegal request" SYSTEM_ERROR, "System error" ACCESS_TOO_OFTEN, "Access too often" CLIENT_TIME_INVALID, "Please check your system time."

CONTRACT_OFFLINE, "This contract is offline!" CONTRACT_PAUSE, "This contract's exchange has been paused!" CONTRACT_ORDER_WILL_LIQUIDATE, "This order would trigger user position liquidate!" CONTRACT_ORDER_HAVE_REVERSE_WAY, "It is not possible to open and close simultaneously in the same position!" CONTRACT_POSITION_IS_CLOSED, "Your position is closed!" CONTRACT_POSITION_IS_DELEGATING, "Your position is in liquidation delegating!" CONTRACT_POSITION_VOLUME_NOT_ENOUGH, "Your position volume is not enough!" CONTRACT_POSITION_NOT_EXSIT, "The position is not exsit" CONTRACT_POSITION_NOT_ISOLATED, "The position is not isolated" CONTRACT_POSITION_LIQUIDATE_WHEN_SUB_MARGIN, "The position would liquidate when sub margin" CONTRACT_POSITION_WARN_WHEN_SUB_MARGIN, "The position would be warnning of liquidation when sub margin" CONTRACT_POSITION_BASE_LIMIT_SUB_MARGIN, "The position’s margin shouldn’t be lower than the base limit" CONTRACT_USER_ASSET_IN_DELEGATE, "You cross margin position is in liquidation delegating." CONTRACT_USER_ASSET_NOT_ENOUGH, "You contract account available balance not enough."

CONTRACT_PLAN_ORDER_COUNT_IS_FULL, "Your plan order's count is more than system maximum limit." CCONTRACT_ORDER_LEVERAGE_TOO_LARGE, "The order's leverage is too large." CCONTRACT_ORDER_LEVERAGE_TOO_SMALL, "The order's leverage is too small." CONTRACT_ORDER_PRICE_WOULD_NOT_TRIGGER, "The deviation between current price and trigger price is too large." CONTRACT_PLAN_ORDER_LIFECYCLE_TOO_LONG, "The plan order's life cycle is too long." CONTRACT_PLAN_ORDER_LIFECYCLE_TOO_SHORT, "The plan order's life cycle is too short." CONTRACT_NOT_FOUND, "This contract not found!"

 

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
NAV Navbar