Trading API

v1.6.0

Overview

B2BX provides both HTTP and WebSocket APIs for interacting with the exchange. Both allow read access to public market data and private read access to your account. Private write access to your account is available via the private API.

The public HTTP endpoint is accessed via GET requests while the private endpoint is accessed via HMAC-SHA512 signed POST requests using API keys. Both types of HTTP endpoints return results in JSON format.

The WebSocket API allows pushing notifications about the public order books and your private account. Similar to the HTTP API, it requires HMAC-SHA512 signed requests using API keys for requests related to your private account.

The base URLs for requests are:

Code

URL

[base]

https://api.b2bx.exchange:8443/trading

[base2]

https://cmc-gate.b2bx.exchange/marketdata/cmc/v1

Required fields are marked with *.

Private API

All REST requests must contain two HTTP headers:

  • "Key": public key

  • "Sign": hash of payload

API keys are UUID string (UTF-8), for example: “ca3a03e1-fc5c-4954-99dc-876db3997d8f”. API keys are obtained through Trader’s Room: Profile > API Keys Management. The payload is a JSON body. For hashing the HMAC-SHA512 algorithm is used.

All requests must include the following fields:

  • ts — a string representation of the current time in UTC Date and time, for example: “2019-12-20T08:20:51”

  • nonce — any 64-bit integer value. Must be unique every 22 second time interval in the frame of the used public key (for example, if nonce=12345 was used now, then the next time it can be used only in 22 seconds)

API Rate Limits

  • /frontoffice/* — 1 request per second

  • /marketdata/* — 2 requests per second


Public REST Methods

Supported Instruments

GET [base]/frontoffice/api/info

Returns information on all currency pairs supported by the exchange. In case of success, the following JSON-structure will be returned in the response body:

baseAsset string

Base asset

quoteAsset string

Quote asset

hidden number

Instrument availability: 0 — available, 1 — hidden (trading is not recommended, because this instrument may be preparing to disconnect)

status string

Instrument status: open, paused (cannot be traded), halted (cannot be traded, orders are cancelled)

makerFee number

Maker fee, paid if the order adds liquidity

makerFeeLimit number

Minimum maker fee value

takerFee number

Taker fee, paid if the order removes liquidity

takerFeeLimit number

Minimum taker fee value

priceScale number

Price step

amountScale number

Volume step

createdAt string

Date and time of instrument creation: YYYY-MM-DDThh:mm:ss

updatedAt string

Date and time of instrument last update: YYYY-MM-DDThh:mm:ss

Response example
{
    "serverTime": 636880696809972288,
    "pairs": {
        "btc_usdt": {
            "baseAsset": "btc",
            "quoteAsset": "usdt",
            "status": "Open",
            "hidden": 0,
            "makerFee": 0,
            "makerFeeLimit": 0,
            "takerFee": 0.001,
            "takerFeeLimit": 0,
            "priceScale": 6,
            "amountScale": 6,
            "createdAt": "2019-11-14T16:18:49.253354",
            "updatedAt": "2019-11-14T16:18:49.253354"
        },
        "gnt_usdt": {
            "baseAsset": "gnt",
            "quoteAsset": "usdt",
            "status": "Open",
            "hidden": 0,
            "makerFee": 0,
            "makerFeeLimit": 0,
            "takerFee": 0.001,
            "takerFeeLimit": 0,
            "priceScale": 5,
            "amountScale": 5,
            "createdAt": "2019-11-14T16:18:49.253354",
            "updatedAt": "2019-11-14T16:18:49.253354"
        }
    }
}

Order Book Snapshot

GET [base]/marketdata/instruments/{instrument}/depth

Returns order book for a specified currency pair. The following request parameters are available:

instrument* string

Instrument identifier: {baseAsset}_{quoteAsset}

Request example
[base]/marketdata/instruments/eth_btc/depth

In case of success, the following JSON-structure will be returned in the response body:

instrument string

Instrument identifier, same as in the request

bids array

Each element represents one particular order and contains number fields amount and price

asks array

Each element represents one particular order and contains number fields amount and price

version number

Current snapshot version

askTotalAmount number

Sum of all ask orders

bidTotalAmount number

Sum of all bid orders

snapshot boolean

This is a self-contained snapshot (always true for this request)

Response example
{
    "instrument": "eth_btc",
    "bids": [
        {
            "amount": 0.3092258,
            "price": 0.01734264
        },
        {
            "amount": 51.61494099,
            "price": 0.01734363
        }
    ],
    "asks": [
        {
            "amount": 133.52370356,
            "price": 0.01739337
        },
        {
            "amount": 9.16854518,
            "price": 0.01739838
        }
    ],
    "version": 1891724,
    "askTotalAmount": 1849.11363582,
    "bidTotalAmount": 809.23878372,
    "snapshot": true
}

Instrument Candles

New in version v1.2.0.

GET [base]/marketdata/instruments/{instrument}/history

Returns candlesticks graph for a specified currency pair. The following request parameters are available:

instrument* string

Instrument identifier: {baseAsset}_{quoteAsset}

startDate* string

Date and time of period start: YYYY-MM-DDThh:mm:ss

endDate* string

Date and time of period end: YYYY-MM-DDThh:mm:ss

type* string
Timeframe, the following values are avaliable:
  • 1m — 1 Minute

  • 5m — 5 Minutes

  • 15m — 15 Minutes

  • 30m — 30 Minutes

  • 1h — 1 Hour

  • 12h — 12 Hours

  • 1d — 1 Day

  • 1w — 1 Week

  • 1M — 1 Month

count number

Number of candles to return, defaults to 1000 (maximum value)

Request example
[base]/marketdata/instruments/btc_usdt/history?startDate=2019-03-13T09:00:00&endDate=2019-03-13T11:00:00&type=1h&count=2

In case of success, the following JSON-structure data will be returned in the response body:

instrument string

Same as in the request

start string

Same as in the request

end string

Same as in the request

low number

Lowest price

high number

Highest price

volume number

Total volume

quoteVolume number

Total quote asset volume

open number

Open price

close number

Close price

Response example
{
    "success": true,
    "instrument": "btc_usdt",
    "data": [
        {
            "instrument": "btc_usdt",
            "start": "2019-03-13T09:00:00Z",
            "end": "2019-03-13T10:00:00Z",
            "low": 3842.855,
            "high": 3855.445,
            "volume": 4,
            "quoteVolume": 0,
            "open": 3855.105,
            "close": 3842.855
        },
        {
            "instrument": "btc_usdt",
            "start": "2019-03-13T10:00:00Z",
            "end": "2019-03-13T11:00:00Z",
            "low": 3834.355,
            "high": 3848.855,
            "volume": 26,
            "quoteVolume": 0,
            "open": 3842.865,
            "close": 3835.655
        }
    ],
    "startDateTime": "2019-03-13T09:00:00Z",
    "endDateTime": "2019-03-13T11:00:00Z"
}

Asset Info

New in version v1.3.0.

GET [base2]/asset

Returns assets information.

In case of success, JSON-object will be returned in the response body with the following fields:

name string

Asset name

can_withdraw string

If true, the asset can be withdrawn

can_deposit string

If true, the asset can be deposited

min_withdraw string

Minimum withdrawal/deposit amount

max_withdraw string

Minimum withdrawal/deposit amount

Response Example
{
    "BTC": {
        "name": "btc",
        "can_withdraw": true,
        "can_deposit": true,
        "min_withdraw": "0.00000001",
        "max_withdraw": "100000000"
    },
    "USDT": {
        "name": "usdt",
        "can_withdraw": true,
        "can_deposit": true,
        "min_withdraw": "0.00000001",
        "max_withdraw": "100000000"
    },
    "USD": {
        "name": "usd",
        "can_withdraw": true,
        "can_deposit": true,
        "min_withdraw": "0.00000001",
        "max_withdraw": "100000000"
    }
}

Order Info

New in version v1.6.0.

GET [base]/frontoffice/api/orders

Returns order information. The following request parameters are available:

orderId* string

Order identifier: either orderId, or clientOrderId

Request example — info by orderId
[base]/frontoffice/api/orders?orderId=-72057594037927933
Request example — info by clientOrderId
[base]/frontoffice/api/orders?orderId=6fdf688e-00b0-4c68-82dd-3aee5c727ed1

In case of success, JSON-structure object will be returned in the response body:

updatedAt number

Date and time of the last update of the order

averageFillPrice number

Average order fill price

timeInForce string

Time in Force option of the order

clientOrderId number

Client order identifier

orderId number

System order identifier

total number

Total amount of quoted currency sold (quote amount)

orderType number

Order side: 0 — sell, 1 — buy

commission number

Commission in quoted currency

createdAt string

Date and time of order creation

unitsFilled number

Base amount

isPending boolean

If true, the order is active (not rejected, cancelled, or completed)

status string

Order status: Working, Rejected, Cancelled, Completed

type string

Order side: buy or sell

amount number

Order amount, must be greater than 0

remaining number

Remaining amount

price number

Order price. Required for limit orders, optional for market orders

executionPrice number

Execution price of the order

requestedPrice number

Requested price of the order

isLimit boolean

If true, the order is limit. If false, the order is market.

instrument boolean

Order instrument identifier: {baseAsset}_{quoteAsset}

side string

Order side: 0 — buy, 1 — sell

Note

The price field is obsolete. It is equal to executionPrice for Market and Stop orders, and requestedPrice for Stop orders.

Response example
{
    "order": {
	"updatedAt": "2020-06-19T11:21:30.532789",
	"averageFillPrice": "1000",
	"timeInForce": "GTC",
	"clientOrderId": "",
	"orderId": "-72057594037927934",
	"total": 100.0,
	"orderType": 0,
	"commission": 0.0001,
	"createdAt": "2020-06-19T11:21:30.532784Z",
	"unitsFilled": 0.1,
	"isPending": false,
	"status": "completed",
	"type": "buy",
	"amount": 0.1,
	"remaining": 0.0,
	"price": 1000.0,
	"executionPrice": 1000.0,
	"requestedPrice": 1000.0,
	"stopPrice": 0.0,
	"isLimit": true,
	"instrument": "btc_usdt",
	"side": 0
   }
}

Summary

New in version v1.3.0.

GET [base2]/summary

Returns summary information.

In case of success, JSON-object will be returned in the response body with the following fields:

id string

Market identifier

last string

Price of the last trade in the last 24 hours. If the deal was more than 24 hours ago: 0

lowestAsk string

Current lowest ask price

highestBid string

Current highest bid price

percentChange string

Price change in the last 24 hours

baseVolume string

All traded volume in the last 24 hours in base currency

quoteVolume string

All traded volume in the last 24 hours in quote currency

isFrozen string

Market status: 0 — working, 1 — temporarily suspended

high24hr string

Maximum trade price in the last 24 hours

low24hr string

Minimum trade price in the last 24 hours

Response example
{
    "BTC_USDT": {
        "id": "btc_usdt",
        "last": "10978.93578",
        "lowestAsk": "10979.0",
        "highestBid": "10978.71",
        "percentChange": "0.0813730364297798727996051454",
        "baseVolume": "6.47119743",
        "quoteVolume": "70829.9781692126756",
        "isFrozen": "0",
        "high24hr": "10985.0049",
        "low24hr": "10857.95376"
    },
    "BTC_USD": {
        "id": "btc_usd",
        "last": "0",
        "lowestAsk": "0",
        "highestBid": "0",
        "percentChange": "0",
        "baseVolume": "0",
        "quoteVolume": "0",
        "isFrozen": "0",
        "high24hr": "0",
        "low24hr": "0"
    }
}

Ticker Info

New in version v1.3.0.

GET [base2]/ticker

Returns ticker information.

In case of success, JSON-object will be returned in the response body with the following fields:

base_name string

Base asset name

quote_name string

Quote asset name

last_price string

Price of the last trade in the last 24 hours. If the deal was more than 24 hours ago: 0

base_volume string

All traded volume in the last 24 hours in base currency

quote_volume string

All traded volume in the last 24 hours in quote currency

isFrozen string

Market status: 0 — working, 1 — temporarily suspended

Response example
{
    "dash_btc": {
        "base_name": "dash",
        "quote_name": "btc",
        "last_price": "0",
        "base_volume": "0",
        "quote_volume": "0",
        "isFrozen": "1"
    },
    "eth_usdt": {
        "base_name": "eth",
        "quote_name": "usdt",
        "last_price": "423.9936",
        "base_volume": "2942.97774",
        "quote_volume": "1273092.080666887",
        "isFrozen": "0"
    }
}

Trades Info

New in version v1.3.0.

GET [base2]/trades/{instrument}

Returns all trades for a specified instrument in the last 24 hours. The following request parameters are available:

instrument* string

Instrument identifier: {baseAsset}_{quoteAsset}

Request Example
[base]/trades/btc_usd

In case of success, JSON-object will be returned in the response body with the following fields:

tradeID string

Trade identifier

price string

Trade price

base_volume string

Amount in base currency

quote_volume string

Amount in quote currency

trade_timestamp string

Datetime of the trade in the UNIX timestamp format

type string

Trade side: "buy" or "sell"

Response example
[
	{
		"tradeID": "1247307",
		"price": "10093.92246491",
		"base_volume": "0.0259",
		"quote_volume": "261.432591841169",
		"trade_timestamp": "1599577070",
		"type": "buy"
	},
	{
		"tradeID": "1247309",
		"price": "10091.69185435",
		"base_volume": "0.0754",
		"quote_volume": "760.913565817990",
		"trade_timestamp": "1599577128",
		"type": "sell"
	}
]

Private REST Methods

Place an Order

POST [base]/frontoffice/api/order

Places a new order. Request body must contain ts and nonce fields, and JSON-object order with the following fields:

instrument* string

Order instrument identifier: {baseAsset}_{quoteAsset}

type* string

Order side: "buy" or "sell"

amount* number

Order amount, must be greater than 0

price number

Order price. Required for limit orders, optional for market orders. If isLimit is true, must be greater than 0, in other cases can be equal to 0

isLimit boolean

If true, the order is limit. If false, the order is market. Ref. to Flags Combinations for details

isStop boolean Currently not supported

If true, the order is stop market or stop limit (depending on isLimit value). Ref. to Flags Combinations for details

isFok boolean

If true, the order must be executed immediately or be cancelled if not filled. Ref. to Flags Combinations for details

activationPrice number Currently not supported

Required and applicable only if isStop is true

clientOrderId number

Client provided order identifier: any UUID, except for 00000000-0000-0000-0000-000000000000

Flags Combinations

Order

Description

Flags

Limit

Limit order

isLimit is true, isStop is false, isFok is false

Market (Market IOK)

Market order (Immediate-or-Cancel market order) — order must be executed immediately and cancel any unfilled portion

isLimit is false, isStop is false, isFok is false

Market FOK

Fill-or-Kill market order — order must be executed immediately or cancelled if not filled

isLimit is false, isStop is false, isFok is true

Request example
{
    "ts": "2019-12-12T01:01:01",
    "nonce": 4,
    "order": {
        "instrument": "btc_usdt",
        "type": "sell",
        "amount": 1,
        "price": 1,
        "isLimit": true,
        "isStop": false,
        "isFok": false,
        "activationPrice": 0,
        "clientOrderId": "6fdf688e-00b0-4c68-82dd-3aee5c727ed1"
    }
}

In case of success, JSON-structure object will be returned in the response body:

orderId number

System order identifier

total number

Total amount of quoted currency sold (quote amount)

orderType number

Order side: 0 — sell, 1 — buy

commission number

Commission in quoted currency

createdAt string

Date and time of order creation

unitsFilled number

Base amount

isPending boolean

If true, the order is active (not rejected, cancelled, or completed)

status string

Order status: Working, Rejected, Cancelled, Completed

type string

Same as in the request

amount number

Same as in the request

remaining number

Remaining amount

price number

Same as in the request

executionPrice number

Execution price of the order

requestedPrice number

Requested price of the order

stopPrice number

Order stop price

isLimit boolean

Same as in the request

isStop boolean

Same as in the request

isFok boolean

Same as in the request

instrument boolean

Same as in the request

side string

Order side: 0 — buy, 1 — sell

Note

The price field is obsolete. It is equal to executionPrice for Market and Stop orders, and requestedPrice for Stop orders.

Response example
{
    "order": {
        "orderId": "-72057594037927933",
        "total": 0.0,
        "orderType": 0,
        "commission": 0.0,
        "createdAt": "2020-08-18T12:18:12.2296801Z",
        "unitsFilled": 0.0,
        "isPending": true,
        "status": "working",
        "type": "buy",
        "amount": 1,
        "remaining": 1,
        "price": 1,
	"executionPrice": 0.0,
        "requestedPrice": 10029.0,
        "stopPrice": 0.0,
        "isLimit": true,
        "instrument": "eth_usd",
        "side": 0
    }
}
JavaScript
 1const crypto = require('crypto');
 2const https = require('https');
 3const Key = "7fa6ceec-d8fc..."; // Change to your PublicKey
 4const Secret = "7ae49b5b-99db..."; // Change to your Secret
 5const Host = "api.b2bx.exchange";
 6const Port = 8443;
 7const Method = '/trading/frontoffice/api/order'
 8const Payload = new Date().toISOString();
 9const body = {
10    ts: Payload,
11	nonce:1,
12    order: {
13        instrument: 'eth_usd',
14        type: 'buy',
15        amount: 1,
16        price: 1,
17        isLimit: true
18    }
19};
20const data = JSON.stringify(body);
21const Sign = crypto
22    .createHmac('sha512', Secret)
23    .update(data)
24    .digest('hex')
25    .toUpperCase();
26const options = {
27    hostname: Host,
28    path: Method,
29    port: Port,
30    method: 'POST',
31    headers: {
32        'Content-Type': 'application/json',
33        'Content-Length': data.length,
34        Key,
35        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
36        Sign
37    }
38};
39const req = https.request(options, res => {
40    console.log(`statusCode: ${res.statusCode}`);
41    res.on('data', d => {
42        process.stdout.write(d);
43    });
44});
45req.on('error', e => {
46    console.error(e);
47});
48req.write(data);
49req.end();

Cancel an Order

DELETE [base]/frontoffice/api/orders?orderId={id}

Cancels the order. Request must contain ts and nonce values. The following request parameters are available:

id* string

Order identifier: either orderId — same as in the response message generated with Place an Order request, or clientOrderId — same as in the Place an Order request

Changed in version v1.1.0: Possibility to cancel an order by clientOrderId added.

Request example — cancel by orderId
[base]/frontoffice/api/orders?orderId=-72057594037927933&ts=2019-12-12T01:01:01&nonce=4
Request example — cancel by clientOrderId
[base]/frontoffice/api/orders?orderId=6fdf688e-00b0-4c68-82dd-3aee5c727ed1&ts=2019-12-12T01:01:01&nonce=4

In case of success, JSON-structure object will be returned in the response body (for details ref. to Place an Order response description).

Response example
{
    "order": {
        "orderId": "-72057594037927933",
        "total": 0.0,
        "orderType": 0,
        "commission": 0.0,
        "createdAt": "2020-08-18T12:28:26.6415513Z",
        "unitsFilled": 0.0,
        "isPending": false,
        "status": "cancelled",
        "type": "buy",
        "amount": 0.1,
        "remaining": 0.1,
        "price": 0.001,
	"executionPrice": 0.0,
        "requestedPrice": 0.71504,
        "stopPrice": 0.0,
        "isLimit": true,
        "instrument": "eth_usd",
        "side": 0
    }
}
JavaScript — cancel by orderId example
 1const crypto = require('crypto');
 2const https = require('https');
 3const Key = "7fa6ceec-d8fc..."; // Change to your PublicKey
 4const Secret = "7ae49b5b-99db..."; // Change to your Secret
 5const Host = "api.b2bx.exchange";
 6const Port = 8443;
 7const Payload = new Date().toISOString();
 8const OrderId = '-72057594037927933';
 9const Method = `/trading/frontoffice/api/orders?OrderId=${OrderId}&ts=${Payload}&nonce=2`
10async function deleteOrder() {
11
12    const Sign = crypto
13        .createHmac('sha512', Secret)
14        .update(`?OrderId=${OrderId}&ts=${Payload}&nonce=2`)
15        .digest('hex')
16        .toUpperCase();
17    const options = {
18        hostname: Host,
19        path: Method,
20        port: Port,
21        method: 'DELETE',
22        headers: {
23            'Content-Type': 'application/json',
24            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
25            Key,
26            Sign
27        }
28    };
29    const req = https.request(options, res => {
30        console.log(`statusCode: ${res.statusCode}`);
31        console.log(`statusMessage: ${res.statusMessage}`);
32        res.on('data', d => {
33            process.stdout.write(d);
34        });
35    });
36    req.on('error', e => {
37        console.error(e);
38    });
39    req.end();
40}
41deleteOrder().catch(err => {
42    console.log(err);
43});
JavaScript — cancel by clientOrderId example
 1const crypto = require('crypto');
 2const https = require('https');
 3const Key = "7fa6ceec-d8fc..."; // Change to your PublicKey
 4const Secret = "7ae49b5b-99db..."; // Change to your Secret
 5const Host = "api.b2bx.exchange";
 6const Port = 8443;
 7const Payload = new Date().toISOString();
 8const ClientOrderId = '6fdf688e-00b0-4c68-82dd-3aee5c727ed1'; // Change to your ClientOrderId
 9const Method = `/trading/frontoffice/api/orders?OrderId=${ClientOrderId}&ts=${Payload}&nonce=3`
10async function deleteOrder() {
11
12    const Sign = crypto
13        .createHmac('sha512', Secret)
14        .update(`?OrderId=${ClientOrderId}&ts=${Payload}&nonce=3`)
15        .digest('hex')
16        .toUpperCase();
17    const options = {
18        hostname: Host,
19        path: Method,
20        port: Port,
21        method: 'DELETE',
22        headers: {
23            'Content-Type': 'application/json',
24            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
25            Key,
26            Sign
27        }
28    };
29    const req = https.request(options, res => {
30        console.log(`statusCode: ${res.statusCode}`);
31        console.log(`statusMessage: ${res.statusMessage}`);
32        res.on('data', d => {
33            process.stdout.write(d);
34        });
35    });
36    req.on('error', e => {
37        console.error(e);
38    });
39    req.end();
40}
41deleteOrder().catch(err => {
42    console.log(err);
43});

Orders History

GET [base]/frontoffice/api/order_history

Returns the orders history. Request must contain ts and nonce values. The following request parameters are available:

market string

Market orders filter: currency pair (for example: btc_usdt)

side string

Order side: either buy or sell

status string

Order status: Working, Rejected, Cancelled, Completed

startDate string

Date and time of period start: YYYY-MM-DDThh:mm:ss.s

endDate string

Date and time of period end: YYYY-MM-DDThh:mm:ss.s

Request example
[base]/frontoffice/api/order_history?market=btc_usdt&ts=2019-12-12T01:01:01&nonce=4

In case of success, JSON-object data will be returned in the response body (for details ref. to Place an Order response description).

Response example
{
    "filters": {
        "market": "btc_usd"
    },
    "paging": {
        "page": 1,
        "per_page": 15,
        "total": 0
    },
    "data": [{
            "orderId": "-72057593704231199",
            "total": 0.0,
            "orderType": 0,
            "commission": 0.0,
            "createdAt": "2020-08-18T12:53:19.755247Z",
            "unitsFilled": 0.0,
            "isPending": false,
            "status": "cancelled",
            "type": "buy",
            "amount": 0.57945583,
            "remaining": 0.57945583,
            "price": 12241.61,
	    "executionPrice": 0.0,
            "requestedPrice": 10029.0,
            "stopPrice": 0.0,
            "isLimit": true,
            "instrument": "btc_usd",
            "side": 0
        },
        {
            "orderId": "-72057593704231200",
            "total": 0.0,
            "orderType": 0,
            "commission": 0.0,
            "createdAt": "2020-08-18T12:53:19.755163Z",
            "unitsFilled": 0.0,
            "isPending": false,
            "status": "cancelled",
            "type": "sell",
            "amount": 0.4081,
            "remaining": 0.4081,
            "price": 12253.93,
	    "executionPrice": 0.0,
            "requestedPrice": 10029.0,
            "stopPrice": 0.0,
            "isLimit": true,
            "instrument": "btc_usd",
            "side": 1
        }
    ]
}
JavaScript
 1const crypto = require('crypto');
 2const https = require('https');
 3const Key = "7fa6ceec-d8fc..."; // Change to your PublicKey
 4const Secret = "7ae49b5b-99db..."; // Change to your Secret
 5const Host = "api.b2bx.exchange";
 6const Port = 8443;
 7const Payload = new Date().toISOString();
 8const Method = `/trading/frontoffice/api/order_history?ts=${Payload}&market=btc_usd&nonce=4`;
 9async function GetOrders() {
10
11    const Sign = crypto
12        .createHmac('sha512', Secret)
13        .update(`?ts=${Payload}&market=btc_usd&nonce=4`)
14        .digest('hex')
15        .toUpperCase();
16    const options = {
17        hostname: Host,
18        port: Port,
19        path: Method,
20        method: 'GET',
21        headers: {
22            'Content-Type': 'application/json',
23            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
24            Key,
25            Sign
26        }
27    };
28    const req = https.request(options, res => {
29        console.log(`statusCode: ${res.statusCode}`);
30        console.log(`statusMessage: ${res.statusMessage}`);
31        res.on('data', d => {
32            process.stdout.write(d);
33        });
34    });
35    req.on('error', e => {
36        console.error(e);
37    });
38    req.end();
39}
40
41GetOrders().catch(err => {
42    console.log(err);
43});

Trades History

GET [base]/frontoffice/api/trade_history

Returns trades history. Request must contain ts and nonce values. The following request parameters are available:

orderId number

Order identifier, by which it is possible to get information about all related trades

New in version v1.4.0.

market string

Market orders filter: currency pair (for example: btc_usdt)

side string

Order side: buy or sell

startDate string

Date and time of period start: YYYY-MM-DDThh:mm:ss.s

endDate string

Date and time of period end: YYYY-MM-DDThh:mm:ss.s

Request example
[base]/frontoffice/api/trade_history?market=btc_usdt&ts=2019-12-12T01:01:01&nonce=4

In case of success, JSON-object data will be returned in the response with the following fields:

tradeSeq number

Sequence number of the trade

tradeTime string

Date and time of the trade

amount number

Trade amount

executionPrice number

Trade execution price

instrument string

Trade instrument

side number

Trade side: 0 — buy, 1 — sell

commission number

Trade commission

orderId number

Order identifier of the trade

Response example
{
    "filters": {
        "market": "btc_usdt"
    },
    "paging": {
        "page": 1,
        "per_page": 15,
        "total": 0
    },
    "data": [
        {
            "tradeSeq": 0,
            "tradeTime": "2019-12-20T06:17:03.093597",
            "amount": 0.00000001,
            "executionPrice": 0.00000001,
            "instrument": "btc_usdt",
            "side": 0,
            "commission": 0.00000000,
            "orderId": -72057593704402280
        },
        {
            "tradeSeq": 3927,
            "tradeTime": "2019-12-20T06:17:03.093597",
            "amount": 0.00000001,
            "executionPrice": 0.00000001,
            "instrument": "btc_usdt",
            "side": 1,
            "commission": 0.00000000,
            "orderId": -72057593704402281
        }
    ]
}
JavaScript
 1const crypto = require('crypto');
 2const https = require('https');
 3const Key = "7fa6ceec-d8fc..."; // Change to your PublicKey
 4const Secret = "7ae49b5b-99db..."; // Change to your Secret
 5
 6const Host = "api.b2bx.exchange";
 7const Port = 8443;
 8const Payload = new Date().toISOString();
 9const Method = `/trading/frontoffice/api/trade_history?ts=${Payload}&market=btc_usd&startDate=2020-01-12T01:01:01&nonce=5`;
10async function GetTrades() {
11
12    const Sign = crypto
13        .createHmac('sha512', Secret)
14        .update(`?ts=${Payload}&market=btc_usd&startDate=2020-01-12T01:01:01&nonce=5`)
15        .digest('hex')
16        .toUpperCase();
17    const options = {
18        hostname: Host,
19        port: Port,
20        path: Method,
21        method: 'GET',
22        headers: {
23            'Content-Type': 'application/json',
24            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
25            Key,
26            Sign
27        }
28    };
29    const req = https.request(options, res => {
30        console.log(`statusCode: ${res.statusCode}`);
31        console.log(`statusMessage: ${res.statusMessage}`);
32        res.on('data', d => {
33            process.stdout.write(d);
34        });
35    });
36    req.on('error', e => {
37        console.error(e);
38    });
39    req.end();
40}
41GetTrades().catch(err => {
42    console.log(err);
43});

User Balance

New in version v1.5.0.

GET [base]/frontoffice/api/balances

Returns information on full and locked balances for each asset. Request must contain ts and nonce values. In case of success, the following JSON-structure will be returned in the response body:

asset string

Asset name

balance number

Full balance

locked number

Locked amount

Response example
[
    {
        "asset": "btc",
        "balance": 10.0,
        "locked": 0.0
    },
    {
        "asset": "usdt",
        "balance": 80000.0,
        "locked": 7.0
    }
]

My Orders Info

New in version v1.6.0.

GET [base]/frontoffice/api/orders/my

Returns information about the open orders of the current user.

Request example
[base]/frontoffice/api/orders/my

In case of success, JSON-structure object will be returned in the response body (for details ref. to Order Info response description).

Note

The price field is obsolete. It is equal to executionPrice for Market and Stop orders, and requestedPrice for Stop orders.

Response example
[
    {
        "orderId": "-216172781189478695",
        "total": 0.0,
        "orderType": 0,
        "commission": 0.0,
        "createdAt": "2021-06-09T06:39:05.343157Z",
        "unitsFilled": 0.0,
        "isPending": true,
        "status": "working",
        "type": "sell",
        "amount": 1.0,
        "remaining": 1.0,
        "price": 0.0,
        "executionPrice": 0.0,
        "requestedPrice": 10029.0,
        "stopPrice": 0.0,
        "isLimit": true,
        "instrument": "eos_btc",
        "side": 1
    },
    {
        "orderId": "-144115187427224314",
        "total": 0.0,
        "orderType": 0,
        "commission": 0.0,
        "createdAt": "2021-06-09T11:25:03.5545112Z",
        "unitsFilled": 0.0,
        "isPending": true,
        "status": "working",
        "type": "sell",
        "amount": 3508.0,
        "remaining": 3508.0,
        "price": 0.0,
        "executionPrice": 0.0,
        "requestedPrice": 0.71504,
        "stopPrice": 0.0,
        "isLimit": true,
        "instrument": "xrp_eur",
        "side": 1
    }
]

HTTP Codes and Errors

200 OK

400 Bad Request: incorrect parameters

{
    "errors": [
        {
            "message": "Unknown instrument 'gold_silver'",
            "value": "gold_silver",
            "key": "instrument"
        }
    ]
}

401 Unauthorized: incorrect keys or ts value differs from the current time by more than 5 seconds

404 Not Found

{
    "errors": [
        {
            "message": "Not Found",
            "key": "instrument"
        }
    ]
}

429 Too Many Requests: API Rate Limits violated

500 Internal Server Error

{
    "errors": [
        {
            "message": "Stop orders are not supported."
        }
    ]
}

503 Service Unavailable

Either JSON:

{
    "errors": [
        {
            "message": "System is currently overloaded."
        }
    ]
}

or string:

"This service is currently undergoing maintenance."

Public WebSocket Methods

Real-Time Order Book Data

Open connection with public hub: [base]/marketdata/info

Order book channel name is “Book”.

Attention

Upon subscription, a complete snapshot of a book will be sent (snapshot: true), after that subsequent responses will contain only updates, not the whole book (snapshot: false).

For response details ref. to Order Book Snapshot response description.

Response example
{
    "instrument": "btc_usd",
    "bids": [
        {
            "amount": 0,
            "price": 11883.731508
        },
        {
            "amount": 0,
            "price": 11884.241457
        },
        {
            "amount": 0,
            "price": 11884.251456
        },
        {
            "amount": 6.57132172,
            "price": 11884.421439
        },
        {
            "amount": 4.18222543,
            "price": 11884.431438
        },
        {
            "amount": 0,
            "price": 11885.181363
        },
        {
            "amount": 1.30694544,
            "price": 11887.141167
        }
    ],
    "asks": [
        {
            "amount": 12.40938478,
            "price": 11890.1889
        },
        {
            "amount": 28.87423081,
            "price": 11890.208902
        },
        {
            "amount": 1.30694544,
            "price": 11890.58894
        },
        {
            "amount": 0,
            "price": 11890.728954
        }
    ],
    "version": 443366001,
    "askTotalAmount": 170.26792556,
    "bidTotalAmount": 164.11677626,
    "snapshot": false
}
JavaScript
 1const { HubConnectionBuilder } = require("@microsoft/signalr"); // Package version must be >= 5.0.0
 2
 3const url = "https://api.b2bx.exchange:8443/trading/marketdata/info";
 4const instrument = "btc_usd";
 5const channel = 'Book';
 6
 7let connection = new HubConnectionBuilder()
 8    .withUrl(url)
 9    .build();
10
11connection.start().then(function () {
12connection.stream(channel, instrument)
13    .subscribe({
14        next: (item) => {
15		console.log(JSON.stringify(item));
16        },
17        error: (err) => {
18            console.log(err);
19        },
20}); 
21});

Real-Time Exchange Status

New in version v1.7.0.

Open connection with public hub: [base]/status-api/status

One of the following exchange statuses is returned:

  • online

  • maintenance

  • down

Response example
    {
        "exchangeStatus":"maintenance",
    }

Private WebSocket Methods

Orders Data

Open connection with private hub: [base]/ws/account

Open orders channel name is “OpenOrders”.

Upon subscription, the following JSON-object will be sent (for details ref. to Place an Order response description).

Response example
[
    {
        "orderId": "-72057593698565937",
        "total": 0,
        "orderType": 0,
        "commission": 0,
        "createdAt": "2020-09-01T09:01:15.3651338Z",
        "unitsFilled": 0,
        "isPending": true,
        "status": 0,
        "type": "sell",
        "amount": 1,
        "remaining": 1,
        "price": 1,
	"executionPrice": 0.0,
        "requestedPrice": 10029.0,
        "stopPrice": 0,
        "isLimit": true,
        "instrument": "btc_usdt",
        "side": 1
    }
]
JavaScript
 1const { HubConnectionBuilder } = require("@microsoft/signalr"); // Package version must be >= 5.0.0
 2const crypto = require("crypto");
 3const Key = "7fa6ceec-d8fc..."; // Change to your PublicKey
 4const Secret = "7ae49b5b-99db..."; // Change to your Secret
 5const Payload = new Date().toISOString();
 6	const Sign = crypto
 7	.createHmac('sha512', Secret)
 8	.update(Payload)
 9	.digest('hex')
10	.toUpperCase();
11const headers = {
12    Key,
13    Payload,
14    Sign
15};
16
17const url = "https://api.b2bx.exchange:8443/trading/frontoffice/ws/account";
18const channel = "OpenOrders";
19let connection = new HubConnectionBuilder()
20    .withUrl(url, {headers: headers})
21    .build();
22
23connection.start().then(function () {
24connection.stream(channel)
25    .subscribe({
26        next: (item) => {
27		console.log(JSON.stringify(item));
28        },
29        error: (err) => {
30            console.log(err);
31        },
32}); 
33});

Real-Time Balances

Open connection with private hub: [base]/ws/account

Balance updates channel name is “FullBalance”.

Upon subscription, a JSON-structure with the following fields will be sent:

asset string

Asset name

amount number

Asset amount

balance number

Full balance

locked number

Locked amount

Response example
[
    {
        "asset": "ada",
        "amount": 1000000000,
        "balance": 1000000000,
        "locked": 0
    },
    {
        "asset": "b2bx",
        "amount": 10000000,
        "balance": 10000000,
        "locked": 0
    },
    {
        "asset": "bch",
        "amount": 9999999.99999999,
        "balance": 9999999.99999999,
        "locked": 0
    }
]
JavaScript
 1const { HubConnectionBuilder } = require("@microsoft/signalr"); // Package version must be >= 5.0.0
 2const crypto = require("crypto");
 3const Key = "7fa6ceec-d8fc..."; // Change to your PublicKey
 4const Secret = "7ae49b5b-99db..."; // Change to your Secret
 5const Payload = new Date().toISOString();
 6	const Sign = crypto
 7	.createHmac('sha512', Secret)
 8	.update(Payload)
 9	.digest('hex')
10	.toUpperCase();
11const headers = {
12    Key,
13    Payload,
14    Sign
15};
16
17const url = "https://api.b2bx.exchange:8443/trading/frontoffice/ws/account";
18const channel = "FullBalance";
19let connection = new HubConnectionBuilder()
20    .withUrl(url, {headers: headers})
21    .build();
22
23connection.start().then(function () {
24connection.stream(channel, {})
25    .subscribe({
26        next: (item) => {
27		console.log(JSON.stringify(item));
28        },
29        error: (err) => {
30            console.log(err);
31        },
32}); 
33});