# Welcome to TruBit

## TruBit Open Api

* doc directory: Include the openapi doc, easily make your own sdk with the doc.
* SDK directory: Include java and python sdk

## Spot API Endpoints for TruBit Pro

| Name               | base endpoint                 |
| ------------------ | ----------------------------- |
| rest-api           | `https://api-spot.trubit.com` |
| web-socket-streams | `wss://ws.trubit.com`         |
| user-data-stream   | `wss://ws.trubit.com`         |

## Contract API Endpoints for TruBit Pro

| Name             | base endpoint                                  |
| ---------------- | ---------------------------------------------- |
| market-api       | `https://api-futures.trubit.com/market/api/v1` |
| trade-api        | `https://api-futures.trubit.com/trade/api/v1`  |
| market-websocket | `wss://api-futures.trubit.com/ws/market`       |
| trade-websocket  | `wss://api-futures.trubit.com/ws/trade`        |

## Block Trade API Endpoints for TruBit Pro

| Name     | base endpoint                |
| -------- | ---------------------------- |
| rest-api | `https://api-otc.trubit.com` |

**If you have any question, please contact our customer service. We will answer you as soon as we can. Thanks.**


# Spot


# Api Endpoints for TruBit Exchange

| Name               | base endpoint                                                  |
| ------------------ | -------------------------------------------------------------- |
| rest-api           | [**https://api-spot.trubit.com**](https://api-spot.trubit.com) |
| web-socket-streams | [**wss://ws.trubit.com**](wss://ws.trubit.com)                 |
| user-data-stream   | [**wss://ws.trubit.com**](wss://ws.trubit.com)                 |


# Error codes

Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary. Here is the error JSON payload:

```javascript
{
  "code":-1121,
  "msg":"Invalid symbol."
}
```

## 10xx - General Server or Network issues

### -1000 UNKNOWN

* An unknown error occured while processing the request.

### -1001 DISCONNECTED

* Internal error; unable to process your request. Please try again.

### -1002 UNAUTHORIZED

* You are not authorized to execute this request. Request need API Key included in . We suggest that API Key be included in any request.

### -1003 TOO\_MANY\_REQUESTS

* Too many requests; please use the websocket for live updates.
* Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API.
* Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans.

### -1006 UNEXPECTED\_RESP

* An unexpected response was received from the message bus. Execution status unknown. OPEN API server find some exception in execute request .Please report to Customer service.

### -1007 TIMEOUT

* Timeout waiting for response from backend server. Send status unknown; execution status unknown.

### -1014 UNKNOWN\_ORDER\_COMPOSITION

* Unsupported order combination.

### -1015 TOO\_MANY\_ORDERS

* Reach the rate limit .Please slow down your request speed.
* Too many new orders.
* Too many new orders; current limit is %s orders per %s.

### -1016 SERVICE\_SHUTTING\_DOWN

* This service is no longer available.

### -1020 UNSUPPORTED\_OPERATION

* This operation is not supported.

### -1021 INVALID\_TIMESTAMP

* Timestamp for this request is outside of the recvWindow.
* Timestamp for this request was 1000ms ahead of the server's time.
* Please check the difference between your local time and server time .

### -1022 INVALID\_SIGNATURE

* Signature for this request is not valid.

## 11xx - Request issues

### -1100 ILLEGAL\_CHARS

* Illegal characters found in a parameter.
* Illegal characters found in parameter '%s'; legal range is '%s'.

### -1101 TOO\_MANY\_PARAMETERS

* Too many parameters sent for this endpoint.
* Too many parameters; expected '%s' and received '%s'.
* Duplicate values for a parameter detected.

### -1102 MANDATORY\_PARAM\_EMPTY\_OR\_MALFORMED

* A mandatory parameter was not sent, was empty/null, or malformed.
* Mandatory parameter '%s' was not sent, was empty/null, or malformed.
* Param '%s' or '%s' must be sent, but both were empty/null!

### -1103 UNKNOWN\_PARAM

* An unknown parameter was sent.
* In TruBit Open Api , each request requires at least one parameter. {Timestamp}.

### -1104 UNREAD\_PARAMETERS

* Not all sent parameters were read.
* Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'.

### -1105 PARAM\_EMPTY

* A parameter was empty.
* Parameter '%s' was empty.

### -1106 PARAM\_NOT\_REQUIRED

* A parameter was sent when not required.
* Parameter '%s' sent when not required.

### -1111 BAD\_PRECISION

* Precision is over the maximum defined for this asset.

### -1112 NO\_DEPTH

* No orders on book for symbol.

### -1114 TIF\_NOT\_REQUIRED

* TimeInForce parameter sent when not required.

### -1115 INVALID\_TIF

* Invalid timeInForce.
* In the current version, this parameter is either empty or GTC.

### -1116 INVALID\_ORDER\_TYPE

* Invalid orderType.
* In the current version , ORDER\_TYPE values is LIMIT or MARKET.

### -1117 INVALID\_SIDE

* Invalid side.
* ORDER\_SIDE values is BUY or SELL

### -1118 EMPTY\_NEW\_CL\_ORD\_ID

* New client order ID was empty.

### -1119 EMPTY\_ORG\_CL\_ORD\_ID

* Original client order ID was empty.

### -1120 BAD\_INTERVAL

* Invalid interval.

### -1121 BAD\_SYMBOL

* Invalid symbol.

### -1125 INVALID\_LISTEN\_KEY

* This listenKey does not exist.

### -1127 MORE\_THAN\_XX\_HOURS

* Lookup interval is too big.
* More than %s hours between startTime and endTime.

### -1128 OPTIONAL\_PARAMS\_BAD\_COMBO

* Combination of optional parameters invalid.

### -1130 INVALID\_PARAMETER

* Invalid data sent for a parameter.
* Data sent for paramter '%s' is not valid.

### -1132 ORDER\_PRICE\_TOO\_HIGH

* Order price too high.

### -1133 ORDER\_PRICE\_TOO\_SMALL

* Order price lower than the minimum,please check general info.

### -1134 ORDER\_PRICE\_PRECISION\_TOO\_LONG

* Order price decimal too long,please check general info.

### -1135 ORDER\_QUANTITY\_TOO\_BIG

* Order quantity too large.

### -1136 ORDER\_QUANTITY\_TOO\_SMALL

* Order quantity lower than the minimum.

### -1137 ORDER\_QUANTITY\_PRECISION\_TOO\_LONG

* Order quantity decimal too long.

### -1138 ORDER\_PRICE\_WAVE\_EXCEED

* Order price exceeds permissible range.

### -1139 ORDER\_HAS\_FILLED

* Order has been filled.

### -1140 ORDER\_AMOUNT\_TOO\_SMALL

* Transaction amount lower than the minimum.

### -1141 ORDER\_DUPLICATED

* Duplicate clientOrderId

### -1142 ORDER\_CANCELLED

* Order has been canceled

### -1143 ORDER\_NOT\_FOUND\_ON\_ORDER\_BOOK

* Cannot be found on order book

### -1144 ORDER\_LOCKED

* Order has been locked

### -1145 ORDER\_NOT\_SUPPORT\_CANCELLATION

* This order type does not support cancellation

### -1146 ORDER\_CREATION\_TIMEOUT

* Order creation timeout

### -1147 ORDER\_CANCELLATION\_TIMEOUT

* Order cancellation timeout

### -2010 NEW\_ORDER\_REJECTED

* NEW\_ORDER\_REJECTED

### -2011 CANCEL\_REJECTED

* CANCEL\_REJECTED

### -2013 NO\_SUCH\_ORDER

* Order does not exist.

### -2014 BAD\_API\_KEY\_FMT

* API-key format invalid.

### -2015 REJECTED\_MBX\_KEY

* Invalid API-key, IP, or permissions for action.

### -2016 NO\_TRADING\_WINDOW

* No trading window could be found for the symbol. Try ticker/24hrs instead.

## Messages for -1010 ERROR\_MSG\_RECEIVED, -2010 NEW\_ORDER\_REJECTED, and -2011 CANCEL\_REJECTED

This code is sent when an error has been returned by the matching engine. The following messages which will indicate the specific error:

| Error message                                                 | Description                                                                                 |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| "Unknown order sent."                                         | The order (by either `orderId`, `clOrdId`, `origClOrdId`) could not be found                |
| "Duplicate order sent."                                       | The `clOrdId` is already in use                                                             |
| "Market is closed."                                           | The symbol is not trading                                                                   |
| "Account has insufficient balance for requested action."      | Not enough funds to complete the action                                                     |
| "Market orders are not supported for this symbol."            | `MARKET` is not enabled on the symbol                                                       |
| "Iceberg orders are not supported for this symbol."           | `icebergQty` is not enabled on the symbol                                                   |
| "Stop loss orders are not supported for this symbol."         | `STOP_LOSS` is not enabled on the symbol                                                    |
| "Stop loss limit orders are not supported for this symbol."   | `STOP_LOSS_LIMIT` is not enabled on the symbol                                              |
| "Take profit orders are not supported for this symbol."       | `TAKE_PROFIT` is not enabled on the symbol                                                  |
| "Take profit limit orders are not supported for this symbol." | `TAKE_PROFIT_LIMIT` is not enabled on the symbol                                            |
| "Price\* QTY is zero or less."                                | `price`\* `quantity` is too low                                                             |
| "IcebergQty exceeds QTY."                                     | `icebergQty` must be less than the order quantity                                           |
| "This action disabled is on this account."                    | Contact customer support; some actions have been disabled on the account.                   |
| "Unsupported order combination"                               | The `orderType`, `timeInForce`, `stopPrice`, and/or `icebergQty` combination isn't allowed. |
| "Order would trigger immediately."                            | The order's stop price is not valid when compared to the last traded price.                 |
| "Cancel order is invalid. Check origClOrdId and orderId."     | No `origClOrdId` or `orderId` was sent in.                                                  |
| "Order would immediately match and take."                     | `LIMIT_MAKER` order type would immediately match and trade, and not be a pure maker order.  |

## -9xxx Filter failures

| Error message                               | Description                                                                              |
| ------------------------------------------- | ---------------------------------------------------------------------------------------- |
| "Filter failure: PRICE\_FILTER"             | `price` is too high, too low, and/or not following the tick size rule for the symbol.    |
| "Filter failure: LOT\_SIZE"                 | `quantity` is too high, too low, and/or not following the step size rule for the symbol. |
| "Filter failure: MIN\_NOTIONAL"             | `price`\* `quantity` is too low to be a valid order for the symbol.                      |
| "Filter failure: MAX\_NUM\_ORDERS"          | Account has too many open orders on the symbol.                                          |
| "Filter failure: MAX\_ALGO\_ORDERS"         | Account has too many open stop loss and/or take profit orders on the symbol.             |
| "Filter failure: BROKER\_MAX\_NUM\_ORDERS"  | Account has too many open orders on the exchange.                                        |
| "Filter failure: BROKER\_MAX\_ALGO\_ORDERS" | Account has too many open stop loss and/or take profit orders on the exchange.           |
| "Filter failure: ICEBERG\_PARTS"            | Iceberg order would break into too many parts; icebergQty is too small.                  |


# Options Open API

## Base URL

The base url of open API can be found [here](https://github.com/Galactic-Tech/GitBook/blob/main/Spot/endpoint.md)

## Public Options Endpoints

### `exchange`

Current trading rules and symbol information.

#### **Request Weight:**

0

#### **Request Url:**

```bash
GET /openapi/v1/exchange
```

#### **Parameters:**

None

#### **Response:**

| name         | type   | example         | description                                   |
| ------------ | ------ | --------------- | --------------------------------------------- |
| `timezone`   | string | `UTC`           | Timezone of timestamp                         |
| `serverTime` | long   | `1554887652929` | Retrieves the current time on server (in ms). |

In the `symbols` field, the endpoint will return information on current actively trading cryptos. You can ignore this section.

In the `options` field: All actively trading options will be displayed.

| name                  | type   | example         | description                         |
| --------------------- | ------ | --------------- | ----------------------------------- |
| `symbol`              | string | `BTC0308CS3900` | Name of the option                  |
| `status`              | string | `TRADING`       | Status of the option                |
| `baseAsset`           | string | `BTC0308CS3900` | Underlying asset for the option     |
| `baseAssetPrecision`  | float  | `0.001`         | Precision of the option quantity    |
| `quoteAsset`          | string | `BUSDT`         | Quote asset for the option          |
| `quoteAssetPrecision` | float  | `0.01`          | Precision of the option price       |
| `icebergAllowed`      | string | `false`         | Whether iceberg orders are allowed. |

For `filters` in `options` field:

| name          | type   | example           | description                                            |
| ------------- | ------ | ----------------- | ------------------------------------------------------ |
| `filterType`  | string | `PRICE_FILTER`    | Type of the filter.                                    |
| `minPrice`    | float  | `0.001`           | Precision of the option price。                         |
| `maxPrice`    | float  | `100000.00000000` |                                                        |
| `tickSize`    | float  | `0.001`           | Precision of the option price.                         |
| `minQty`      | float  | `0.01`            | Minimal trading quantity of the option                 |
| `maxQty`      | float  | `100000.00000000` |                                                        |
| `stepSize`    | float  | `0.001`           | Precision of the option quantity                       |
| `minNotional` | float  | `1`               | Precision of the option order size (quantity \* price) |

#### **Example:**

```js
{
  'timezone': 'UTC',
  'serverTime': '1555048558151',
  'brokerFilters': [],
  'symbols': [{...}],
  'options': [
        {
          'filters': [
            {
              'minPrice': '0.01',
              'maxPrice': '100000.00000000',
              'tickSize': '0.01',
              'filterType': 'PRICE_FILTER'
            },
            {
              'minQty': '0.01',
              'maxQty': '100000.00000000',
              'stepSize': '0.001',
              'filterType': 'LOT_SIZE'
            },
            {
              'minNotional': '1',
              'filterType': 'MIN_NOTIONAL'
            }
          ],
          'exchangeId': '301',
          'symbol': 'BTC0412PS5100',
          'status': 'TRADING',
          'baseAsset': 'BTC0412PS5100',
          'baseAssetPrecision': '0.001',
          'quoteAsset': 'USDT',
          'quotePrecision': '0.01',
          'icebergAllowed': False
          },...
        ]
      }      
```

### `getOptions`

Retrieves available trading and expired options. Expired options will be returned if `expired` is set `true`.

#### **Request Weight:**

1

#### **Request URL:**

```
GET /openapi/v1/getOptions
```

#### **Parameters：**

| name      | type   | required | default | description                                                                                                    |
| --------- | ------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------- |
| `expired` | string | `NO`     | `false` | Set to `true` to show expired options instead of active ones. This can be useful for retrieving historic data. |

#### **Response:**

| name         | type    | example         | description                                                                                                       |
| ------------ | ------- | --------------- | ----------------------------------------------------------------------------------------------------------------- |
| `symbol`     | string  | `BTC0412CS5400` | Name of the option. 'underlying - expiration date - option type(CS is call spread and PS is put spread) - strike' |
| `strike`     | float   | `5400.0`        | The strike price of the option.                                                                                   |
| `created`    | long    | `1554710400000` | Unix timestamp when the option was first created (ms).                                                            |
| `expiration` | long    | `1555055400000` | Unix timestamp when the option will expire (ms)                                                                   |
| `optionType` | integer | `1`             | `1`=Call Spread, `0`= Put Spread                                                                                  |
| `maxPayoff`  | float   | `500`           | The maximum payoff of the option.                                                                                 |
| `underlying` | string  | `BTCBUSDT`      | The underlying price index name of the option                                                                     |
| `settlement` | string  | `weekly`        | The settlement interval.                                                                                          |

#### **Example:**

```js
[
  {'symbol': 'BTC0412PS5100',
  'strike': '5100.0',
  'created': '1554710400000',
  'expiration': '1555055400000',
  'optionType': 0,
  'maxPayOff': '500.0',
  'underlying': 'BTCUSDT',
  'settlement': 'weekly'
},...
      ]
```

### `index`

Retrieves the current index price and EDP. This API endpoint does not take any Parameters.

#### **Request Weight:**

0

#### **Request URL:**

```
GET /openapi/quote/v1/option/index
```

#### **Parameters:**

None

#### **Response：**

| name    | type  | example   | description                                                            |
| ------- | ----- | --------- | ---------------------------------------------------------------------- |
| `index` | float | `3652.81` | The currency index price.                                              |
| `edp`   | float | `3652.81` | Estimated delivery price (Average index price in the last 10 minutes). |

#### **Example:**

```js
{
  'BTCUSDT':{
    'index':3795.77,
    'edp': 3652.81
  },
  ...
}
```

### `depth`

Retrieves the options order book.

#### **Request Weight:**

Adjusted based on the limit:

| Limit              | Weight |
| ------------------ | ------ |
| 5, 10, 20, 50, 100 | 1      |
| 500                | 5      |
| 1000               | 10     |

#### **Request Url:**

```
GET /openapi/quote/v1/option/depth
```

#### **Parameters:**

| parameter | type    | required | default                                                                                     | description                                        |
| --------- | ------- | -------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `symbol`  | string  | `YES`    | The option name for which to retrieve the order book, use `getOptions` to get option names. |                                                    |
| `limit`   | integer | `NO`     | `100` (max = 100)                                                                           | The number of entries to return for bids and asks. |

#### **Response:**

| name   | type | example         | description                                                     |
| ------ | ---- | --------------- | --------------------------------------------------------------- |
| `time` | long | `1550829103981` | Current timestamp (ms)                                          |
| `bids` | list | (see below)     | List of all bids, best bids first. See below for entry details. |
| `asks` | list | (see below)     | List of all asks, best asks first. See below for entry details. |

The fields `bids` and `asks` are lists of order book price level entries, sorted from best to worst.

| name | type  | example  | description                                       |
| ---- | ----- | -------- | ------------------------------------------------- |
| `''` | float | `123.10` | price level                                       |
| `''` | float | `300`    | The total quantity of orders for this price level |

#### **Example:**

```js
{
  'time': 1555049455783,
  'bids': [
   ['78.82', '0.526'],//[Price, Quantity]
   ['77.24', '1.22'],
   ['76.65', '1.043'],
   ['76.58', '1.34'],
   ['75.67', '1.52'],
   ['75.12', '0.635'],
   ['75.02', '0.72'],
   ['75.01', '0.672'],
   ['73.73', '1.282'],
   ['73.58', '1.116'],
   ['73.45', '0.471'],
   ['73.44', '0.483'],
   ['72.32', '0.383'],
   ['72.26', '1.283'],
   ['72.11', '0.703'],
   ['70.61', '0.454']],
   'asks': [
     ['122.96', '0.381'],//[Price, Quantity]
     ['144.46', '1'],
     ['155.55', '0.065'],
     ['160.16', '0.052'],
     ['200', '0.775'],
     ['249', '0.17'],
     ['250', '1'],
     ['300', '1'],
     ['400', '1'],
     ['499', '1']]
   }

```

### `trades`

Retrieve the latest trades that have occurred for a specific option.

#### **Request Weight:**

1

#### **Request URL:**

```
GET /openapi/quote/v1/option/trades
```

#### **Parameters：**

| Parameter | type    | required                   | default                 | description                   |
| --------- | ------- | -------------------------- | ----------------------- | ----------------------------- |
| `symbol`  | string  | `YES`                      | The name of the option. |                               |
| `limit`   | integer | `NO` (clamped to max 1000) | `100`                   | The number of trades returned |

#### **Response:**

| name           | type   | example         | description                                                 |
| -------------- | ------ | --------------- | ----------------------------------------------------------- |
| `price`        | float  | `0.055`         | The price of the trade                                      |
| `time`         | long   | `1537797044116` | Current timestamp (ms)                                      |
| `qty`          | float  | `5`             | The quantity traded                                         |
| `isBuyerMaker` | string | `true`          | Maker or taker of the trade. `true`= maker, `false` = taker |

#### **Example:**

```js
[
  {
    'price': '1.21',
    'time': 1555034474064,
    'qty': '0.725',
    'isBuyerMaker': False
  },...
]
```

### `klines`

Retrieves the kline information (open, high, trade volume, etc.) for a specific option.

#### **Request Weight:**

1

#### **Request URL:**

```
GET /openapi/quote/v1/option/klines
```

#### **Parameters：**

| Parameter  | type    | required | default                                                                                   | description                                        |
| ---------- | ------- | -------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `symbol`   | string  | `YES`    | Name of the option.                                                                       |                                                    |
| `interval` | string  | `YES`    | Interval of the kline. Possible values include: `1m`,`5m`,`15m`,`30m`,`1h`,`1d`,`1w`,`1M` |                                                    |
| `limit`    | integer | `NO`     | `1000`                                                                                    | Number of entries returned. Max is capped at 1000. |
| `to`       | integer | `NO`     | timestamp of the last datapoint                                                           |                                                    |

#### **Response:**

| name | type    | example           | description                  |
| ---- | ------- | ----------------- | ---------------------------- |
| `''` | long    | `1538728740000`   | Open Time                    |
| `''` | float   | `36.00000'`       | Open                         |
| `''` | float   | `36.00000`        | High                         |
| `''` | float   | `36.00000`        | Low                          |
| `''` | float   | `36.00000`        | Close                        |
| `''` | float   | `148976.11427815` | Trade volume amount          |
| `''` | long    | `1538728740000`   | Close time                   |
| `''` | float   | `2434.19055334`   | Quote asset volume           |
| `''` | integer | `308`             | Number of trades             |
| `''` | float   | `1756.87402397`   | Taker buy base asset volume  |
| `''` | float   | `28.46694368`     | Taker buy quote asset volume |

#### **Example:**

```js
[
  [
    1538728740000, //'opentime'
    '36.000000000000000000', //'open'
    '36.000000000000000000', //'high'
    '36.000000000000000000', //'low':
    '36.000000000000000000', //'close'
    '148976.11427815',  // Volume
    1499644799999,      // Close time
    '2434.19055334',    // Quote asset volume
    308,                // Number of trades
    '1756.87402397',    // Taker buy base asset volume
    '28.46694368'       // Taker buy quote asset volume
  ],...
]
```

`base asset` refers to the asset that is the quantity of a symbol.

`quote asset` refers to the asset that is the price of a symbol.

## Private Options Endpoints

### `order`

Places a buy order for an option. This API endpoint requires your request to be signed.

#### **Request Weight:**

1

#### **Request URL:**

```bash
POST /openapi/openapi/option/order
```

#### **Parameters：**

| Parameter       | type        | required                       | example         | description                                                       |
| --------------- | ----------- | ------------------------------ | --------------- | ----------------------------------------------------------------- |
| `symbol`        | string      | `YES`                          | `BTC0412PS3900` | Name of option                                                    |
| `clientOrderId` | string/long | `NO`                           | `as78sda9f`     | A unique ID of the order. Automatically generated if not sent.    |
| `side`          | string      | `YES`                          | `BUY`           | Direction of the order. Possible values include `BUY` and `SELL`. |
| `type`          | string      | `YES`                          | `LIMIT`         | The order type, possible types: `LIMIT`, `MARKET`                 |
| `timeInForce`   | string      | `NO`                           | `GTC`           | Time in force. Possible values include `GTC`,`FOK`,`IOC`.         |
| `price`         | float       | `NO` Required for limit orders | `3213.32`       | Price of the order                                                |
| `quantity`      | float       | `YES`                          | `22.12`         | The number of contracts to buy                                    |

You can get options' price, quantity configuration data in the `exchange` endpoint.

#### **Response:**

| Name            | type    | example                       | description                                                                                                     |
| --------------- | ------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `time`          | long    | `1551062936784`               | Timestamp when the order is created.                                                                            |
| `updateTime`    | long    | `1551062936784`               | Last time this order was updated                                                                                |
| `orderId`       | integer | `891`                         | ID of the order.                                                                                                |
| `clientOrderId` | integer | `213443`                      | A unique ID of the order.                                                                                       |
| `symbol`        | string  | `BTC0412CS4200`               | Name of the option.                                                                                             |
| `price`         | float   | `4765.29`                     | Price of the order.                                                                                             |
| `origQty`       | float   | `1.01`                        | Quantity ordered                                                                                                |
| `executedQty`   | float   | `1.01`                        | Quantity of orders that has been executed                                                                       |
| `avgPrice`      | float   | `4754.24`                     | Average price of filled orders.                                                                                 |
| `type`          | string  | `LIMIT`                       | The order type, possible types: `LIMIT`, `MARKET`                                                               |
| `side`          | string  | `BUY`                         | Direction of the order. Possible values include `BUY` or `SELL`                                                 |
| `status`        | string  | `NEW`                         | The state of the order.Possible values include `NEW`, `PARTIALLY_FILLED`, `FILLED`, `CANCELED`, and `REJECTED`. |
| `timeInForce`   | string  | `GTC`                         | Time in force. Possible values include `GTC`,`FOK`,`IOC`.                                                       |
| `fees`          |         | Fees incurred for this order. |                                                                                                                 |

In the `fees` field:

| Name       | type   | example | description                       |
| ---------- | ------ | ------- | --------------------------------- |
| `feeToken` | string | `USDT`  | Fee token kind.                   |
| `fee`      | float  | `0`     | Actual transaction fees occurred. |

#### **Example:**

```js
{
    'time':1541161088303,
    'updateTime': 1541161088303,
    'orderId': 28,
    'clientOrderId': 213443,
    'symbol': 'BTC0412CS4200',
    'price': 102.32,
    'origQty': 21.3,
    'executedQty': 10.2,
    'avgPrice': 3121.13
    'type': 'LIMIT',
    'side': 'SELL',
    'status': 'NEW',
    'timeInForce': 'GTC',
    'fees':[]
}
```

### `cancel`

Cancels an order, specified by `orderId` or `clientOrderId`. This API endpoint requires your request to be signed.

#### **Request Weight:**

1

#### **Request Url:**

```bash
DELETE /openapi/option/v1/order/cancel
```

#### **Parameter:**

| Parameter       | type        | required | default                 | description                              |
| --------------- | ----------- | -------- | ----------------------- | ---------------------------------------- |
| `orderId`       | integer     | `NO`     | `12817334`              | The order ID of the order to be canceled |
| `clientOrderId` | string/long | `NO`     | Unique ID of the order. |                                          |

One **MUST** be provided of these two parameters.

#### **Response:**

| Name            | type    | example                       | description                                                                                                     |
| --------------- | ------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `time`          | long    | `1541161088303`               | Timestamp when order request is submitted (ms).                                                                 |
| `updateTime`    | long    | `1551062936784`               | Last time this order was updated (ms)                                                                           |
| `orderId`       | integer | `713637304`                   | ID of the order                                                                                                 |
| `clientOrderId` | string  | `213443`                      | Unique ID of the order.                                                                                         |
| `symbol`        | string  | `BTC0412CS4200`               | name of the option                                                                                              |
| `price`         | float   | Price of the order.           |                                                                                                                 |
| `origQty`       | float   | `1.01`                        | Quantity ordered                                                                                                |
| `executedQty`   | float   | `1.01`                        | Quantity of orders that has been executed                                                                       |
| `avgPrice`      | float   | `4754.24`                     | Average price of filled orders.                                                                                 |
| `type`          | string  | `LIMIT`                       | The order type, possible types: `LIMIT`, `MARKET`                                                               |
| `side`          | string  | `BUY`                         | Direction of the order. Possible values include `BUY` or `SELL`                                                 |
| `status`        | string  | `NEW`                         | The state of the order.Possible values include `NEW`, `PARTIALLY_FILLED`, `FILLED`, `CANCELED`, and `REJECTED`. |
| `timeInForce`   | string  | `GTC`                         | Time in force. Possible values include `GTC`,`FOK`,`IOC`.                                                       |
| `fees`          |         | Fees incurred for this order. |                                                                                                                 |

In the `fees` field:

| Name       | type   | example | description                       |
| ---------- | ------ | ------- | --------------------------------- |
| `feeToken` | string | `USDT`  | Fee token kind.                   |
| `fee`      | float  | `0`     | Actual transaction fees occurred. |

#### **Example:**

```js
{
  'time':1541161088303,
  'updateTime': 1541161088303,
  'orderId': 713637304,
  'clientOrderId': 213443,
  'symbol': 'BTC0412CS4200',
  'price': 102.32,
  'origQty': 21.3,
  'executedQty': 10.2,
  'avgPrice': 3121.13
  'type': 'LIMIT',
  'side': 'SELL',
  'status': 'CANCELED', //status will always be `CANCELED` for cancel request
  'timeInForce': 'GTC',
  'fees': []
}
```

#### `openOrders`

Retrieves open orders. This API endpoint requires your request to be signed.

#### **Request Weight:**

1

#### **Request Url:**

```bash
GET /openapi/option/v1/openOrders
```

#### **Parameters:**

| Parameter | type    | required | default                                                                                | description                  |
| --------- | ------- | -------- | -------------------------------------------------------------------------------------- | ---------------------------- |
| `symbol`  | string  | `NO`     | Symbol to return open orders for. If not sent, orders of all options will be returned. |                              |
| `orderId` | integer | `NO`     | Order ID                                                                               |                              |
| `side`    | string  | `NO`     | Direction of the order, possible values include `BUY` and `SELL`.                      |                              |
| `type`    | string  | `NO`     | Order types to return, possible values include `LIMIT` and `MARKET`.                   |                              |
| `limit`   | integer | `NO`     | `20`                                                                                   | Number of entries to return. |

If `orderId` is set, it will get orders < that `orderId`. Otherwise most recent orders are returned.

#### **Response:**

| Name            | type    | example                       | description                                                                                                     |
| --------------- | ------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `time`          | long    | `1541161088303`               | Timestamp when order request is submitted (ms).                                                                 |
| `updateTime`    | long    | `1551062936784`               | Last time this order was updated (ms)                                                                           |
| `orderId`       | integer | `713637304`                   | ID of the order                                                                                                 |
| `clientOrderId` | string  | `213443`                      | Unique ID of the order.                                                                                         |
| `symbol`        | string  | `BTC0412CS4200`               | name of the option                                                                                              |
| `price`         | float   | `12.34`                       | Price of the order.                                                                                             |
| `origQty`       | float   | `1.01`                        | Quantity ordered                                                                                                |
| `executedQty`   | float   | `1.01`                        | Quantity of orders that has been executed                                                                       |
| `avgPrice`      | float   | `4754.24`                     | Average price of filled orders.                                                                                 |
| `type`          | string  | `LIMIT`                       | The order type, possible types: `LIMIT`, `MARKET`                                                               |
| `side`          | string  | `BUY`                         | Direction of the order. Possible values include `BUY` or `SELL`                                                 |
| `status`        | string  | `NEW`                         | The state of the order.Possible values include `NEW`, `PARTIALLY_FILLED`, `FILLED`, `CANCELED`, and `REJECTED`. |
| `timeInForce`   | string  | `GTC`                         | Time in force. Possible values include `GTC`,`FOK`,`IOC`.                                                       |
| `fees`          |         | Fees incurred for this order. |                                                                                                                 |

In the `fees` field:

| Name       | type   | example | description                       |
| ---------- | ------ | ------- | --------------------------------- |
| `feeToken` | string | `USDT`  | Fee token kind.                   |
| `fee`      | float  | `0`     | Actual transaction fees occurred. |

#### **Example:**

```js
[
  {
    'time': '1554948456641',
    'updateTime': '0',
    'orderId': '337326535438529024',
    'clientOrderId': '19524737',
    'symbol': 'BTC0412CS4200',
    'price': '1.98',
    'origQty': '1',
    'executedQty': '0',
    'avgPrice': '0',
    'type': 'LIMIT',
    'side': 'BUY',
    'status': 'NEW',
    'timeInForce': 'GTC',
    'fees': []
  },...

]
```

### `positions`

Retrieves current positions. This API endpoint requires your request to be signed.

#### **Request Weight:**

1

#### **Request Url:**

```bash
GET /openapi/option/v1/positions
```

#### **Parameters:**

| Parameter | type   | required | default                                                                      | description |
| --------- | ------ | -------- | ---------------------------------------------------------------------------- | ----------- |
| `symbol`  | string | `NO`     | Name of the option. If not sent, positions for all options will be returned. |             |

#### **Response:**

For each unique `symbol`, this endpoint will return the following information.

| name                | type    | example          | description                                                                                                                           |
| ------------------- | ------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `symbol`            | string  | `BTC0405PS3850`  | Name of the option.                                                                                                                   |
| `position`          | float   | `-10.760`        | The position of the option. Can be negative (short) or positive (long)                                                                |
| `margin`            | float   | `5380`           | Total margin amount for position held.                                                                                                |
| `settlementTime`    | integer | `1555056000000`  | Settlement timestamp of the option.                                                                                                   |
| `strikePrice`       | float   | `4200`           | Strike price of the option.                                                                                                           |
| `price`             | float   | `500.00`         | Current option price                                                                                                                  |
| `availablePosition` | float   | `10.76`          | Number of option contracts that can be closed.                                                                                        |
| `averagePrice`      | float   | `9693.502194671` | Average price for the position                                                                                                        |
| `changed`           | float   | `-4018.21`       | Profit or loss for holding the position.                                                                                              |
| `changedRate`       | float   | `1.02`           | **Long Position:** `changed`/`averagePrice` **Short Position:** (`changed` \* `position`) / (`margin` - `averagePrice` \* `position`) |
| `index`             | float   | `5012.28666667`  | Current index price of the underlying asset.                                                                                          |

#### **Example:**

```js
[
  {
    'symbol': 'BTC0412CS4200',
    'position': '-10.760',
    'margin': '5380',
    'settlementTime': '1555056000000',
    'strikePrice': '4200',
    'price': '500.00',
    'availablePosition': '10.76',
    'averagePrice': '126.56',
    'changedRate': '-100.00',
    'changed': '-4018.21',
    'index': '5012.28666667'
  },...
]
```

### `historyOrders`

Retrieves history of orders that have been partially or fully filled or canceled. This API endpoint requires your request to be signed.

#### **Request Weight:**

1

#### **Request Url:**

```bash
GET /openapi/option/v1/historyOrders
```

#### **Parameters:**

| Parameter     | type    | required                                                                                   | efault                                                                   | description |
| ------------- | ------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ----------- |
| `symbol`      | string  | `NO`                                                                                       | Name of the option. If not sent, orders of all options will be returned. |             |
| `side`        | string  | `buy`                                                                                      | Direction of the order. Possible values include `BUY` and `SELL`.        |             |
| `type`        | string  | Order Type. Possible values include `LIMIT` and `MARKET`.                                  |                                                                          |             |
| `orderStatus` | string  | Status of the order. Possible values include `PARTIALLY_FILLED`, `FILLED`, and `CANCELED`. |                                                                          |             |
| `limit`       | integer | `20`                                                                                       | Number of items to be returned                                           |             |

#### **Response:**

| Name            | type    | example                       | description                                                                                                     |
| --------------- | ------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `time`          | long    | `1541161088303`               | Timestamp when order request is submitted (ms).                                                                 |
| `updateTime`    | long    | `1551062936784`               | Last time this order was updated                                                                                |
| `orderId`       | integer | `713637304`                   | ID of the order                                                                                                 |
| `clientOrderId` | string  | `213443`                      | Unique ID of the order.                                                                                         |
| `symbol`        | string  | `BTC0412CS4200`               | Name of the option                                                                                              |
| `price`         | float   | Price of the order.           |                                                                                                                 |
| `origQty`       | float   | `1.01`                        | Quantity ordered                                                                                                |
| `executedQty`   | float   | `1.01`                        | Quantity of orders that has been executed                                                                       |
| `avgPrice`      | float   | `44.24`                       | Average price of filled orders.                                                                                 |
| `type`          | string  | `LIMIT`                       | The order type, possible types: `LIMIT`, `MARKET`                                                               |
| `side`          | string  | `BUY`                         | Direction of the order. Possible values include `BUY` or `SELL`                                                 |
| `status`        | string  | `NEW`                         | The state of the order.Possible values include `NEW`, `PARTIALLY_FILLED`, `FILLED`, `CANCELED`, and `REJECTED`. |
| `timeInForce`   | string  | `GTC`                         | Time in force. Possible values include `GTC`,`FOK`,`IOC`.                                                       |
| `fees`          |         | Fees incurred for this order. |                                                                                                                 |

In the `fees` field:

| Name       | type   | example | description                       |
| ---------- | ------ | ------- | --------------------------------- |
| `feeToken` | string | `USDT`  | Fee token kind.                   |
| `fee`      | float  | `0`     | Actual transaction fees occurred. |

#### **Example:**

```js
{
  [
    {
      'time':1541161088303,
      'updateTime': 1541161088303,
      'orderId': 28,
      'clientOrderId': 213443,
      'symbol': 'BTC0412CS4200',
      'price': 102.32,
      'origQty': 21.3,
      'executedQty': 10.2,
      'avgPrice': 3121.13
      'type': 'LIMIT',
      'side': 'SELL',
      'status': 'NEW',
      'timeInForce': 'GTC',
      'fees':[]
    },...
  ]
}
```

### `getOrder`

Get details on a specific order, regardless of order state.

#### **Request Weight:**

1

#### **Request Url:**

```bash
GET /openapi/option/v1/getOrder
```

#### **Parameters:**

| Parameter       | type    | required | default                                                                                        | description |
| --------------- | ------- | -------- | ---------------------------------------------------------------------------------------------- | ----------- |
| `orderId`       | integer | `NO`     | Order ID. **Either `orderId` or `clientOrderId` must be sent**                                 |             |
| `clientOrderId` | string  | `NO`     | Unique client customized ID of the order. **Either `orderId` or `clientOrderId` must be sent** |             |

#### **Response:**

| Name            | type    | example                       | description                                                                                                     |
| --------------- | ------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `time`          | long    | `1541161088303`               | Timestamp when order request is submitted (ms).                                                                 |
| `updateTime`    | long    | `1551062936784`               | Last time this order was updated                                                                                |
| `orderId`       | integer | `713637304`                   | ID of the order                                                                                                 |
| `clientOrderId` | string  | `213443`                      | Unique ID of the order.                                                                                         |
| `symbol`        | string  | `BTC0412CS4200`               | Name of the option                                                                                              |
| `price`         | float   | Price of the order.           |                                                                                                                 |
| `origQty`       | float   | `1.01`                        | Quantity ordered                                                                                                |
| `executedQty`   | float   | `1.01`                        | Quantity of orders that has been executed                                                                       |
| `avgPrice`      | float   | `44.24`                       | Average price of filled orders.                                                                                 |
| `type`          | string  | `LIMIT`                       | The order type, possible types: `LIMIT`, `MARKET`                                                               |
| `side`          | string  | `BUY`                         | Direction of the order. Possible values include `BUY` or `SELL`                                                 |
| `status`        | string  | `NEW`                         | The state of the order.Possible values include `NEW`, `PARTIALLY_FILLED`, `FILLED`, `CANCELED`, and `REJECTED`. |
| `timeInForce`   | string  | `GTC`                         | Time in force. Possible values include `GTC`,`FOK`,`IOC`.                                                       |
| `fees`          |         | Fees incurred for this order. |                                                                                                                 |

In the `fees` field:

| Name       | type   | example | description                       |
| ---------- | ------ | ------- | --------------------------------- |
| `feeToken` | string | `USDT`  | Fee token kind.                   |
| `fee`      | float  | `0`     | Actual transaction fees occurred. |

#### **Example:**

```js
{
  'time':1541161088303,
  'updateTime': 1541161088303,
  'orderId': 28,
  'clientOrderId': 213443,
  'symbol': 'BTC0412CS4200',
  'price': 102.32,
  'origQty': 21.3,
  'executedQty': 10.2,
  'avgPrice': 3121.13
  'type': 'LIMIT',
  'side': 'SELL',
  'status': 'NEW',
  'timeInForce': 'GTC',
  'fees':[]
}
```

### `myTrades`

Retrieve the trade history of the account. This API endpoint requires your request to be signed.

#### **Request Weight:**

1

#### **Request Url:**

```bash
GET /openapi/option/v1/myTrades
```

#### **Parameters:**

| Parameter | type    | required | default                                                                   | description                                         |
| --------- | ------- | -------- | ------------------------------------------------------------------------- | --------------------------------------------------- |
| `symbol`  | string  | `NO`     | Name of the option. If not sent, trades for all symbols will be returned. |                                                     |
| `limit`   | integer | `NO`     | `20`                                                                      | The number of trades returned (clamped to max 1000) |
| `side`    | string  | `NO`     | Direction of the order.                                                   |                                                     |
| `fromId`  | integer | `NO`     | TradeId to fetch from.                                                    |                                                     |
| `toId`    | integer | `NO`     | TradeId to fetch to.                                                      |                                                     |

#### **Response:**

| Name           | type   | example                | description                                                                        |
| -------------- | ------ | ---------------------- | ---------------------------------------------------------------------------------- |
| `time`         | long   | `1503439494351`        | The timestamp of the trade（ms）                                                     |
| `tradeId`      | long   | `49366`                | The ID for the trade                                                               |
| `orderId`      | long   | `630491422`            | ID of the order                                                                    |
| `matchOrderId` | long   | `630491432`            | ID of the match order                                                              |
| `price`        | float  | `0.055`                | The price of the trade.                                                            |
| `quantity`     | float  | `23.3`                 | Quantity of the trade.                                                             |
| `feeTokenName` | string | `USDT`                 | Fee token name                                                                     |
| `fee`          | float  | `0.000090000000000000` | Fee of the trade.                                                                  |
| `side`         | string | `BUY`                  | Trade side from the user's point of view. Possible values include `BUY` and `SELL` |
| `type`         | string | `LIMIT`                | The order type, possible types: `LIMIT`, `MARKET`                                  |
| `symbol`       | string | `BTC0412PS3900`        | The name of the option                                                             |

#### **Example:**

```js
[
  {
    'time': '1554897921663',
    'tradeId': '336902617393292032',
    'orderId': '336902617267462912',
    "matchOrderId": 336002617267469062,
    'price': '99',
    'quantity': '11.414',
    'feeTokenName': 'BUSDT',
    'fee': '0.1129986',
    'type': 'LIMIT',
    'side': 'BUY',
    'symbol': 'BTC0412PS3900'
  },...
]
```

### `settlements`

Retrieves settlement events that have affected your account. This API endpoint requires your request to be signed.

#### **Request Weight:**

1

#### **Request Url:**

```bash
GET  /openapi/option/v1/settlements
```

#### **Parameters:**

None

#### **Responses:**

| Name              | type    | example          | description                                                                                                                  |
| ----------------- | ------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `symbol`          | string  | `BTC0412PS3900`  | Name of the option.                                                                                                          |
| `optionType`      | string  | `call`           | Type of the option. Possible values include: 'call' and 'put'                                                                |
| `margin`          | float   | `400`            | Margin for the position                                                                                                      |
| `timestamp`       | integer | `1517299201923`  | The timestamp of the settlement.                                                                                             |
| `strikePrice`     | float   | `3740`           | Strike price of the option                                                                                                   |
| `settlementPrice` | float   | `11008.37`       | Settlement price (EDP, which is the average index price in the last 10 minutes) at time of settlement.                       |
| `maxPayoff`       | float   | `400`            | Maximum payoff of the option                                                                                                 |
| `averagePrice`    | float   | `9693.502194671` | Average price for the position                                                                                               |
| `position`        | string  | `1000`           | Position quantity                                                                                                            |
| `changed`         | float   | `20.3`           | Settlement payoff of the option                                                                                              |
| `changedRate`     | float   | `2.34`           | **Long Position**: `changed`/(averagePrice \* position). **Short Position**: `changed`/(`margin` - averagePrice \* position) |

#### **Examples:**

```js
[
  {'symbol': 'BTC0405PS3850',
  'optionType': 'put',
  'margin': '0',
  'timestamp': '1554451200000',
  'strikePrice': '3850',
  'settlementPrice': '4956.54',
  'maxPayOff': '500',
  'averagePrice': '119.27',
  'position': '0',
  'changed': '0',
  'changedRate': '0'},...
  ]       
```

### `account`

This endpoint is used to retrieve options account balance. This endpoint requires you to be signed.

#### **Request Weight:**

1

#### **Request Url:**

```bash
GET  /openapi/option/v1/account
```

#### **Parameters:**

None

#### **Response:**

| Name          | type  | example               | description                                         |
| ------------- | ----- | --------------------- | --------------------------------------------------- |
| `totalAsset`  | float | `1000.0`              | Total asset value in option account quoted in USDT. |
| `optionAsset` | float | `100.0`               | Total option value quoted in USDT                   |
| `balances`    | float | Show balance details. |                                                     |

In the `balances` field:

| Name        | type   | example | description                                  |
| ----------- | ------ | ------- | -------------------------------------------- |
| `tokenName` | string | `USDT`  | Name of the asset                            |
| `free`      | float  | `600.0` | Amount available for use                     |
| `locked`    | float  | `100.0` | Amount locked (for open orders)              |
| `margin`    | float  | `100.0` | Amount used for margin (for short positions) |

#### **Examples:**

```js
{
  'totalAsset': '8533.0606762',
  'optionAsset': '558.1832',
  'balances': [
    {
      'tokenName': 'USDT',
      'free': '0.0',
      'locked': '0.0',
      'margin': '0.0'
    },
    {
      'tokenName': 'BUSDT',
      'free': '7961.9951881',
      'locked': '12.8822881',
      'margin': '5798.0'
    },...
  ]
}
```


# Public Rest API (2018-09-25)

## General API Information

* All endpoints return either a JSON object or array.
* Data is returned in **ascending** order. Oldest first, newest last.
* All time and timestamp related fields are in milliseconds.
* HTTP `4XX` return codes are used for for malformed requests; the issue is on the sender's side.
* HTTP `429` return code is used when breaking a request rate limit.
* HTTP `418` return code is used when an IP has been auto-banned for continuing to send requests after receiving `429` codes.
* HTTP `5XX` return codes are used for internal errors; the issue is on exchange's side. It is important to **NOT** treat this as a failure operation; the execution status is **UNKNOWN** and could have been a success.
* Any endpoint can return an ERROR; the error payload is as follows:

```javascript
{
  "code": -1121,
  "msg": "Invalid symbol."
}
```

* Specific error codes and messages defined in another document.
* For `GET` endpoints, parameters must be sent as a `query string`.
* For `POST`, `PUT`, and `DELETE` endpoints, the parameters may be sent as a `query string` or in the `request body` with content type `application/x-www-form-urlencoded`. You may mix parameters between both the `query string` and `request body` if you wish to do so.
* Parameters may be sent in any order.
* If a parameter sent in both the `query string` and `request body`, the `query string` parameter will be used.

### LIMITS

* The `/openapi/v1/exchange` `rateLimits` array contains objects related to the exchange's `REQUEST_WEIGHT` and `ORDER` rate limits.
* A 429 will be returned when either rate limit is violated.
* Each route has a `weight` which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier `weight`.
* When a 429 is recieved, it's your obligation as an API to back off and not spam the API.
* **Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (http status 418).**
* IP bans are tracked and **scale in duration** for repeat offenders, **from 2 minutes to 3 days**.

### Endpoint security type

* Each endpoint has a security type that determines the how you will interact with it.
* API-keys are passed into the Rest API via the `X-BH-APIKEY` header.
* API-keys and secret-keys **are case sensitive**.
* API-keys can be configured to only access certain types of secure endpoints. For example, one API-key could be used for TRADE only, while another API-key can access everything except for TRADE routes.
* By default, API-keys can access all secure routes.

| Security Type | Description                                              |
| ------------- | -------------------------------------------------------- |
| NONE          | Endpoint can be accessed freely.                         |
| TRADE         | Endpoint requires sending a valid API-Key and signature. |
| USER\_DATA    | Endpoint requires sending a valid API-Key and signature. |
| USER\_STREAM  | Endpoint requires sending a valid API-Key.               |
| MARKET\_DATA  | Endpoint requires sending a valid API-Key.               |

* `TRADE` and `USER_DATA` endpoints are `SIGNED` endpoints.

### SIGNED (TRADE and USER\_DATA) Endpoint security

* `SIGNED` endpoints require an additional parameter, `signature`, to be sent in the `query string` or `request body`.
* Endpoints use `HMAC SHA256` signatures. The `HMAC SHA256 signature` is a keyed `HMAC SHA256` operation. Use your `secretKey` as the key and `totalParams` as the value for the HMAC operation.
* The `signature` is **not case sensitive**.
* `totalParams` is defined as the `query string` concatenated with the `request body`.

### Timing security

* A `SIGNED` endpoint also requires a parameter, `timestamp`, to be sent which should be the millisecond timestamp of when the request was created and sent.
* An additional parameter, `recvWindow`, may be sent to specify the number of milliseconds after `timestamp` the request is valid for. If `recvWindow` is not sent, **it defaults to 5000**.
* Currently, `recvWindow` is only used when creates order.
* The logic is as follows:

  ```javascript
  if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) {
    // process request
  } else {
    // reject request
  }
  ```

**Serious trading is about timing.** Networks can be unstable and unreliable, which can lead to requests taking varying amounts of time to reach the servers. With `recvWindow`, you can specify that the request must be processed within a certain number of milliseconds or be rejected by the server.

**It recommended to use a small recvWindow of 5000 or less!**

### SIGNED Endpoint Examples for POST /openapi/v1/order

Here is a step-by-step example of how to send a vaild signed payload from the Linux command line using `echo`, `openssl`, and `curl`.

| Key       | Value                                                            |
| --------- | ---------------------------------------------------------------- |
| apiKey    | tAQfOrPIZAhym0qHISRt8EFvxPemdBm5j5WMlkm3Ke9aFp0EGWC2CGM8GHV4kCYW |
| secretKey | lH3ELTNiFxCQTmi9pPcWWikhsjO04Yoqw3euoHUuOLC3GYBW64ZqzQsiOEHXQS76 |

| Parameter   | Value         |
| ----------- | ------------- |
| symbol      | ETHBTC        |
| side        | BUY           |
| type        | LIMIT         |
| timeInForce | GTC           |
| quantity    | 1             |
| price       | 0.1           |
| recvWindow  | 5000          |
| timestamp   | 1538323200000 |

#### Example 1: As a query string

* **queryString:** symbol=ETHBTC\&side=BUY\&type=LIMIT\&timeInForce=GTC\&quantity=1\&price=0.1\&recvWindow=5000\&timestamp=1538323200000
* **HMAC SHA256 signature:**

```shell
[linux]$ echo -n "symbol=ETHBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1538323200000" | openssl dgst -sha256 -hmac "lH3ELTNiFxCQTmi9pPcWWikhsjO04Yoqw3euoHUuOLC3GYBW64ZqzQsiOEHXQS76"
(stdin)= 5f2750ad7589d1d40757a55342e621a44037dad23b5128cc70e18ec1d1c3f4c6
```

* **curl command:**

```shell
(HMAC SHA256)
[linux]$ curl -H "X-BH-APIKEY: tAQfOrPIZAhym0qHISRt8EFvxPemdBm5j5WMlkm3Ke9aFp0EGWC2CGM8GHV4kCYW" -X POST 'https://$HOST/openapi/v1/order?symbol=ETHBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1538323200000&signature=5f2750ad7589d1d40757a55342e621a44037dad23b5128cc70e18ec1d1c3f4c6'
```

#### Example 2: As a request body

* **requestBody:** symbol=ETHBTC\&side=BUY\&type=LIMIT\&timeInForce=GTC\&quantity=1\&price=0.1\&recvWindow=5000\&timestamp=1538323200000
* **HMAC SHA256 signature:**

```shell
[linux]$ echo -n "symbol=ETHBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1538323200000" | openssl dgst -sha256 -hmac "lH3ELTNiFxCQTmi9pPcWWikhsjO04Yoqw3euoHUuOLC3GYBW64ZqzQsiOEHXQS76"
(stdin)= 5f2750ad7589d1d40757a55342e621a44037dad23b5128cc70e18ec1d1c3f4c6
```

* **curl command:**

```shell
(HMAC SHA256)
[linux]$ curl -H "X-BH-APIKEY: tAQfOrPIZAhym0qHISRt8EFvxPemdBm5j5WMlkm3Ke9aFp0EGWC2CGM8GHV4kCYW" -X POST 'https://$HOST/openapi/v1/order' -d 'symbol=ETHBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1538323200000&signature=5f2750ad7589d1d40757a55342e621a44037dad23b5128cc70e18ec1d1c3f4c6'
```

#### Example 3: Mixed query string and request body

* **queryString:** symbol=ETHBTC\&side=BUY\&type=LIMIT\&timeInForce=GTC
* **requestBody:** quantity=1\&price=0.1\&recvWindow=5000\&timestamp=1538323200000
* **HMAC SHA256 signature:**

```shell
[linux]$ echo -n "symbol=ETHBTC&side=BUY&type=LIMIT&timeInForce=GTCquantity=1&price=0.1&recvWindow=5000&timestamp=1538323200000" | openssl dgst -sha256 -hmac "lH3ELTNiFxCQTmi9pPcWWikhsjO04Yoqw3euoHUuOLC3GYBW64ZqzQsiOEHXQS76"
(stdin)= 885c9e3dd89ccd13408b25e6d54c2330703759d7494bea6dd5a3d1fd16ba3afa
```

* **curl command:**

```shell
(HMAC SHA256)
[linux]$ curl -H "X-BH-APIKEY: tAQfOrPIZAhym0qHISRt8EFvxPemdBm5j5WMlkm3Ke9aFp0EGWC2CGM8GHV4kCYW" -X POST 'https://$HOST/openapi/v1/order?symbol=ETHBTC&side=BUY&type=LIMIT&timeInForce=GTC' -d 'quantity=1&price=0.1&recvWindow=5000&timestamp=1538323200000&signature=885c9e3dd89ccd13408b25e6d54c2330703759d7494bea6dd5a3d1fd16ba3afa'
```

Note that the signature is different in example 3. There is no & between "GTC" and "quantity=1".

## Public API Endpoints

### Terminology

* `base asset` refers to the asset that is the `quantity` of a symbol.
* `quote asset` refers to the asset that is the `price` of a symbol.

### ENUM definitions

**Symbol status:**

* TRADING
* HALT
* BREAK

**Symbol type:**

* SPOT

**Asset type:**

* CASH
* MARGIN

**Order status:**

* NEW
* PARTIALLY\_FILLED
* FILLED
* CANCELED
* PENDING\_CANCEL
* REJECTED

**Order types:**

* LIMIT
* MARKET
* LIMIT\_MAKER
* STOP\_LOSS (unavailable now)
* STOP\_LOSS\_LIMIT (unavailable now)
* TAKE\_PROFIT (unavailable now)
* TAKE\_PROFIT\_LIMIT (unavailable now)
* MARKET\_OF\_PAYOUT (unavailable now)

**Order side:**

* BUY
* SELL

**Time in force:**

* GTC
* IOC
* FOK

**Kline/Candlestick chart intervals:**

m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

* 1m
* 3m
* 5m
* 15m
* 30m
* 1h
* 2h
* 4h
* 6h
* 8h
* 12h
* 1d
* 3d
* 1w
* 1M

**Rate limiters (rateLimitType)**

* REQUESTS\_WEIGHT
* ORDERS

**Rate limit intervals**

* SECOND
* MINUTE
* DAY

### General endpoints

#### Test connectivity

```shell
GET /openapi/v1/ping
```

Test connectivity to the Rest API.

**Weight:** 0

**Parameters:** NONE

**Response:**

```javascript
{}
```

#### Check server time

```shell
GET /openapi/v1/time
```

Test connectivity to the Rest API and get the current server time.

**Weight:** 0

**Parameters:** NONE

**Response:**

```javascript
{
  "serverTime": 1538323200000
}
```

#### Exchange information

```shell
GET /openapi/v1/exchange
```

Current trading rules and symbol information

**Weight:** 0

**Parameters:** NONE

**Response:**

```javascript
{
  "timezone": "UTC",
  "serverTime": 1538323200000,
  "rateLimits": [{
      "rateLimitType": "REQUESTS_WEIGHT",
      "interval": "MINUTE",
      "limit": 1500
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "SECOND",
      "limit": 20
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "DAY",
      "limit": 350000
    }
  ],
  "brokerFilters":[],
  "symbols": [{
    "symbol": "ETHBTC",
    "status": "TRADING",
    "baseAsset": "ETH",
    "baseAssetPrecision": "0.001",
    "quoteAsset": "BTC",
    "quotePrecision": "0.01",
    "icebergAllowed": false,
    "filters": [{
      "filterType": "PRICE_FILTER",
      "minPrice": "0.00000100",
      "maxPrice": "100000.00000000",
      "tickSize": "0.00000100"
    }, {
      "filterType": "LOT_SIZE",
      "minQty": "0.00100000",
      "maxQty": "100000.00000000",
      "stepSize": "0.00100000"
    }, {
      "filterType": "MIN_NOTIONAL",
      "minNotional": "0.00100000"
    }]
  }]
}
```

### Market Data endpoints

#### Order book

```shell
GET /openapi/quote/v1/depth
```

**Weight:** Adjusted based on the limit:

| Limit              | Weight |
| ------------------ | ------ |
| 5, 10, 20, 50, 100 | 1      |
| 500                | 5      |
| 1000               | 10     |

**Parameters:**

| Name   | Type   | Mandatory | Description           |
| ------ | ------ | --------- | --------------------- |
| symbol | STRING | YES       |                       |
| limit  | INT    | NO        | Default 100; max 100. |

**Caution:** setting limit=0 can return a lot of data.

**Response:**

\[PRICE, QTY]

```javascript
{
  "bids": [
    [
      "3.90000000",   // PRICE
      "431.00000000"  // QTY
    ],
    [
      "4.00000000",
      "431.00000000"
    ]
  ],
  "asks": [
    [
      "4.00000200",  // PRICE
      "12.00000000"  // QTY
    ],
    [
      "5.10000000",
      "28.00000000"
    ]
  ]
}
```

#### Recent trades list

```shell
GET /openapi/quote/v1/trades
```

Get recent trades (up to last 500).

**Weight:** 1

**Parameters:**

| Name   | Type   | Mandatory | Description            |
| ------ | ------ | --------- | ---------------------- |
| symbol | STRING | YES       |                        |
| limit  | INT    | NO        | Default 500; max 1000. |

**Response:**

```javascript
[
  {
    "price": "4.00000100",
    "qty": "12.00000000",
    "time": 1499865549590,
    "isBuyerMaker": true
  }
]
```

#### Kline/Candlestick data

```shell
GET /openapi/quote/v1/klines
```

Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.

**Weight:** 1

**Parameters:**

| Name      | Type   | Mandatory | Description            |
| --------- | ------ | --------- | ---------------------- |
| symbol    | STRING | YES       |                        |
| interval  | ENUM   | YES       |                        |
| startTime | LONG   | NO        |                        |
| endTime   | LONG   | NO        |                        |
| limit     | INT    | NO        | Default 500; max 1000. |

* If startTime and endTime are not sent, the most recent klines are returned.

**Response:**

```javascript
[
  [
    1499040000000,      // Open time
    "0.01634790",       // Open
    "0.80000000",       // High
    "0.01575800",       // Low
    "0.01577100",       // Close
    "148976.11427815",  // Volume
    1499644799999,      // Close time
    "2434.19055334",    // Quote asset volume
    308                // Number of trades
  ]
]
```

#### 24hr ticker price change statistics

```shell
GET /openapi/quote/v1/ticker/24hr
```

24 hour price change statistics. **Careful** when accessing this with no symbol.

**Weight:** 1 for a single symbol; **40** when the symbol parameter is omitted

**Parameters:**

| Name   | Type   | Mandatory | Description |
| ------ | ------ | --------- | ----------- |
| symbol | STRING | NO        |             |

* If the symbol is not sent, tickers for all symbols will be returned in an array.

**Response:**

```javascript
{
  "time": 1538725500422,
  "symbol": "ETHBTC",
  "bestBidPrice": "4.00000200",
  "bestAskPrice": "4.00000200",
  "lastPrice": "4.00000200",
  "openPrice": "99.00000000",
  "highPrice": "100.00000000",
  "lowPrice": "0.10000000",
  "volume": "8913.30000000"
}
```

OR

```javascript
[
  {
    "time": 1538725500422,
    "symbol": "ETHBTC",
    "lastPrice": "4.00000200",
    "openPrice": "99.00000000",
    "highPrice": "100.00000000",
    "lowPrice": "0.10000000",
    "volume": "8913.30000000"
 }
]
```

#### Symbol price ticker

```shell
GET /openapi/quote/v1/ticker/price
```

Latest price for a symbol or symbols.

**Weight:** 1

**Parameters:**

| Name   | Type   | Mandatory | Description |
| ------ | ------ | --------- | ----------- |
| symbol | STRING | NO        |             |

* If the symbol is not sent, prices for all symbols will be returned in an array.

**Response:**

```javascript
{
  "price": "4.00000200"
}
```

OR

```javascript
[
  {
    "symbol": "LTCBTC",
    "price": "4.00000200"
  },
  {
    "symbol": "ETHBTC",
    "price": "0.07946600"
  }
]
```

#### Symbol order book ticker

```shell
GET /openapi/quote/v1/ticker/bookTicker
```

Best price/qty on the order book for a symbol or symbols.

**Weight:** 1

**Parameters:**

| Name   | Type   | Mandatory | Description |
| ------ | ------ | --------- | ----------- |
| symbol | STRING | NO        |             |

* If the symbol is not sent, bookTickers for all symbols will be returned in an array.

**Response:**

```javascript
{
  "symbol": "LTCBTC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}
```

OR

```javascript
[
  {
    "symbol": "LTCBTC",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000"
  },
  {
    "symbol": "ETHBTC",
    "bidPrice": "0.07946700",
    "bidQty": "9.00000000",
    "askPrice": "100000.00000000",
    "askQty": "1000.00000000"
  }
]
```

### Account endpoints

#### New order (TRADE)

```shell
POST /openapi/v1/order  (HMAC SHA256)
```

Send in a new order.

**Weight:** 1

**Parameters:**

| Name             | Type    | Mandatory | Description                                                                                           |
| ---------------- | ------- | --------- | ----------------------------------------------------------------------------------------------------- |
| symbol           | STRING  | YES       |                                                                                                       |
| assetType        | STRING  | NO        |                                                                                                       |
| side             | ENUM    | YES       |                                                                                                       |
| type             | ENUM    | YES       |                                                                                                       |
| timeInForce      | ENUM    | NO        |                                                                                                       |
| quantity         | DECIMAL | YES       |                                                                                                       |
| price            | DECIMAL | NO        |                                                                                                       |
| newClientOrderId | STRING  | NO        | A unique id for the order. Automatically generated if not sent.                                       |
| stopPrice        | DECIMAL | NO        | Used with `STOP_LOSS`, `STOP_LOSS_LIMIT`, `TAKE_PROFIT`, and `TAKE_PROFIT_LIMIT` orders. Unavailable  |
| icebergQty       | DECIMAL | NO        | Used with `LIMIT`, `STOP_LOSS_LIMIT`, and `TAKE_PROFIT_LIMIT` to create an iceberg order. Unavailable |
| recvWindow       | LONG    | NO        |                                                                                                       |
| timestamp        | LONG    | YES       |                                                                                                       |

Additional mandatory parameters based on `type`:

| Type                | Additional mandatory parameters                 |
| ------------------- | ----------------------------------------------- |
| `LIMIT`             | `timeInForce`, `quantity`, `price`              |
| `MARKET`            | `quantity`                                      |
| `STOP_LOSS`         | `quantity`, `stopPrice`                         |
| `STOP_LOSS_LIMIT`   | `timeInForce`, `quantity`, `price`, `stopPrice` |
| `TAKE_PROFIT`       | `quantity`, `stopPrice`                         |
| `TAKE_PROFIT_LIMIT` | `timeInForce`, `quantity`, `price`, `stopPrice` |
| `LIMIT_MAKER`       | `quantity`, `price`                             |

Other info:

* `LIMIT_MAKER` are `LIMIT` orders that will be rejected if they would immediately match and trade as a taker.
* `STOP_LOSS` and `TAKE_PROFIT` will execute a `MARKET` order when the `stopPrice` is reached.
* Any `LIMIT` or `LIMIT_MAKER` type order can be made an iceberg order by sending an `icebergQty`.
* Any order with an `icebergQty` MUST have `timeInForce` set to `GTC`.

Trigger order price rules against market price for both MARKET and LIMIT versions:

* Price above market price: `STOP_LOSS` `BUY`, `TAKE_PROFIT` `SELL`
* Price below market price: `STOP_LOSS` `SELL`, `TAKE_PROFIT` `BUY`

**Response:**

```javascript
{
  "orderId": 28,
  "clientOrderId": "6k9M212T12092"
}
```

#### Test new order (TRADE)

```shell
POST /openapi/v1/order/test (HMAC SHA256)
```

Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.

**Weight:** 1

**Parameters:**

Same as `POST /openapi/v1/order`

**Response:**

```javascript
{}
```

#### Query order (USER\_DATA)

```shell
GET /openapi/v1/order (HMAC SHA256)
```

Check an order's status.

**Weight:** 1

**Parameters:**

| Name              | Type   | Mandatory | Description |
| ----------------- | ------ | --------- | ----------- |
| orderId           | LONG   | NO        |             |
| origClientOrderId | STRING | NO        |             |
| recvWindow        | LONG   | NO        |             |
| timestamp         | LONG   | YES       |             |

Notes:

* Either `orderId` or `origClientOrderId` must be sent.
* For some historical orders `cummulativeQuoteQty` will be < 0, meaning the data is not available at this time.

**Response:**

```javascript
{
  "symbol": "LTCBTC",
  "orderId": 1,
  "clientOrderId": "9t1M2K0Ya092",
  "price": "0.1",
  "origQty": "1.0",
  "executedQty": "0.0",
  "cummulativeQuoteQty": "0.0",
  "avgPrice": "0.0",
  "status": "NEW",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "BUY",
  "stopPrice": "0.0",
  "icebergQty": "0.0",
  "time": 1499827319559,
  "updateTime": 1499827319559,
  "isWorking": true
}
```

#### Cancel order (TRADE)

```shell
DELETE /openapi/v1/order  (HMAC SHA256)
```

Cancel an active order.

**Weight:** 1

**Parameters:**

| Name          | Type   | Mandatory | Description |
| ------------- | ------ | --------- | ----------- |
| orderId       | LONG   | NO        |             |
| clientOrderId | STRING | NO        |             |
| recvWindow    | LONG   | NO        |             |
| timestamp     | LONG   | YES       |             |

Either `orderId` or `clientOrderId` must be sent.

**Response:**

```javascript
{
  "symbol": "LTCBTC",
  "clientOrderId": "tU721112KM",
  "orderId": 1,
  "status": "CANCELED"
}
```

#### Current open orders (USER\_DATA)

```shell
GET /openapi/v1/openOrders  (HMAC SHA256)
```

GET all open orders on a symbol. **Careful** when accessing this with no symbol.

**Weight:** 1

**Parameters:**

| Name       | Type   | Mandatory | Description            |
| ---------- | ------ | --------- | ---------------------- |
| symbol     | String | NO        |                        |
| orderId    | LONG   | NO        |                        |
| limit      | INT    | NO        | Default 500; max 1000. |
| recvWindow | LONG   | NO        |                        |
| timestamp  | LONG   | YES       |                        |

**Notes:**

* If `orderId` is set, it will get orders < that `orderId`. Otherwise most recent orders are returned.

**Response:**

```javascript
[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "clientOrderId": "t7921223K12",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "avgPrice": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true
  }
]
```

#### History orders (USER\_DATA)

```shell
GET /openapi/v1/historyOrders (HMAC SHA256)
```

GET all orders of the account; canceled, filled or rejected.

**Weight:** 5

**Parameters:**

| Name       | Type   | Mandatory | Description            |
| ---------- | ------ | --------- | ---------------------- |
| symbol     | String | NO        |                        |
| orderId    | LONG   | NO        |                        |
| startTime  | LONG   | NO        |                        |
| endTime    | LONG   | NO        |                        |
| limit      | INT    | NO        | Default 500; max 1000. |
| recvWindow | LONG   | NO        |                        |
| timestamp  | LONG   | YES       |                        |

**Notes:**

* If `orderId` is set, it will get orders < that `orderId`. Otherwise most recent orders are returned.

**Response:**

```javascript
[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "clientOrderId": "987yjj2Ym",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "avgPrice": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true
  }
]
```

#### Account information (USER\_DATA)

```shell
GET /openapi/v1/account (HMAC SHA256)
```

GET current account information.

**Weight:** 5

**Parameters:**

| Name       | Type | Mandatory | Description |
| ---------- | ---- | --------- | ----------- |
| recvWindow | LONG | NO        |             |
| timestamp  | LONG | YES       |             |

**Response:**

```javascript
{
  "canTrade": true,
  "canWithdraw": true,
  "canDeposit": true,
  "updateTime": 123456789,
  "balances": [
    {
      "asset": "BTC",
      "free": "4723846.89208129",
      "locked": "0.00000000"
    },
    {
      "asset": "LTC",
      "free": "4763368.68006011",
      "locked": "0.00000000"
    }
  ]
}
```

#### Account trade list (USER\_DATA)

```shell
GET /openapi/v1/myTrades  (HMAC SHA256)
```

GET trades for a specific account.

**Weight:** 5

**Parameters:**

| Name       | Type | Mandatory | Description            |
| ---------- | ---- | --------- | ---------------------- |
| startTime  | LONG | NO        |                        |
| endTime    | LONG | NO        |                        |
| fromId     | LONG | NO        | TradeId to fetch from. |
| toId       | LONG | NO        | TradeId to fetch to.   |
| limit      | INT  | NO        | Default 500; max 1000. |
| recvWindow | LONG | NO        |                        |
| timestamp  | LONG | YES       |                        |

**Notes:**

* If only `fromId` is set，it will get orders < that `fromId` in descending order.
* If only `toId` is set, it will get orders > that `toId` in ascending order.
* If `fromId` is set and `toId` is set, it will get orders < that `fromId` and > that `toId` in descending order.
* If `fromId` is not set and `toId` it not set, most recent order are returned in descending order.

**Response:**

```javascript
[
  {
    "symbol": "ETHBTC",
    "id": 28457,
    "orderId": 100234,
    "matchOrderId": 109834,
    "price": "4.00000100",
    "qty": "12.00000000",
    "commission": "10.10000000",
    "commissionAsset": "ETH",
    "time": 1499865549590,
    "isBuyer": true,
    "isMaker": false,
    "feeTokenId": "ETH",
    "fee": "0.012"
  }
]
```

#### Account deposit list (USER\_DATA)

```shell
GET /openapi/v1/depositOrders  (HMAC SHA256)
```

GET deposit orders for a specific account.

**Weight:** 5

**Parameters:**

| Name       | Type | Mandatory | Description                                                             |
| ---------- | ---- | --------- | ----------------------------------------------------------------------- |
| startTime  | LONG | NO        |                                                                         |
| endTime    | LONG | NO        |                                                                         |
| fromId     | LONG | NO        | Deposit OrderId to fetch from. Default gets most recent deposit orders. |
| limit      | INT  | NO        | Default 500; max 1000.                                                  |
| recvWindow | LONG | NO        |                                                                         |
| timestamp  | LONG | YES       |                                                                         |

**Notes:**

* If `fromId` is set, it will get orders > that `fromId`. Otherwise most recent orders are returned.

**Response:**

```javascript
[
  {
	"orderId": 100234,
	"token": "EOS",
	"address": "deposit2bh",
	"addressTag": "19012584",
	"fromAddress": "clarkkent",
	"fromAddressTag": "19029901",
	"time": 1499865549590,
	"quantity": "1.01"
  }
]
```

### User data stream endpoints

Specifics on how user data streams work is in another document.

#### Start user data stream (USER\_STREAM)

```shell
POST /openapi/v1/userDataStream
```

Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent.

**Weight:** 1

**Parameters:**

| Name       | Type | Mandatory | Description |
| ---------- | ---- | --------- | ----------- |
| recvWindow | LONG | NO        |             |
| timestamp  | LONG | YES       |             |

**Response:**

```javascript
{
  "listenKey": "1A9LWJjuMwKWYP4QQPw34GRm8gz3x5AephXSuqcDef1RnzoBVhEeGE963CoS1Sgj"
}
```

#### Keepalive user data stream (USER\_STREAM)

```shell
PUT /openapi/v1/userDataStream
```

Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 30 minutes.

**Weight:** 1

**Parameters:**

| Name       | Type   | Mandatory | Description |
| ---------- | ------ | --------- | ----------- |
| listenKey  | STRING | YES       |             |
| recvWindow | LONG   | NO        |             |
| timestamp  | LONG   | YES       |             |

**Response:**

```javascript
{}
```

#### Close user data stream (USER\_STREAM)

```shell
DELETE /openapi/v1/userDataStream
```

Close out a user data stream.

**Weight:** 1

**Parameters:**

| Name       | Type   | Mandatory | Description |
| ---------- | ------ | --------- | ----------- |
| listenKey  | STRING | YES       |             |
| recvWindow | LONG   | NO        |             |
| timestamp  | LONG   | YES       |             |

**Response:**

```javascript
{}
```

#### Sub-account list(SUB\_ACCOUNT\_LIST)

```shell
POST /openapi/v1/subAccount/query
```

Query sub-account lists

**Parameters:**

None

**Weight:** 5

**Response:**

```javascript
[
    {
        "accountId": "122216245228131",
        "accountName": "",
        "accountType": 1,
        "accountIndex": 0 // main-account: 0, sub-account: 1
    },
    {
        "accountId": "482694560475091200",
        "accountName": "createSubAccountByCurl", // sub-account name
        "accountType": 1, // sub-account type 1. token trading 3. contract trading
        "accountIndex": 1
    },
    {
        "accountId": "422446415267060992",
        "accountName": "",
        "accountType": 3,
        "accountIndex": 0
    },
    {
        "accountId": "482711469199298816",
        "accountName": "createSubAccountByCurl",
        "accountType": 3,
        "accountIndex": 1
    },
]
```

#### Internal Account Transfer (ACCOUNT\_TRANSFER)

```shell
POST /openapi/v1/transfer
```

Internal transfer

**Weight:** 1

**Parameters:**

| Name             | Typee  | Mandatory | Description                                                                                                    |
| ---------------- | ------ | --------- | -------------------------------------------------------------------------------------------------------------- |
| fromAccountType  | int    | YES       | source account type: 1. token trading account 2.Options account 3. Contracts account                           |
| fromAccountIndex | int    | YES       | sub-account index(valid when using main-account api, get sub-account indices from `SUB_ACCOUNT_LIST` endpoint) |
| toAccountType    | int    | YES       | Target account type: 1. token trading account 2.Options account 3. Contracts account                           |
| toAccountIndex   | int    | YES       | sub-account index(valid when using main-account api, get sub-account indices from `SUB_ACCOUNT_LIST` endpoint) |
| tokenId          | STRING | YES       | tokenID                                                                                                        |
| amount           | STRING | YES       | Transfer amount                                                                                                |

**Response:**

```javascript
{
    "success":"true" // success
}
```

**Explanation**

1. Either transferring or receiving account must be the main account (Token trading account)
2. Main account api can support transferring to other account(including sub-accounts) and receiving from other accounts
3. **Sub-account API only supports transferring from current account to the main-account. Therefore `fromAccountType\fromAccountIndex\toAccountType\toAccountIndex` should be left empty.**

#### Check Balance Flow (BALANCE\_FLOW)

```shell
POST /openapi/v1/balance_flow
```

Check blance flow

**Weight:** 5

**Parameters:**

| Name         | Type    | Mandatory | Description            |
| ------------ | ------- | --------- | ---------------------- |
| accountType  | int     | no        | Account account\_type  |
| accountIndex | int     | no        | Account account\_index |
| tokenId      | string  | no        | token\_id              |
| fromFlowId   | long    | no        |                        |
| endFlowId    | long    | no        |                        |
| startTime    | long    | no        | Start Time             |
| endTime      | long    | no        | End Time               |
| limit        | integer | no        | Number of entries      |

**Response:**

```javascript
[
    {
        "id": "539870570957903104",
        "accountId": "122216245228131",
        "tokenId": "BTC",
        "tokenName": "BTC",
        "flowTypeValue": 51, // balance flow type
        "flowType": "USER_ACCOUNT_TRANSFER", // balance flow type name
        "flowName": "Transfer", // balance flow type Explanation
        "change": "-12.5", // change
        "total": "379.624059937852365", // total asset after change
        "created": "1579093587214"
    },
    {
        "id": "536072393645448960",
        "accountId": "122216245228131",
        "tokenId": "USDT",
        "tokenName": "USDT",
        "flowTypeValue": 7,
        "flowType": "AIRDROP",
        "flowName": "Airdrop",
        "change": "-2000",
        "total": "918662.0917630848",
        "created": "1578640809195"
    }
]
```

**Explanation**

1. Main-account API can query balance flow for token account and other accounts(including sub-accounts, or designated `accountType` and `accountIndex` accounts)
2. Sub-account API can only query current sub-account, therefore `accountType` and `accountIndex` is not required.

**Please see the following for balance flow types**

| Category             | Parameter Type Name         | Parameter Type Id | Explanation                             |
| -------------------- | --------------------------- | ----------------- | --------------------------------------- |
| General Balance Flow | TRADE                       | 1                 | trades                                  |
| General Balance Flow | FEE                         | 2                 | trading fees                            |
| General Balance Flow | TRANSFER                    | 3                 | transfer                                |
| General Balance Flow | DEPOSIT                     | 4                 | deposit                                 |
| Derivatives          | MAKER\_REWARD               | 27                | maker reward                            |
| Derivatives          | PNL                         | 28                | PnL from contracts                      |
| Derivatives          | SETTLEMENT                  | 30                | Settlement                              |
| Derivatives          | LIQUIDATION                 | 31                | Liquidation                             |
| Derivatives          | FUNDING\_SETTLEMENT         | 32                | 期货等的资金费率结算                              |
| Internal Transfer    | USER\_ACCOUNT\_TRANSFER     | 51                | userAccountTransfer 专用，流水没有subjectExtId |
| OTC                  | OTC\_BUY\_COIN              | 65                | OTC buy coin                            |
| OTC                  | OTC\_SELL\_COIN             | 66                | OTC sell coin                           |
| OTC                  | OTC\_FEE                    | 73                | OTC fees                                |
| OTC                  | OTC\_TRADE                  | 200               | Old OTC balance flow                    |
| Campaign             | ACTIVITY\_AWARD             | 67                | Campaign reward                         |
| Campaign             | INVITATION\_REFERRAL\_BONUS | 68                | 邀请返佣                                    |
| Campaign             | REGISTER\_BONUS             | 69                | Registration reward                     |
| Campaign             | AIRDROP                     | 70                | Airdrop                                 |
| Campaign             | MINE\_REWARD                | 71                | Mining reward                           |

### Filters

Filters define trading rules on a symbol. Filters come in two forms: `symbol filters` and `broker filters`.

#### Symbol filters

**PRICE\_FILTER**

The `PRICE_FILTER` defines the `price` rules for a symbol. There are 3 parts:

* `minPrice` defines the minimum `price`/`stopPrice` allowed.
* `maxPrice` defines the maximum `price`/`stopPrice` allowed.
* `tickSize` defines the intervals that a `price`/`stopPrice` can be increased/decreased by.

In order to pass the `price filter`, the following must be true for `price`/`stopPrice`:

* `price` >= `minPrice`
* `price` <= `maxPrice`
* (`price`-`minPrice`) % `tickSize` == 0

**/exchange format:**

```javascript
  {
    "filterType": "PRICE_FILTER",
    "minPrice": "0.00000100",
    "maxPrice": "100000.00000000",
    "tickSize": "0.00000100"
  }
```

**LOT\_SIZE**

The `LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for a symbol. There are 3 parts:

* `minQty` defines the minimum `quantity`/`icebergQty` allowed.
* `maxQty` defines the maximum `quantity`/`icebergQty` allowed.
* `stepSize` defines the intervals that a `quantity`/`icebergQty` can be increased/decreased by.

In order to pass the `lot size`, the following must be true for `quantity`/`icebergQty`:

* `quantity` >= `minQty`
* `quantity` <= `maxQty`
* (`quantity`-`minQty`) % `stepSize` == 0

**/exchange format:**

```javascript
  {
    "filterType": "LOT_SIZE",
    "minQty": "0.00100000",
    "maxQty": "100000.00000000",
    "stepSize": "0.00100000"
  }
```

**MIN\_NOTIONAL**

The `MIN_NOTIONAL` filter defines the minimum notional value allowed for an order on a symbol. An order's notional value is the `price` \* `quantity`.

**/exchange format:**

```javascript
  {
    "filterType": "MIN_NOTIONAL",
    "minNotional": "0.00100000"
  }
```

**MAX\_NUM\_ORDERS**

The `MAX_NUM_ORDERS` filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter.

**/exchange format:**

```javascript
  {
    "filterType": "MAX_NUM_ORDERS",
    "limit": 25
  }
```

**MAX\_NUM\_ALGO\_ORDERS**

The `MAX_ALGO_ORDERS` filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are `STOP_LOSS`, `STOP_LOSS_LIMIT`, `TAKE_PROFIT`, and `TAKE_PROFIT_LIMIT` orders.

**/exchange format:**

```javascript
  {
    "filterType": "MAX_NUM_ALGO_ORDERS",
    "maxNumAlgoOrders": 5
  }
```

**ICEBERG\_PARTS**

The `ICEBERG_PARTS` filter defines the maximum parts an iceberg order can have. The number of `ICEBERG_PARTS` is defined as `CEIL(qty / icebergQty)`.

**/exchange format:**

```javascript
  {
    "filterType": "ICEBERG_PARTS",
    "limit": 10
  }
```

#### Broker Filters

**BROKER\_MAX\_NUM\_ORDERS**

The `MAX_NUM_ORDERS` filter defines the maximum number of orders an account is allowed to have open on the exchange. Note that both "algo" orders and normal orders are counted for this filter.

**/exchange format:**

```javascript
  {
    "filterType": "BROKER_MAX_NUM_ORDERS",
    "limit": 1000
  }
```

**BROKER\_MAX\_NUM\_ALGO\_ORDERS**

The `MAX_ALGO_ORDERS` filter defines the maximum number of "algo" orders an account is allowed to have open on the exchange. "Algo" orders are `STOP_LOSS`, `STOP_LOSS_LIMIT`, `TAKE_PROFIT`, and `TAKE_PROFIT_LIMIT` orders.

**/exchange format:**

```javascript
  {
    "filterType": "BROKER_MAX_NUM_ALGO_ORDERS",
    "limit": 200
  }
```

#### user transfer (TRANSFER)

```shell
POST /openapi/v1/user/transfer
```


# User Data Streams

## General WSS information

* A User Data Stream `listenKey` is valid for 60 minutes after creation.
* Doing a `PUT` on a `listenKey` will extend its validity for 60 minutes.
* Doing a `DELETE` on a `listenKey` will close the stream.
* User Data Streams are accessed at **/openapi/ws/\<listenKey>**
* A single connection to api endpoint is only valid for 24 hours; expect to be disconnected at the 24 hour mark
* User data stream payloads are **not guaranteed** to be in order during heavy periods; **make sure to order your updates using E**

## API Endpoints

### Create a listenKey

```shell
POST /openapi/v1/userDataStream
```

Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent.

**Weight:** 1

**Parameters:**

| Name       | Type | Mandatory | Description |
| ---------- | ---- | --------- | ----------- |
| recvWindow | LONG | NO        |             |
| timestamp  | LONG | YES       |             |

**Response:**

```javascript
{
  "listenKey": "1A9LWJjuMwKWYP4QQPw34GRm8gz3x5AephXSuqcDef1RnzoBVhEeGE963CoS1Sgj"
}
```

### Ping/Keep-alive a listenKey

```shell
PUT /openapi/v1/userDataStream
```

Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 30 minutes.

**Weight:** 1

**Parameters:**

| Name       | Type   | Mandatory | Description |
| ---------- | ------ | --------- | ----------- |
| listenKey  | STRING | YES       |             |
| recvWindow | LONG   | NO        |             |
| timestamp  | LONG   | YES       |             |

**Response:**

```javascript
{}
```

### Close a listenKey

```shell
DELETE /openapi/v1/userDataStream
```

Close out a user data stream.

**Weight:** 1

**Parameters:**

| Name       | Type   | Mandatory | Description |
| ---------- | ------ | --------- | ----------- |
| listenKey  | STRING | YES       |             |
| recvWindow | LONG   | NO        |             |
| timestamp  | LONG   | YES       |             |

**Response:**

```javascript
{}
```

## Web Socket Payloads

### Account Update

Account state is updated with the `outboundAccountInfo` event.

**Payload:**

```javascript
{
  "e": "outboundAccountInfo",   // Event type
  "E": 1499405658849,           // Event time
  // "m": 0,                       // Maker commission rate (bips)
  // "t": 0,                       // Taker commission rate (bips)
  // "b": 0,                       // Buyer commission rate (bips)
  // "s": 0,                       // Seller commission rate (bips)
  "T": true,                    // Can trade?
  "W": true,                    // Can withdraw?
  "D": true,                    // Can deposit?
  // "u": 1499405658848,           // Time of last account update
  "B": [                        // Balances changed
    {
      "a": "LTC",               // Asset
      "f": "17366.18538083",    // Free amount
      "l": "0.00000000"         // Locked amount
    }
  ]
}
```

### Order Update

Orders are updated with the `executionReport` event. Check the API documentation and below for relevant enum definitions. Average price can be found by doing `Z` divided by `z`.

**Payload:**

```javascript
{
  "e": "executionReport",        // Event type
  "E": 1499405658658,            // Event time
  "s": "ETHBTC",                 // Symbol
  "c": 1000087761,               // Client order ID
  "S": "BUY",                    // Side
  "o": "LIMIT",                  // Order type
  "f": "GTC",                    // Time in force
  "q": "1.00000000",             // Order quantity
  "p": "0.10264410",             // Order price
  // "P": "0.00000000",             // Stop price
  // "F": "0.00000000",             // Iceberg quantity
  // "g": -1,                       // Ignore
  // "x": "NEW",                    // Current execution type
  "X": "NEW",                    // Current order status
  // "r": "NONE",                   // Order reject reason; will be an error code.
  "i": 4293153,                  // Order ID
  "l": "0.00000000",             // Last executed quantity
  "z": "0.00000000",             // Cumulative filled quantity
  "L": "0.00000000",             // Last executed price
  "n": "0",                      // Commission amount
  "N": null,                     // Commission asset
  "u": true,                     // Is the trade normal, ignore for now
  // "T": 1499405658657,            // Transaction time
  // "t": -1,                       // Trade ID
  // "I": 8641984,                  // Ignore
  "w": true,                     // Is the order working? Stops will have
  "m": false,                    // Is this trade the maker side?
  // "M": false,                    // Ignore
  "O": 1499405658657,            // Order creation time
  "Z": "0.00000000"              // Cumulative quote asset transacted quantity
}
```

**Execution types:**

* NEW
* PARTIALLY\_FILLED
* FILLED
* CANCELED
* REJECTED


# Web Socket Streams (2019-08-12)

## General WSS information

* The base endpoint is [here](https://github.com/Galactic-Tech/GitBook/blob/main/Spot/endpoint.md)
* Raw streams are accessed at **/openapi/quote/ws/v1**

| name     | values                                        |
| -------- | --------------------------------------------- |
| topic    | realtimes, trade, kline\_$interval, depth     |
| event    | sub, cancel, cancel\_all                      |
| interval | 1m, 5m, 15m, 30m, 1h, 2h, 6h, 12h, 1d, 1w, 1M |

**Sample Subscription Data:**

```javascript
{
  "symbol" : "$symbol0, $symbol1",
  "topic" : "$topic",
  "event" : "sub",
  // customizable parameter
  "params" : {
      // kline max limit is 2000, default is 1
      "limit" : "$limit",
      // Whether data is returned in binary format, default to false
      "binary" : "false"
  }
}
```

| name   | Explanation                                                                 |
| ------ | --------------------------------------------------------------------------- |
| limit  | Specify number of entries returned                                          |
| binary | Whether returned values is in binary format. **DEFAULT** value is **false** |

## Heartbeat

The client need to send a `PING` message to the server regularly through the Websocket, which then the server replies with `PONG`. If the client does not send the message every 5 minutes, the server will close the connection.

* Request

```javascript
{
    "ping": 1535975085052
}
```

* Response

```javascript
{
    "pong": 1535975085052
}
```

### Trade Streams

The Trade Streams push raw trade information; each trade has a unique buyer and seller.

After successful handshake and connected to server, the server will return the latest 60 trades. After this payload, the following will be real-time trades.

Variable "v" acts as an tradeId. This variable is shared across different symbols; however, each ID is unique. For example, suppose in the last 5 seconds 3 trades happened in ETHSUDT, BTCUSDT, and BHTBTC. Their version (which is "v") will be consecutive: 112, 113, 114.

**Subscription message structure:**

```javascript
{
  "symbol": "$symbol0, $symbol1",
  "topic": "trade",
  "event": "sub",
  "params": {
    "binary": false // Whether data returned is in binary format
  }
}
```

**Payload:**

```javascript
{
  "symbol": "BTCUSDT",
  "topic": "trade",
  "data": [{
    "v": "426635153180475392", // Version
    "t": 1565594873508,  //Timestamp
    "p": "11369", // Price
    "q": "0.01", // Quantity
    "m": false // true = buy, false = sell
  }, {
    "v": "426635153373413376",
    "t": 1565594873531,
    "p": "11369",
    "q": "0.0012",
    "m": false
  }],
  "f": false // Whether this is the first entry
}
```

### Market Tickers Stream

24hr Ticker statistics for a symbol that changed in an array.

**Subscription message structure:**

```javascript
{
  "symbol": "$symbol0, $symbol1",
  "topic": "realtimes",
  "event": "sub",
  "params": {
    "binary": false
  }
}
```

**Payload:**

```javascript
{
  "symbol": "ETHUSDT",
  "topic": "realtimes",
  "data": [{
    "t": "1565592599015", //time
    "s": "ETHUSDT", //symbol
    "c": "212.63", //close
    "h": "216.96", //high
    "l": "206.78", //low
    "o": "210.23", //open
    "v": "73013.575", //volume
    "qv": "15726612.498168", //trade amount (in base asset, in this case is USDT)
    }],
  "f": false // Whether this is the first entry
}
```

### Kline/Candlestick Streams

The Kline/Candlestick Stream push updates to the current klines/candlestick every second.

**Kline/Candlestick chart intervals:**

m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

* 1m
* 5m
* 15m
* 30m
* 1h
* 2h
* 4h
* 6h
* 12h
* 1d
* 1w
* 1M

**Subscription message structure:**

```javascript
{
  "symbol": "$symbol0, $symbol1",
  "topic": "kline_"+$interval,
  "event": "sub",
  "params": {
    "binary": false
  }
}
```

**Payload:**

```javascript
{
  "symbol": "BTCUSDT",
  "topic": "kline",
  "params": {"klineType": "15m"},
  "data": [{
    "t": 1565595900000, //kline start time
    "s": "BTCUSDT", // symbol
    "c": "11436.14", //close
    "h": "11437", //high
    "l": "11381.89", //low
    "o": "11381.89", //open
    "v": "16.3306" //volume
  }],
  "f": true// Whether this is the first entry
}
```

### Orderbook Depth Stream

The Depth Streams for symbols.

Here is the book dump instructions：

* The book dump frequency：Every 300ms, if book version changed.
* The book dump depth：300 for asks and bids each.
* The book version change event：
  * order enters book
  * order leaves book
  * order quantity or amount changes
  * order is finished

#### Merged Depth Stream

```javascript
{
  "symbol": "$symbol0, $symbol1",
  "topic": "depth",
  "event": "sub",
  "params": {
    "binary": false
    }
}
```

**Payload:**

```javascript
{
  "symbol": "BTCUSDT",
  "topic": "depth",
  "data": [{
    "s": "BTCUSDT", //Symbol
    "t": 1565600357643, //Timestamp
    "v": "112801745_18", //Version
    "b": [ //Bids
      ["11371.49", "0.0014"], //[Price, Quantity]
      ["11371.12", "0.2"],
      ["11369.97", "0.3523"],
      ["11369.96", "0.5"],
      ["11369.95", "0.0934"],
      ["11369.94", "1.6809"],
      ["11369.6", "0.0047"],
      ["11369.17", "0.3"],
      ["11369.16", "0.2"],
      ["11369.04", "1.3203"],
    "a": [//Asks
      ["11375.41", "0.0053"], //[Price, Quantity]
      ["11375.42", "0.0043"],
      ["11375.48", "0.0052"],
      ["11375.58", "0.0541"],
      ["11375.7", "0.0386"],
      ["11375.71", "2"],
      ["11377", "2.0691"],
      ["11377.01", "0.0167"],
      ["11377.12", "1.5"],
      ["11377.61", "0.3"]
    ]
  }],
  "f": true// Whether this is the first entry
}
```

#### Diff. Depth Stream

```javascript
{
  "symbol": "$symbol0, $symbol1",
  "topic": "diffDepth",
  "event": "sub",
  "params": {
    "binary": false
  }
}
```

Order book price and quantity depth updates used to locally manage an order book pushed every second.

In the Diff. (difference) depth stream, the quantity doesn"t necessarily mean the corresponding quantity to the price anymore. If the quantity is 0, it means this previous price level is not in the orderbook anymore. If the quantity is > 0, it means the updated quantity for this price level.

Suppose now we have received the first depth data payload:

```javascript
["0.00181860", "155.92000000"]// price, quantity
```

If the next payload is:

```javascript
["0.00181860", "12.3"]
```

This means that this price level"s quantity has changed.

If the next payload is:

```javascript
["0.00181860", "0"]
```

This means that this price level is not in orderbook anymore.

**Payload:**

```javascript
{
  "symbol": "BTCUSDT",
  "topic": "diffDepth",
  "data": [{
    "e": 0,
    "t": 1565687625534,
    "v": "115277986_18",
    "b": [
      ["11316.78", "0.078"],
      ["11313.16", "0.0052"],
      ["11312.12", "0"],
      ["11309.75", "0.0067"],
      ["11309.58", "0"],
      ["11306.14", "0.0073"]
    ],
    "a": [
      ["11318.96", "0.0041"],
      ["11318.99", "0.0017"],
      ["11319.12", "0.0017"],
      ["11319.22", "0.4516"],
      ["11319.23", "0.0934"],
      ["11319.24", "3.0665"]
    ]
  }],
  "f": false //Whether this is the first entry
}
```

### Index Data Stream

This stream is for index prices gathered for options and futures.

**Subscription message structure:**

```javascript
{
  "symbol": "$symbol0, $symbol1",
  "topic": "index",
  "event": "sub",
}
```

**Payload:**

```javascript
{
  "symbol": "HTUSDT",  
  "topic": "index",
  "data": [{
    "symbol": "HTUSDT",
    "index": "5.0941",
    "edp": "5.08799333",
    "formula": "(5.0941[HUOBI])/1"
  }],
  "f": true// Whether this is the first entry
}
```

## Error handling

**Error Codes:**

```java
INVALID_REQUEST("-10000", "Invalid request!")
JSON_FORMAT_ERROR("-10001", "Invalid JSON!")
INVALID_EVENT("-10002", "Invalid event")
REQUIRED_EVENT("-10003", "Event required!")
INVALID_TOPIC("-10004", "Invalid topic!")
REQUIRED_TOPIC("-10005", "Topic required!")
PARAM_EMPTY("-10007", "Params required!")
PERIOD_EMPTY("-10008", "Period required!")
PERIOD_ERROR("-10009", "Invalid period!")
SYMBOLS_ERROR("-100010", "Invalid Symbols!")
```


# Contract


# Contract API

## Base Info

### The base url

| Name             | base endpoint                                  |
| ---------------- | ---------------------------------------------- |
| market-api       | `https://api-futures.trubit.com/market/api/v1` |
| trade-api        | `https://api-futures.trubit.com/trade/api/v1`  |
| market-websocket | `wss://api-futures.trubit.com/ws/market`       |
| trade-websocket  | `wss://api-futures.trubit.com/ws/trade`        |

### Time zone

The time zone for all times is UTC+0

### WebSocket Overview

WebSocket is a new protocol for HTML5, which enables full-duplex communication between the client and the server, allowing data to travel in both directions quickly. The client and server connections can be established through a simple handshake, and the server can actively push information to the client according to the business rules. The advantages are as follows:

* When the client and the server perform data transmission, the request header information is relatively small, about 2 bytes.
* Both the client and the server can actively send data to the other party.
* There is no need to create TCP requests and destroy multiple times, saving bandwidth and server resources.

## Market Endpoint

### `Contract info` <a href="#contractinfo" id="contractinfo"></a>

Exchange trading rules and symbol information

#### **Limit:**

Speed limit: 1 times/second, Speed limit rule: IP

#### **Request Url:**

```bash
GET /basic/refData
```

#### **Parameters：**

| Name         | Type         | Required     | Default      | Description |
| ------------ | ------------ | ------------ | ------------ | ----------- |
| ------------ | ------------ | ------------ | ------------ | ----        |

#### **Response:**

| Name      | Type   | Example   | Description                                |
| --------- | ------ | --------- | ------------------------------------------ |
| `symbol`  | string | `XRPUSDT` | Contract name                              |
| `lotSize` | float  | `1.0`     | Defines the minimum quantity allowed       |
| `tick`    | float  | `0.00001` | Minimal price value                        |
| `type`    | string | `USDT`    | Contract type, PERP => Perpetual Contract. |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": [
    {
      "lotSize": 1.0,
      "symbol": "MASKUSDT",
      "tick": 0.001,
      "type": "PERP"
    }
  ]
}
```

### `Klines` <a href="#klines" id="klines"></a>

Obtain K line by from and step

#### **Limit:**

Speed limit: 15 times/1min, Speed limit rule: IP

#### **Request URL:**

```
GET /kLine/byFrom
```

#### **Parameters：**

| Name     | Type    | Required | Default | Description                                                                                                   |
| -------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------- |
| `symbol` | string  | `YES`    | `--`    | The contract symbol                                                                                           |
| `type`   | string  | `YES`    | `--`    | Interval of the kline. Identifiable values: 1M, 3M, 5M, 10M, 15M, 30M, 1H, 2H, 4H, 6H, 8H, 12H, D, 3D, W, MTH |
| `from`   | integer | `NO`     | `0`     | Start from of K line, 0 means from the latest one                                                             |
| `step`   | integer | `NO`     | `--`    | The number of K line, equal or less than 1500                                                                 |

#### **Response:**

| Name  | Type   | Example      | Description                          |
| ----- | ------ | ------------ | ------------------------------------ |
| `[0]` | string | `26435.5`    | Close Price                          |
| `[1]` | string | `26435.5`    | High Price                           |
| `[2]` | string | `1686905040` | \*1000 timestamp(ms)                 |
| `[3]` | string | `26435.5`    | Low Price                            |
| `[4]` | string | `26435.5`    | Open Price                           |
| `[6]` | string | `7.08`       | Volume eg:BTCUSDT The unit is BTC    |
| `[7]` | string | `181074.0`   | Turnover eg:BTCUSDT The unit is USDT |

#### **Example:**

```json
{
    "code": 0,
        "message": "OK",
        "result": [
        [
            "25559.4",
            "25559.7",
            "1686905040",
            "25553.2",
            "25554.1",
            "1",
            "7.08",
            "181074.0"
        ]
    ]
}
```

### `Klines By Time` <a href="#klinesbytime" id="klinesbytime"></a>

Obtain K line by time and step

#### **Limit:**

Speed limit: 15 times/1min, Speed limit rule: IP

#### **Request URL:**

```
GET /kLine/byTime
```

#### **Parameters：**

| Name     | Type    | Required | Default             | Description                                                                                                   |
| -------- | ------- | -------- | ------------------- | ------------------------------------------------------------------------------------------------------------- |
| `symbol` | string  | `YES`    | `--`                | The contract symbol                                                                                           |
| `type`   | string  | `YES`    | `--`                | Interval of the kline. Identifiable values: 1M, 3M, 5M, 10M, 15M, 30M, 1H, 2H, 4H, 6H, 8H, 12H, D, 3D, W, MTH |
| `from`   | integer | `NO`     | `currentTimeMillis` | Milli seconds of K line keyTime, query from the latest one if not provided                                    |
| `step`   | integer | `YES`    | `--`                | The number of K line, equal or less than 1500                                                                 |

#### **Response:**

| Name  | Type   | Example      | Description                          |
| ----- | ------ | ------------ | ------------------------------------ |
| `[0]` | string | `26435.5`    | Close Price                          |
| `[1]` | string | `26435.5`    | High Price                           |
| `[2]` | string | `1686905040` | \*1000 timestamp(ms)                 |
| `[3]` | string | `26435.5`    | Low Price                            |
| `[4]` | string | `26435.5`    | Open Price                           |
| `[6]` | string | `7.08`       | Volume eg:BTCUSDT The unit is BTC    |
| `[7]` | string | `181074.0`   | Turnover eg:BTCUSDT The unit is USDT |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": [
        [
            "25559.4",
            "25559.7",
            "1686905040",
            "25553.2",
            "25554.1",
            "1",
            "7.08",
            "181074.0"
        ]
    ]
}
```

### `Index` <a href="#index" id="index"></a>

Index price of underlying asset

#### **Limit:**

Speed limit: 10 times/second, Speed limit rule: IP

#### **Request Url:**

```bash
GET /basic/indexPrice
```

#### **Parameters：**

| Name    | Type   | Required | Default | Description                                                                 |
| ------- | ------ | -------- | ------- | --------------------------------------------------------------------------- |
| symbols | string | `NO`     | `--`    | The contract symbol, multiple symbols separated by ',', eg: BTCUSDT,ETHUSDT |

#### **Response:**

| Name     | Type   | Example         | Description                       |
| -------- | ------ | --------------- | --------------------------------- |
| `symbol` | string | `BTCUSDT`       | The contract symbol               |
| `price`  | float  | `8342.73`       | The index price of the underlying |
| `time`   | long   | `1686196441142` | The time of the underlying        |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": [
        {
            "symbol": "BTCUSDT",
            "price": 26442.32666666667,
            "time": 1686209050099
        }
    ]
}
```

### `Last Price` <a href="#lastprice" id="lastprice"></a>

Query last price of instrument(s)

#### **Limit:**

Speed limit: 1 times/second, Speed limit rule: IP

#### **Request Url:**

```bash
GET /basic/lastPrice
```

#### **Parameters：**

| Name    | Type   | Required | Default | Description                                                                 |
| ------- | ------ | -------- | ------- | --------------------------------------------------------------------------- |
| symbols | string | `NO`     | `--`    | The contract symbol, multiple symbols separated by ',', eg: BTCUSDT,ETHUSDT |

#### **Response:**

| Name     | Type   | Example         | Description         |
| -------- | ------ | --------------- | ------------------- |
| `symbol` | string | `BTCUSDT`       | The contract symbol |
| `price`  | float  | `8342.73`       | The last price      |
| `time`   | long   | `1686196441142` | The time            |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": [
        {
            "price": 26627.7,
            "symbol": "BTCUSDT",
            "time": 1686304783617
        }
    ]
}
```

### `Mark Price` <a href="#markprice" id="markprice"></a>

Query mark price of instrument(s)

#### **Limit:**

Speed limit: 10 times/second, Speed limit rule: IP

#### **Request Url:**

```bash
GET /basic/markPrice
```

#### **Parameters：**

| Name    | Type   | Required | Default | Description                                                                 |
| ------- | ------ | -------- | ------- | --------------------------------------------------------------------------- |
| symbols | string | `NO`     | \`\`    | The contract symbol, multiple symbols separated by ',', eg: BTCUSDT,ETHUSDT |

#### **Response:**

| Name     | Type   | Example         | Description         |
| -------- | ------ | --------------- | ------------------- |
| `symbol` | string | `BTCUSDT`       | The contract symbol |
| `price`  | float  | `8342.73`       | The mark price      |
| `time`   | long   | `1686196441142` | The time            |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": [
        {
            "price": 26627.7,
            "symbol": "BTCUSDT",
            "time": 1686304783617
        }
    ]
}
```

### `Funding Rate` <a href="#fundingrate" id="fundingrate"></a>

Obtain funding rate of instrument

#### **Limit:**

Speed limit: 5 times/second, Speed limit rule: IP

#### **Request Url:**

```bash
GET /kLine/fundingRate
```

#### **Parameters：**

| Name    | Type   | Required | Default                                                                     | Description |
| ------- | ------ | -------- | --------------------------------------------------------------------------- | ----------- |
| symbols | string | `NO`     | The contract symbol, multiple symbols separated by ',', eg: BTCUSDT,ETHUSDT |             |

#### **Response:**

| Name     | Type   | Example                         | Description         |
| -------- | ------ | ------------------------------- | ------------------- |
| `symbol` | string | `BTCUSDT`                       | The contract symbol |
| `rate`   | double | `0.0001`                        | Funding rate        |
| `date`   | string | `2023-06-08T07:00:00.000+00:00` | Time                |
| `time`   | long   | `1686196441142`                 | Timestamp           |

#### **Example:**

```json
{
    "code": 0,
        "message": "OK",
        "result": [
        {
            "symbol": "BTCUSDT",
            "rate": 0.0001,
            "date": "2023-06-08T08:00:00.000+00:00",
            "timestamp": 1686207600020
        }
    ]
}
```

### `Depth` <a href="#depth" id="depth"></a>

Query market depth Snapshot & trades of instrument

#### **Limit:**

Speed limit: 10 times/second, Speed limit rule: IP

#### **Request Url:**

```
GET /depth/list
```

#### **Parameters:**

| Name     | Type    | Required | Default | Description                                               |
| -------- | ------- | -------- | ------- | --------------------------------------------------------- |
| `symbol` | string  | `YES`    | `--`    | The contract symbol to be retrieved                       |
| `level`  | integer | `NO`     | `20`    | The number(5/10/20) of entries returned for bids and asks |

#### **Response:**

| Name       | Type   | Example | Description                  |
| ---------- | ------ | ------- | ---------------------------- |
| `price`    | double | 26418.5 | Price                        |
| `qty`      | double | 18873.0 | Positive integer, 1Qty=1USDT |
| `count`    | int    | 1       | Order count                  |
| `iceCount` | int    | 1       | Ice Count                    |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": {
        "buyDepth": [
            {
                "price": 26418.5,
                "qty": 50056.0,
                "count": 6,
                "iceCount": 0
            },
            {
                "price": 26418.4,
                "qty": 80489.0,
                "count": 6,
                "iceCount": 0
            },
            {
                "price": 26418.1,
                "qty": 58500.0,
                "count": 4,
                "iceCount": 0
            }
        ],
            "sellDepth": [
            {
                "price": 26418.8,
                "qty": 7797.0,
                "count": 2,
                "iceCount": 0
            },
            {
                "price": 26418.9,
                "qty": 9891.0,
                "count": 2,
                "iceCount": 0
            },
            {
                "price": 26419.0,
                "qty": 17483.0,
                "count": 5,
                "iceCount": 0
            },
            {
                "price": 26419.1,
                "qty": 19006.0,
                "count": 6,
                "iceCount": 0
            },
            {
                "price": 26419.2,
                "qty": 17266.0,
                "count": 6,
                "iceCount": 0
            }
        ],
            "trades": null
    }
}
```

### `trades` <a href="#trades" id="trades"></a>

Retrieve the latest trades that have occurred for a specific contract.

#### **Limit:**

Speed limit: 10 times/second, Speed limit rule: IP

#### **Request URL:**

```
GET /depth/trades
```

#### **Parameters：**

| Parameter  | type   | required | default | description                                                     |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------- |
| `symbol`   | string | `YES`    | `--`    | The contract symbol                                             |
| `sequence` | string | `NO`     | `--`    | Sequence of last trade id, retrieve all trades if value is null |

#### **Response:**

| Name        | Type    | Example               | Description                                                          |
| ----------- | ------- | --------------------- | -------------------------------------------------------------------- |
| `id`        | string  | `1686213904404000035` | Trade id                                                             |
| `symbol`    | string  | `BTCUSDT`             | The contract symbol                                                  |
| `price`     | double  | `1295.0`              | Price                                                                |
| `qty`       | double  | `1295.0`              | The quantity traded                                                  |
| `buyActive` | boolean | `true`                | True is the buyer's active order, false is the seller's active order |
| `tms`       | long    | `1537797044116`       | timestamp (ms)                                                       |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": [
        {
            "id": "1686213904404000035",
            "symbol": "BTCUSDT",
            "price": 26428.9,
            "qty": 1295.0,
            "buyActive": false,
            "timestamp": "2023-06-08T08:45:04.404+00:00",
            "tms": "1686213904404"
        },
        {
            "id": "1686213899234000003",
            "symbol": "BTCUSDT",
            "price": 26438.2,
            "qty": 2000.0,
            "buyActive": false,
            "timestamp": "2023-06-08T08:44:59.234+00:00",
            "tms": "1686213899234"
        },
        {
            "id": "1686213884863000003",
            "symbol": "BTCUSDT",
            "price": 26433.3,
            "qty": 9100.0,
            "buyActive": true,
            "timestamp": "2023-06-08T08:44:44.863+00:00",
            "tms": "1686213884863"
        }
    ]
}
```

### `Trade Statistics in latest 24 hours` <a href="#tradestatisticsinlatest24hours" id="tradestatisticsinlatest24hours"></a>

Trade Statistics in latest 24 hours

#### **Limit:**

Speed limit: 10 times/second, Speed limit rule: IP

#### **Request URL:**

```
GET /kLine/tradeStatistics
```

#### **Parameters：**

| Name      | Type   | Required | Default | Description                                                                 |
| --------- | ------ | -------- | ------- | --------------------------------------------------------------------------- |
| `symbols` | string | `YES`    | `--`    | The contract symbol, multiple symbols separated by ',', eg: BTCUSDT,ETHUSDT |

#### **Response:**

| Name                 | Type   | Example                 | Description                 |
| -------------------- | ------ | ----------------------- | --------------------------- |
| `'symbol'`           | string | `BTCUSDT`               | The contract symbol         |
| `'lastPrice'`        | double | `BTCUSDT`               | The contract symbol         |
| `'maxPrice'`         | double | `26420.9`               | Max price                   |
| `'minPrice'`         | double | `25713.4`               | Min price                   |
| `'priceChange'`      | double | `-142.0`                | Price change                |
| `'priceChangeRatio'` | double | `-0.005437842019200944` | Price change ratio          |
| `'volume'`           | double | `6.5697459E7`           | eg:BTCUSDT The unit is BTC  |
| `'turnover'`         | double | `2483.5865212475437`    | eg:BTCUSDT The unit is USDT |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": [
        {
            "lastPrice": 25971.3,
            "maxPrice": 26420.9,
            "minPrice": 25713.4,
            "priceChange": -142.0,
            "priceChangeRatio": -0.005437842019200944,
            "symbol": "BTCUSDT",
            "turnover": 16171.504782381482,
            "volume": 4.19809141E8
        }
    ]
}
```

### `Open Position In Exchange` <a href="#openpositioninexchange" id="openpositioninexchange"></a>

Total Open Position In Exchange

#### **Limit:**

Speed limit: 5 times/second, Speed limit rule: IP

#### **Request URL:**

```
GET /kLine/openInterest
```

#### **Parameters：**

| Name     | Type   | Required | Default | Description         |
| -------- | ------ | -------- | ------- | ------------------- |
| `symbol` | string | `YES`    | `--`    | The contract symbol |

#### **Response:**

| Name       | Type   | Example                         | Description                 |
| ---------- | ------ | ------------------------------- | --------------------------- |
| `'symbol'` | string | `BTCUSDT`                       | The contract symbol         |
| `'date'`   | double | `2023-06-19T02:37:53.617+00:00` | Time                        |
| `'qty'`    | double | `1084388.0`                     | eg:BTCUSDT The unit is USDT |
| `'value'`  | double | `41.035743951380205`            | eg:BTCUSDT The unit is BTC  |

#### **Example:**

```js
{
    "code": 0,
        "message": "OK",
        "result": {
        "symbol": "BTCUSDT",
            "value": 41.035743951380205,
            "date": "2023-06-19T02:37:53.617+00:00",
            "qty": 1084388.0
    }
}
```

## Public Websocket Endpoints

### Receiving data requires an event subscription

### `Kline` <a href="#klinews" id="klinews"></a>

#### **Parameters:**

| Name      | Type   | Required | Default | Description                                                       |
| --------- | ------ | -------- | ------- | ----------------------------------------------------------------- |
| `op`      | string | `YES`    | `--`    | subscribe/unsubscribe                                             |
| `key`     | string | `YES`    | `--`    | The contract symbol                                               |
| `type`    | string | `YES`    | `--`    | 1M, 3M, 5M, 10M, 15M, 30M, 1H, 2H, 4H, 6H, 8H, 12H, D, 3D, W, MTH |
| `channel` | string | `YES`    | `--`    | Channel                                                           |

#### **Example:**

```json
{
  "op": "subscribe",
  "key": "BTCUSDT",
  "type": "1M",
  "channel": "kLine"
}
```

#### **Response:**

| Name  | Type   | Example      | Description                          |
| ----- | ------ | ------------ | ------------------------------------ |
| `[0]` | string | `26435.5`    | Close Price                          |
| `[1]` | string | `26435.5`    | High Price                           |
| `[2]` | string | `1686905040` | \*1000 timestamp(ms)                 |
| `[3]` | string | `26435.5`    | Low Price                            |
| `[4]` | string | `26435.5`    | Open Price                           |
| `[6]` | string | `7.08`       | Volume eg:BTCUSDT The unit is BTC    |
| `[7]` | string | `181074.0`   | Turnover eg:BTCUSDT The unit is USDT |

#### **Example:**

```js
{
    "hisPrice": [
    "25557.4",
    "25557.7",
    "1686905100",
    "25557.4",
    "25557.5",
    "1",
    "0.69",
    "17681.0"
],
    "isNew": false,
    "key": "MEXO_BTCUSDT_1M"
}
```

### `Depth` <a href="#depthws" id="depthws"></a>

#### **Parameters:**

| Name                     | Type         | Required     | Default                      | Description           |
| ------------------------ | ------------ | ------------ | ---------------------------- | --------------------- |
| `op`                     | string       | `YES`        | `--`                         | subscribe/unsubscribe |
| `key`                    | string       | `YES`        | `--`                         | The contract symbol   |
| `channel`                | string       | `YES`        | `--`                         | Channel               |
| ### **Example:**         |              |              |                              |                       |
| \`\`\`json               |              |              |                              |                       |
| {                        |              |              |                              |                       |
| "op": "subscribe",       |              |              |                              |                       |
| "key": "BTCUSDT",        |              |              |                              |                       |
| "channel": "depthUpdate" |              |              |                              |                       |
| }                        |              |              |                              |                       |
| \`\`\`                   |              |              |                              |                       |
| ### **Response:**        |              |              |                              |                       |
| Name                     | Type         | Example      | Description                  |                       |
| ------------             | ------------ | ------------ | ------------                 |                       |
| `price`                  | double       | 26418.5      | Price                        |                       |
| `qty`                    | double       | 18873.0      | Positive integer, 1Qty=1USDT |                       |
| `count`                  | int          | 1            | Order count                  |                       |
| `iceCount`               | int          | 1            | Ice Count                    |                       |

#### **Example:**

```json
{
  "buyDepth": [
    {
      "price": 25916.1,
      "qty": 26144.0,
      "count": 4,
      "iceCount": 0
    },
    {
      "price": 25915.9,
      "qty": 82419.0,
      "count": 7,
      "iceCount": 0
    }
  ],
  "sellDepth": [
    {
      "price": 25916.4,
      "qty": 6233.0,
      "count": 2,
      "iceCount": 0
    },
    {
      "price": 25917.3,
      "qty": 33746.0,
      "count": 5,
      "iceCount": 0
    }
  ],
  "trades": [
    {
      "id": "1686733223325000025",
      "symbol": "BTCUSDT",
      "price": 25916.4,
      "qty": 3648.0,
      "buyActive": true,
      "timestamp": "Jun 14, 2023 09:00:23 AM",
      "tms": "1686733223325"
    },
    {
      "id": "1686733223325000023",
      "symbol": "BTCUSDT",
      "price": 25916.4,
      "qty": 4289.0,
      "buyActive": true,
      "timestamp": "Jun 14, 2023 09:00:23 AM",
      "tms": "1686733223325"
    }

  ],
  "key": "BTCUSDT"
}
```

### `Trade Statistics` <a href="#tradestatistics" id="tradestatistics"></a>

#### **Parameters:**

| Name      | Type   | Required | Default | Description           |
| --------- | ------ | -------- | ------- | --------------------- |
| `op`      | string | `YES`    | `--`    | subscribe/unsubscribe |
| `key`     | string | `YES`    | `--`    | The contract symbol   |
| `channel` | string | `YES`    | `--`    | Channel               |

#### **Example:**

```json
{
  "op": "subscribe",
  "key": "BTCUSDT",
  "channel": "tradeStatistics"
}
```

#### **Response:**

| Name                 | Type   | Example                 | Description                 |
| -------------------- | ------ | ----------------------- | --------------------------- |
| `'symbol'`           | string | `BTCUSDT`               | The contract symbol         |
| `'lastPrice'`        | double | `BTCUSDT`               | The contract symbol         |
| `'maxPrice'`         | double | `26420.9`               | Max price                   |
| `'minPrice'`         | double | `25713.4`               | Min price                   |
| `'priceChange'`      | double | `-142.0`                | Price change                |
| `'priceChangeRatio'` | double | `-0.005437842019200944` | Price change ratio          |
| `'volume'`           | double | `6.5697459E7`           | eg:BTCUSDT The unit is BTC  |
| `'turnover'`         | double | `2483.5865212475437`    | eg:BTCUSDT The unit is USDT |

#### **Example:**

```json
{
  "tradeStatistics": {
    "symbol": "BTCUSDT",
    "maxPrice": 26081.8,
    "minPrice": 24800.2,
    "priceChange": -919.1000000000022,
    "priceChangeRatio": -0.03533002494743365,
    "volume": 4.55661746E8,
    "turnover": 17834.7449180242,
    "lastPrice": 25095.6
  },
  "key": "BTCUSDT"
}
```

### `Open Interest` <a href="#openinterest" id="openinterest"></a>

Total Open Position In Exchange

#### **Parameters:**

| Name      | Type   | Required | Default | Description           |
| --------- | ------ | -------- | ------- | --------------------- |
| `op`      | string | `YES`    | `--`    | subscribe/unsubscribe |
| `key`     | string | `YES`    | `--`    | The contract symbol   |
| `channel` | string | `YES`    | `--`    | Channel               |

#### **Example:**

```json
{
  "op": "subscribe",
  "key": "BTCUSDT",
  "channel": "openInterest"
}
```

#### **Response:**

| Name      | Type   | Example                         | Description                 |
| --------- | ------ | ------------------------------- | --------------------------- |
| `'key'`   | string | `BTCUSDT`                       | The contract symbol         |
| `'date'`  | double | `2023-06-19T02:37:53.617+00:00` | Time                        |
| `'qty'`   | double | `1084388.0`                     | eg:BTCUSDT The unit is USDT |
| `'value'` | double | `41.035743951380205`            | eg:BTCUSDT The unit is BTC  |

#### **Example:**

```json
{
  "key": "BTCUSDT",
  "event": "openInterest",
  "value": 45.36721464659362,
  "date": "Jun 19, 2023 03:06:10 AM",
  "qty": 1199212.0
}
```

## Trade Http Endpoints

Trade Endpoints Check signature. Check parameters are passed in header

| Name        | Type   | Required | Default | Description                                                                                            |
| ----------- | ------ | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| `apiKey`    | string | `YES`    | `--`    | Apply at the individual center, apikey/apiSecret                                                       |
| `expires`   | long   | `YES`    | `--`    | Expiration milliseconds, usually set to the current time plus 10 seconds                               |
| `signature` | string | `YES`    | `--`    | signature=sha256(apiSecret+method+path+expires)Note: The + needs to be removed to generate a signature |
| ## `Order`  |        |          |         |                                                                                                        |

Place order for a contract. This API endpoint requires your signed request.

#### **Request Weight:**

Speed limit: 20 times/second Speed limit rule: apiKey

#### **Request URL:**

```bash
POST /trade/enterOrder
```

#### **Parameters：**

| Name            | Type    | Required                                | Default            | Description                                                                                                                           |
| --------------- | ------- | --------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `symbol`        | string  | `YES`                                   | `--`               | The contract symbol, eg: BTCUSDT                                                                                                      |
| `side`          | string  | `YES`                                   | `--`               | Direction of the order. Direction type: `Buy`, `Sell`                                                                                 |
| `orderType`     | string  | `YES`                                   | `--`               | The order type, includes: `Limit`, `Market`                                                                                           |
| `currency`      | string  | `YES`                                   | `--`               | Currency of account, eg: BTC, ETH, USDT                                                                                               |
| `qty`           | double  | `YES`                                   | `0`                | The number of contracts to buy, Positive integer, 1Qty=1USDT                                                                          |
| `openPosition`  | boolean | `YES`                                   | `true`             | Open position or Close position order, eg: true or false                                                                              |
| `positionId`    | string  | `NO`                                    | `--`               | The position ID,In the split-warehouse mode, closing a position requires, eg: 1323056886107491328-CCF-USDT-XRPUSDT-Long               |
| `price`         | double  | `NO`. **REQUIRED** for (`Limit`) orders | `--`               | Order price                                                                                                                           |
| `triggerPrice`  | double  | `NO`                                    | `--`               | Trigger price for conditional order                                                                                                   |
| `trailingStop`  | double  | `NO`                                    | `--`               | Trailing stop value for advanced order, conflict with stopLossPrice                                                                   |
| `stopLossPrice` | double  | `NO`                                    | `--`               | Stop loss price for advanced order, conflict with trailingStop                                                                        |
| `stopWinPrice`  | double  | `NO`                                    | `--`               | Stop win price for advanced order                                                                                                     |
| `tif`           | string  | `NO`                                    | `GOOD_TILL_CANCEL` | Type of advanced order, Available values : FILL\_OR\_KILL, GOOD\_TILL\_CANCEL, IMMEDIATE\_OR\_CANCEL, QUEUE\_OR\_CANCEL               |
| `triggerType`   | string  | `NO`                                    | `--`               | Trigger type of price for conditional order, eg: LAST or INDEX, it will be LAST if not providedAvailable values : INDEX, LAST, MARK   |
| `stopWinType`   | string  | `NO`                                    | `--`               | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market |
| `clientOrderId` | string  | `NO`                                    | `--`               | An unique ID for the order (user defined), Must satisfy regular: ^\[\\.A-Z\\:/a-z0-9\_-]{1,36}$"                                      |

**NOTE** For **Market Orders**, you need to set `orderType` as **`Market`**.

You can get contract price and quantity precision configuration data in the `exchange` endpoint.

Note: if your balance does not meet the margin requirement (which is the minimum margin requirement + open position fee + close position fee), "*insufficient balance*" error message will be returned.

#### **Response:**

| Name            | Type   | Example                         | Description                                                                                                             |
| --------------- | ------ | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `created`       | long   | `1570759718825`                 | Timestamp when the order is created                                                                                     |
| `modified`      | long   | `1551062936784`                 | Timestamp when this order was updated last time                                                                         |
| `id`            | string | `O101-20230531-025722-174-1016` | The order ID                                                                                                            |
| `clientOrderId` | string | `213443`                        | An unique order ID which is defined by user                                                                             |
| `symbol`        | string | `BTC-PERP-REV`                  | The contract symbol                                                                                                     |
| `price`         | float  | `8200`                          | The order price                                                                                                         |
| `qty`           | float  | `1.01`                          | Order quantity                                                                                                          |
| `cumQty`        | float  | `1.01`                          | The number of orders that has been executed                                                                             |
| `avgPx`         | float  | `4754.24`                       | Average price of filled orders                                                                                          |
| `side`          | string | `--`                            | Direction of the order. Direction type: `Buy`, `Sell`                                                                   |
| `type`          | string | `--`                            | The order type, includes: `LIMIT`, `Market`                                                                             |
| `tif`           | string | `GTC`                           | Type of advanced order, Available values : FILL\_OR\_KILL, GOOD\_TILL\_CANCEL, IMMEDIATE\_OR\_CANCEL, QUEUE\_OR\_CANCEL |
| `fee`           | double | `--`                            | Fees incurred for this order.                                                                                           |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": {
    "ordStatus": "PENDING_NEW",
    "symbol": "BTCUSDT",
    "clientOrderId": "213443",
    "showQty": 0.0,
    "side": "Sell",
    "created": 1685699501000,
    "fee": 0.0,
    "cumQty": 0.0,
    "source": "Normal",
    "type": "Market",
    "pnl": 0.0,
    "tif": "GOOD_TILL_CANCEL",
    "openPosition": true,
    "uid": "1323056886107491328",
    "avgPx": 0.0,
    "price": 0.0,
    "qty": 100.0,
    "iceberg": false,
    "modified": 1685699501000,
    "currency": "BTC",
    "id": "O101-20230602-095141-711-1878"
  }
}
```

### `Query Order` <a href="#queryorder" id="queryorder"></a>

Request order by id

#### **Limit:**

Speed limit: 20 times/second, Speed limit rule: apiKey

#### **Request URL:**

```bash
GET /trade/queryOrderById
```

#### **Parameters：**

| Name            | Type   | Required                        | Default | Description                                 |
| --------------- | ------ | ------------------------------- | ------- | ------------------------------------------- |
| `orderId`       | string | `O101-20230531-025722-174-1016` | `NO`    | The order ID                                |
| `clientOrderId` | string | `O101-20230531-025722-174-1016` | `NO`    | An unique order ID which is defined by user |

**NOTE** orderId and clientOrderId must pick one of two

#### **Response:**

| Name            | Type    | Example                         | Description                                                                                                                                                        |
| --------------- | ------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`            | string  | `O101-20230531-025722-174-1016` | The order ID                                                                                                                                                       |
| `uid`           | string  | `1323056886107491328`           | The User ID                                                                                                                                                        |
| `symbol`        | string  | `BTCUSDT`                       | The contract symbol                                                                                                                                                |
| `created`       | long    | `1570759718825`                 | Timestamp when the order is created                                                                                                                                |
| `modified`      | long    | `1551062936784`                 | Timestamp when this order was updated last time                                                                                                                    |
| `clientOrderId` | string  | `213443`                        | An unique order ID which is defined by user                                                                                                                        |
| `side`          | string  | `--`                            | Direction of the order. Direction type: `Buy`, `Sell`                                                                                                              |
| `type`          | string  | `--`                            | The order type, includes: `LIMIT`, `Market`                                                                                                                        |
| `tif`           | string  | `GTC`                           | Type of advanced order, Available values : FILL\_OR\_KILL, GOOD\_TILL\_CANCEL, IMMEDIATE\_OR\_CANCEL, QUEUE\_OR\_CANCEL                                            |
| `currency`      | string  | `USDT`                          | Currency of account, eg: BTC, ETH, USDT                                                                                                                            |
| `price`         | double  | `8200`                          | The order price                                                                                                                                                    |
| `qty`           | double  | `11.0`                          | Order quantity                                                                                                                                                     |
| `openPosition`  | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `ordStatus`     | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `cumQty`        | double  | `11.0`                          | The number of orders that has been executed                                                                                                                        |
| `avgPx`         | double  | `4754.24`                       | Average price of filled orders                                                                                                                                     |
| `ordStatus`     | string  | `FILLED`                        | The order status, includes: `PENDING_NEW`, `NEW`, `PARTIALLY_FILLED`, `FILLED`, `PENDING_CANCEL`, `CANCELED`, `REJECTED`, `PENDING_REPLACE`, `REPLACED`, `WAITING` |
| `iceberg`       | boolean | `false`                         | The order is iceberg                                                                                                                                               |
| `showQty`       | double  | `1.0`                           | The order showQty                                                                                                                                                  |
| `pnl`           | double  | `1.1`                           | Pnl incurred for this order.                                                                                                                                       |
| `fee`           | double  | `1.1`                           | Fees incurred for this order.                                                                                                                                      |
| `triggerPrice`  | double  | `--`                            | Trigger price for conditional order                                                                                                                                |
| `triggerType`   | string  | `--`                            | Trigger type of price for conditional order, eg: LAST or INDEX, it will be LAST if not providedAvailable values : INDEX, LAST, MARK                                |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |
| `stopLossPrice` | double  | `--`                            | Stop loss price for advanced order, conflict with trailingStop                                                                                                     |
| `stopWinPrice`  | double  | `--`                            | Stop win price for advanced order                                                                                                                                  |
| `stopWinType`   | string  | `--`                            | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market                              |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": {
    "id": "O101-20230531-040439-546-1837",
    "uid": "1323056886107491328",
    "symbol": "BTCUSDT",
    "created": 1685505879000,
    "modified": 1685505879000,
    "side": "Buy",
    "type": "Market",
    "tif": "GOOD_TILL_CANCEL",
    "currency": "BTC",
    "price": 0.0,
    "qty": 100.0,
    "openPosition": false,
    "cumQty": 100.0,
    "avgPx": 27620.2,
    "ordStatus": "FILLED",
    "iceberg": false,
    "showQty": 0.0,
    "source": "Normal",
    "pnl": 1.3365529862569942E-6,
    "fee": -1.448215436528338E-6,
    "triggerPrice": null,
    "triggerType": null,
    "stopLossPrice": null,
    "stopWinType": null,
    "stopWinPrice": null,
    "trailingStop": null
  }
}
```

### `Query Order List` <a href="#queryorderlist" id="queryorderlist"></a>

Request order by time

#### **Limit:**

Speed limit: 10 times /1 minutes, Speed limit rule: apiKey, Response data limitation: 300

#### **Request URL:**

```bash
GET /trade/queryOrders
```

#### **Parameters：**

| Name             | Type | Required        | Default | Description                                                                   |
| ---------------- | ---- | --------------- | ------- | ----------------------------------------------------------------------------- |
| `prevTimeMillis` | long | `1685505879000` | `NO`    | The order created, Query the data from the prevTimeMillis to the current time |

#### **Response:**

| Name            | Type    | Example                         | Description                                                                                                                                                        |
| --------------- | ------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`            | string  | `O101-20230531-025722-174-1016` | The order ID                                                                                                                                                       |
| `uid`           | string  | `1323056886107491328`           | The User ID                                                                                                                                                        |
| `symbol`        | string  | `BTCUSDT`                       | The contract symbol                                                                                                                                                |
| `created`       | long    | `1570759718825`                 | Timestamp when the order is created                                                                                                                                |
| `modified`      | long    | `1551062936784`                 | Timestamp when this order was updated last time                                                                                                                    |
| `clientOrderId` | string  | `213443`                        | An unique order ID which is defined by user                                                                                                                        |
| `side`          | string  | `--`                            | Direction of the order. Direction type: `Buy`, `Sell`                                                                                                              |
| `type`          | string  | `--`                            | The order type, includes: `LIMIT`, `Market`                                                                                                                        |
| `tif`           | string  | `GTC`                           | Type of advanced order, Available values : FILL\_OR\_KILL, GOOD\_TILL\_CANCEL, IMMEDIATE\_OR\_CANCEL, QUEUE\_OR\_CANCEL                                            |
| `currency`      | string  | `USDT`                          | Currency of account, eg: BTC, ETH, USDT                                                                                                                            |
| `price`         | double  | `8200`                          | The order price                                                                                                                                                    |
| `qty`           | double  | `11.0`                          | Order quantity                                                                                                                                                     |
| `openPosition`  | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `ordStatus`     | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `cumQty`        | double  | `11.0`                          | The number of orders that has been executed                                                                                                                        |
| `avgPx`         | double  | `4754.24`                       | Average price of filled orders                                                                                                                                     |
| `ordStatus`     | string  | `FILLED`                        | The order status, includes: `PENDING_NEW`, `NEW`, `PARTIALLY_FILLED`, `FILLED`, `PENDING_CANCEL`, `CANCELED`, `REJECTED`, `PENDING_REPLACE`, `REPLACED`, `WAITING` |
| `iceberg`       | boolean | `false`                         | The order is iceberg                                                                                                                                               |
| `showQty`       | double  | `1.0`                           | The order showQty                                                                                                                                                  |
| `pnl`           | double  | `1.1`                           | Pnl incurred for this order.                                                                                                                                       |
| `fee`           | double  | `1.1`                           | Fees incurred for this order.                                                                                                                                      |
| `triggerPrice`  | double  | `--`                            | Trigger price for conditional order                                                                                                                                |
| `triggerType`   | string  | `--`                            | Trigger type of price for conditional order, eg: LAST or INDEX, it will be LAST if not providedAvailable values : INDEX, LAST, MARK                                |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |
| `stopLossPrice` | double  | `--`                            | Stop loss price for advanced order, conflict with trailingStop                                                                                                     |
| `stopWinPrice`  | double  | `--`                            | Stop win price for advanced order                                                                                                                                  |
| `stopWinType`   | string  | `--`                            | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market                              |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": [
    {
      "id": "O101-20230531-040439-546-1837",
      "uid": "1323056886107491328",
      "symbol": "BTCUSDT",
      "created": 1685505879000,
      "modified": 1685505879000,
      "side": "Buy",
      "type": "Market",
      "tif": "GOOD_TILL_CANCEL",
      "currency": "BTC",
      "price": 0.0,
      "qty": 100.0,
      "openPosition": false,
      "cumQty": 100.0,
      "avgPx": 27620.2,
      "ordStatus": "FILLED",
      "iceberg": false,
      "showQty": 0.0,
      "source": "Normal",
      "pnl": 1.3365529862569942E-6,
      "fee": -1.448215436528338E-6,
      "triggerPrice": null,
      "triggerType": null,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null
    }
  ]
}
```

### `Query Trade List` <a href="#querytradelist" id="querytradelist"></a>

Request trades by order id

#### **Limit:**

Speed limit: 10 times/1min, Speed limit rule: apiKey

#### **Request URL:**

```bash
GET /trade/queryTrades
```

#### **Parameters：**

| Name      | Type   | Required                        | Default | Description  |
| --------- | ------ | ------------------------------- | ------- | ------------ |
| `orderId` | string | `O101-20230531-025722-174-1016` | `YES`   | The order ID |

#### **Response:**

| Name               | Type    | Example                         | Description                                              |
| ------------------ | ------- | ------------------------------- | -------------------------------------------------------- |
| `id`               | string  | `T101-20230531-040439-548-1608` | The trade ID                                             |
| `symbol`           | string  | `BTCUSDT`                       | The contract symbol                                      |
| `currency`         | string  | `USDT`                          | Currency of account, eg: BTC, ETH, USDT                  |
| `orderId`          | string  | `O101-20230531-025722-174-1016` | The order ID                                             |
| `side`             | string  | `--`                            | Direction of the order. Direction type: `Buy`, `Sell`    |
| `openPosition`     | boolean | `true`                          | Open position or Close position order, eg: true or false |
| `userId`           | string  | `1323056886107491328`           | The user id                                              |
| `accountId`        | string  | `1323056886107491328`           | The account id                                           |
| `price`            | double  | `8200`                          | The trade price                                          |
| `qty`              | double  | `11.0`                          | Order quantity                                           |
| `fee`              | double  | `1.1`                           | Fees incurred for this order.                            |
| `feeRate`          | double  | `0.0002`                        | Fee rate                                                 |
| `createdTimestamp` | long    | `1570759718825`                 | Timestamp when the order is created                      |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": [
    {
      "id": "T101-20230531-040439-548-1608",
      "symbol": "BTCUSDT",
      "orderId": "O101-20230531-040439-546-1837",
      "side": "Buy",
      "openPosition": false,
      "userId": "1323056886107491328",
      "accountId": "1323056886107491328-CCF-BTC",
      "price": 27620.2,
      "qty": 100.0,
      "fee": -1.448215436528338E-6,
      "feeRate": -4.0E-4,
      "createdTimestamp": "1685505880000",
      "currency": "BTC"
    }
  ]
}
```

### `Query Active Orders` <a href="#queryactiveorders" id="queryactiveorders"></a>

#### **Limit:**

Speed limit: 60 times /1 minutes, Speed limit rule: apiKey

#### **Request URL:**

```bash
GET /trade/queryActiveOrders
```

#### **Parameters：**

| Name     | Type | Required  | Default | Description                                                                                   |
| -------- | ---- | --------- | ------- | --------------------------------------------------------------------------------------------- |
| `symbol` | long | `BTCUSDT` | `NO`    | Retrieve active orders of symbol, eg: BTCUSDT; Will return all active orders of user if empty |

#### **Response:**

| Name            | Type    | Example                         | Description                                                                                                                                                        |
| --------------- | ------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`            | string  | `O101-20230531-025722-174-1016` | The order ID                                                                                                                                                       |
| `uid`           | string  | `1323056886107491328`           | The User ID                                                                                                                                                        |
| `symbol`        | string  | `BTCUSDT`                       | The contract symbol                                                                                                                                                |
| `created`       | long    | `1570759718825`                 | Timestamp when the order is created                                                                                                                                |
| `modified`      | long    | `1551062936784`                 | Timestamp when this order was updated last time                                                                                                                    |
| `clientOrderId` | string  | `213443`                        | An unique order ID which is defined by user                                                                                                                        |
| `side`          | string  | `--`                            | Direction of the order. Direction type: `Buy`, `Sell`                                                                                                              |
| `type`          | string  | `--`                            | The order type, includes: `LIMIT`, `Market`                                                                                                                        |
| `tif`           | string  | `GTC`                           | Type of advanced order, Available values : FILL\_OR\_KILL, GOOD\_TILL\_CANCEL, IMMEDIATE\_OR\_CANCEL, QUEUE\_OR\_CANCEL                                            |
| `currency`      | string  | `USDT`                          | Currency of account, eg: BTC, ETH, USDT                                                                                                                            |
| `price`         | double  | `8200`                          | The order price                                                                                                                                                    |
| `qty`           | double  | `11.0`                          | Order quantity                                                                                                                                                     |
| `openPosition`  | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `ordStatus`     | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `cumQty`        | double  | `11.0`                          | The number of orders that has been executed                                                                                                                        |
| `avgPx`         | double  | `4754.24`                       | Average price of filled orders                                                                                                                                     |
| `ordStatus`     | string  | `FILLED`                        | The order status, includes: `PENDING_NEW`, `NEW`, `PARTIALLY_FILLED`, `FILLED`, `PENDING_CANCEL`, `CANCELED`, `REJECTED`, `PENDING_REPLACE`, `REPLACED`, `WAITING` |
| `iceberg`       | boolean | `false`                         | The order is iceberg                                                                                                                                               |
| `showQty`       | double  | `1.0`                           | The order showQty                                                                                                                                                  |
| `pnl`           | double  | `1.1`                           | Pnl incurred for this order.                                                                                                                                       |
| `fee`           | double  | `1.1`                           | Fees incurred for this order.                                                                                                                                      |
| `triggerPrice`  | double  | `--`                            | Trigger price for conditional order                                                                                                                                |
| `triggerType`   | string  | `--`                            | Trigger type of price for conditional order, eg: LAST or INDEX, it will be LAST if not providedAvailable values : INDEX, LAST, MARK                                |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |
| `stopLossPrice` | double  | `--`                            | Stop loss price for advanced order, conflict with trailingStop                                                                                                     |
| `stopWinPrice`  | double  | `--`                            | Stop win price for advanced order                                                                                                                                  |
| `stopWinType`   | string  | `--`                            | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market                              |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |
| `positionId`    | string  | `--`                            | The position ID, eg: 1323056886107491328-CCF-USDT-XRPUSDT-Long                                                                                                     |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": [
    {
      "id": "O101-20230531-040439-546-1837",
      "uid": "1323056886107491328",
      "symbol": "BTCUSDT",
      "created": 1685505879000,
      "modified": 1685505879000,
      "side": "Buy",
      "type": "Market",
      "tif": "GOOD_TILL_CANCEL",
      "currency": "BTC",
      "price": 0.0,
      "qty": 100.0,
      "openPosition": false,
      "cumQty": 100.0,
      "avgPx": 27620.2,
      "ordStatus": "FILLED",
      "iceberg": false,
      "showQty": 0.0,
      "source": "Normal",
      "pnl": 1.3365529862569942E-6,
      "fee": -1.448215436528338E-6,
      "triggerPrice": null,
      "triggerType": null,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null
    }
  ]
}
```

### `Cancel order` <a href="#cancelorder" id="cancelorder"></a>

Cancel an order, `orderId` or `clientOrderId` is required. This API endpoint requires your signed request.

#### **Request Weight:**

Speed limit: 40 times/second Speed limit rule: apiKey

#### **Request Url:**

```bash
POST /trade/cancelOrder
```

#### **Parameter:**

| Name            | Type    | Required | Default | Description                               |
| --------------- | ------- | -------- | ------- | ----------------------------------------- |
| `orderId`       | integer | `NO`     | `--`    | The order ID                              |
| `clientOrderId` | string  | `NO`     | `--`    | Unique customized client ID for the order |

`orderId` and `clientOrderId`, at least one **MUST** be provided.

#### **Response:**

| Name     | Type    | Example                         | Description                                          |
| -------- | ------- | ------------------------------- | ---------------------------------------------------- |
| `result` | integer | `O101-20230531-023520-732-0610` | The order ID or An unique order ID defined by client |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": "O101-20230531-023520-732-0610"
}
```

### `Close Position` <a href="#closeposition" id="closeposition"></a>

Close all position with market price

#### **Request Weight:**

Speed limit: 8 times/second Speed limit rule: apiKey

#### **Request URL:**

```bash
POST /trade/closePosition
```

#### **Parameters：**

| Name       | Type   | Required | Default | Description                             |
| ---------- | ------ | -------- | ------- | --------------------------------------- |
| `symbol`   | string | `YES`    | `--`    | The contract symbol, eg: BTCUSDT        |
| `side`     | string | `YES`    | `--`    | Position side, eg: `Long` or `Short`    |
| `currency` | string | `YES`    | `--`    | Currency of account, eg: BTC, ETH, USDT |

#### **Response:**

```json
{
  "code": 0,
  "message": "OK",
  "result": null
}
```

### `Query Position` <a href="#queryposition" id="queryposition"></a>

Query all the position of the user

#### **Limit:**

Speed limit: 60 times /1 minutes, Speed limit rule: apiKey

#### **Request URL:**

```bash
GET /trade/queryPosition
```

#### **Parameters：**

| Name         | Type         | Required     | Default      | Description  |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| ------------ | ------------ | ------------ | ------------ | ------------ |

#### **Response:**

| Name                | Type   | Example                                     | Description                                                                                                                           |
| ------------------- | ------ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `uid`               | string | `1323056886107491328`                       | The User ID                                                                                                                           |
| `id`                | string | `1323056886107491328-CCF-ETH-ETHUSDT-Short` | The position ID                                                                                                                       |
| `lvg`               | double | `10.0`                                      | The position lever                                                                                                                    |
| `currency`          | string | `USDT`                                      | Currency of account, eg: BTC, ETH, USDT                                                                                               |
| `symbol`            | string | `BTCUSDT`                                   | The contract symbol                                                                                                                   |
| `side`              | string | `--`                                        | Direction of the position. Direction type: `Long`, `Short`                                                                            |
| `qty`               | double | `11.0`                                      | Position quantity                                                                                                                     |
| `price`             | double | `4754.24`                                   | Price of position                                                                                                                     |
| `closableQty`       | double | `11.0`                                      | Closable quantity                                                                                                                     |
| `pnlRate`           | double | `-0.001`                                    | Pnl rate                                                                                                                              |
| `value`             | double | `11.0`                                      | Position value by currency                                                                                                            |
| `positionLeverage`  | double | `11.0`                                      | Position leverage                                                                                                                     |
| `liquidationPrice`  | double | `11.0`                                      | Liquidation price                                                                                                                     |
| `pnl`               | double | `1.1`                                       | Realized pnl                                                                                                                          |
| `urPnL`             | double | `1.1`                                       | Unrealized pnl                                                                                                                        |
| `deposit`           | double | `1.1`                                       | deposit                                                                                                                               |
| `lastPrice`         | double | `1.1`                                       | Last price                                                                                                                            |
| `created`           | long   | `1570759718825`                             | Timestamp when the position is created                                                                                                |
| `trailingStopPrice` | double | `--`                                        | Trailing stop price                                                                                                                   |
| `stopLossPrice`     | double | `--`                                        | Stop loss price for advanced order, conflict with trailingStop                                                                        |
| `stopWinPrice`      | double | `--`                                        | Stop win price for advanced order                                                                                                     |
| `stopWinType`       | string | `--`                                        | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market |
| `trailingStop`      | double | `--`                                        | Trailing stop value for advanced order, conflict with stopLossPrice                                                                   |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": [
    {
      "uid": "1323056886107491328",
      "currency": "ETH",
      "symbol": "BTCUSDT",
      "side": "Long",
      "qty": 0.0,
      "individualPosition": true,
      "price": 0.0,
      "closableQty": 0.0,
      "pnlRate": 0.0,
      "value": 0.0,
      "positionLeverage": 20.0,
      "trailingStopPrice": 0.0,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null,
      "pnl": 0.0,
      "urPnL": 0.0,
      "liquidationPrice": 0.0,
      "deposit": 0.0,
      "created": "2023-02-15T11:40:13.000+00:00",
      "lastPrice": 27128.5
    },
    {
      "uid": "1323056886107491328",
      "currency": "USDT",
      "symbol": "BTCUSDT",
      "side": "Short",
      "qty": 100.0,
      "individualPosition": false,
      "price": 27117.1,
      "closableQty": 100.0,
      "pnlRate": -0.013644526885249529,
      "value": 100.0,
      "positionLeverage": 20.0,
      "trailingStopPrice": 0.0,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null,
      "pnl": -0.04,
      "urPnL": -0.09742929738062658,
      "liquidationPrice": 162026.91766730743,
      "deposit": 5.0,
      "created": "2023-05-31T08:03:45.000+00:00",
      "lastPrice": 27128.5
    },
    {
      "uid": "1323056886107491328",
      "currency": "TUSDT",
      "symbol": "TBTCTUSDT",
      "side": "Long",
      "qty": 0.0,
      "individualPosition": true,
      "price": 0.0,
      "closableQty": 0.0,
      "pnlRate": 0.0,
      "value": 0.0,
      "positionLeverage": 20.0,
      "trailingStopPrice": 0.0,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null,
      "pnl": 0.0,
      "urPnL": 0.0,
      "liquidationPrice": 0.0,
      "deposit": 0.0,
      "created": "2023-02-17T09:06:52.000+00:00",
      "lastPrice": 27135.0
    },
    {
      "uid": "1323056886107491328",
      "currency": "TUSDT",
      "symbol": "TBTCTUSDT",
      "side": "Short",
      "qty": 0.0,
      "individualPosition": true,
      "price": 0.0,
      "closableQty": 0.0,
      "pnlRate": 0.0,
      "value": 0.0,
      "positionLeverage": 20.0,
      "trailingStopPrice": 0.0,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null,
      "pnl": 0.0,
      "urPnL": 0.0,
      "liquidationPrice": 0.0,
      "deposit": 0.0,
      "created": "2023-02-15T11:05:54.000+00:00",
      "lastPrice": 27135.0
    },
    {
      "uid": "1323056886107491328",
      "currency": "BTC",
      "symbol": "BTCUSDT",
      "side": "Long",
      "qty": 0.0,
      "individualPosition": false,
      "price": 0.0,
      "closableQty": 0.0,
      "pnlRate": 0.0,
      "value": 0.0,
      "positionLeverage": 16.0,
      "trailingStopPrice": 0.0,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null,
      "pnl": 0.0,
      "urPnL": 0.0,
      "liquidationPrice": 0.0,
      "deposit": 0.0,
      "created": "2023-02-15T11:08:13.000+00:00",
      "lastPrice": 27128.5
    },
    {
      "uid": "1323056886107491328",
      "currency": "BTC",
      "symbol": "BTCUSDT",
      "side": "Short",
      "qty": 0.0,
      "individualPosition": false,
      "price": 0.0,
      "closableQty": 0.0,
      "pnlRate": 0.0,
      "value": 0.0,
      "positionLeverage": 16.0,
      "trailingStopPrice": 0.0,
      "stopLossPrice": null,
      "stopWinType": null,
      "stopWinPrice": null,
      "trailingStop": null,
      "pnl": 0.0,
      "urPnL": 0.0,
      "liquidationPrice": 0.0,
      "deposit": 0.0,
      "created": "2023-05-31T04:04:07.000+00:00",
      "lastPrice": 27128.5
    }
  ]
}
```

### `Switch PosSide` <a href="#switchposition" id="switchposition"></a>

Switch position side

#### **Limit:**

Speed limit: 8 times/second, Speed limit rule: apiKey

#### **Request Url:**

```bash
POST /trade/switchPosSide
```

#### **Parameter:**

| Name              | Type    | Required | Default | Description                                                                           |
| ----------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------- |
| `twoSidePosition` | boolean | `YES`    | `--`    | Switch to two side position mode if true, otherwise, switch to one side position mode |
| `currency`        | string  | `YES`    | `--`    | Currency of account, eg: BTC, ETH, USDT                                               |

#### **Response:**

| Name         | Type         | Example      | Description  |
| ------------ | ------------ | ------------ | ------------ |
| ------------ | ------------ | ------------ | ------------ |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": null
}
```

### `Change Position Mode` <a href="#changepositionmode" id="changepositionmode"></a>

Change position mode between Individual and Cross

#### **Limit:**

Speed limit: 8 times/second, Speed limit rule: apiKey

#### **Request Url:**

```bash
POST /trade/changePosMode
```

#### **Parameter:**

| Name         | Type    | Required | Default | Description                                       |
| ------------ | ------- | -------- | ------- | ------------------------------------------------- |
| `individual` | boolean | `YES`    | `--`    | Position mode, true -> Individual; false -> Cross |
| `currency`   | string  | `YES`    | `--`    | Currency of account, eg: BTC, ETH, USDT           |

#### **Response:**

| Name         | Type         | Example      | Description  |
| ------------ | ------------ | ------------ | ------------ |
| ------------ | ------------ | ------------ | ------------ |

```json
{
  "code": 0,
  "message": "OK",
  "result": null
}
```

### `Change PosLeverage` <a href="#changeposleverage" id="changeposleverage"></a>

Change position leverage

#### **Limit:**

Speed limit: 8 times/second, Speed limit rule: apiKey

#### **Request Url:**

```bash
POST /trade/changePosLeverage
```

#### **Parameter:**

| Name       | Type   | Required | Default | Description                             |
| ---------- | ------ | -------- | ------- | --------------------------------------- |
| `leverage` | double | `YES`    | `--`    | Position leverage                       |
| `symbol`   | string | `YES`    | `--`    | The contract symbol, eg: BTCUSDT        |
| `currency` | string | `YES`    | `--`    | Currency of account, eg: BTC, ETH, USDT |

#### **Response:**

| Name         | Type         | Example      | Description  |
| ------------ | ------------ | ------------ | ------------ |
| ------------ | ------------ | ------------ | ------------ |

```json
{
  "code": 0,
  "message": "OK",
  "result": null
}
```

### `Change Risk` <a href="#changerisk" id="changerisk"></a>

Change risk setting of position

#### **Limit:**

Speed limit: 10 times/second, Speed limit rule: apiKey

#### **Request Url:**

```bash
POST /trade/riskSetting
```

#### **Parameter:**

| Name            | Type   | Required | Default | Description                                                                                                                           |
| --------------- | ------ | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `symbol`        | string | `YES`    | `--`    | The contract symbol, eg: BTCUSDT                                                                                                      |
| `currency`      | string | `YES`    | `--`    | Currency of account, eg: BTC, ETH, USDT                                                                                               |
| `side`          | string | `YES`    | `--`    | Position side, eg: Long or Short                                                                                                      |
| `positionId`    | string | `YES`    | `--`    | The position ID, eg: 1323056886107491328-CCF-USDT-XRPUSDT-Long                                                                        |
| `addDeposit`    | double | `NO`     | `--`    | Increase or decrease extra deposit for individual position                                                                            |
| `stopLossPrice` | double | `NO`     | `--`    | Stop loss price for advanced order, conflict with trailingStop                                                                        |
| `stopWinPrice`  | double | `NO`     | `--`    | Stop win price for advanced order                                                                                                     |
| `stopWinType`   | string | `NO`     | `--`    | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market |
| `trailingStop`  | double | `NO`     | `--`    | Trailing stop value for advanced order, conflict with stopLossPrice                                                                   |

#### **Response:**

| Name         | Type         | Example      | Description  |
| ------------ | ------------ | ------------ | ------------ |
| ------------ | ------------ | ------------ | ------------ |

```json
{
  "code": 0,
  "message": "OK",
  "result": null
}
```

### `Query Accounts` <a href="#queryaccounts" id="queryaccounts"></a>

This endpoint is used to retrieve contract account balance. This endpoint requires your signed request.

#### **Limit:**

Speed limit: 60 times/min, Speed limit rule: apiKey

#### **Request Url:**

```bash
GET  /trade/queryAccounts
```

#### **Parameters:**

None

#### **Response:**

| Name               | Type   | Example               | Description       |
| ------------------ | ------ | --------------------- | ----------------- |
| `uid`              | string | `1323056886107491328` | User id           |
| `currency`         | string | `USDT`                | currency          |
| `cash`             | double | `0.01215991`          | cash              |
| `withdrawableCash` | double | `0`                   | Withdrawable cash |
| `frozenCash`       | double | `0`                   | Frozen cash       |
| `urPnl`            | double | `0`                   | Unrealized pnl    |
| `cashAvailable`    | double | `0`                   | Available cash    |

#### **Example:**

```json
{
    "code": 0,
        "message": "OK",
        "result": [
        {
            "uid": "1323056886107491328",
            "currency": "ETH",
            "cash": 0.0,
            "withdrawableCash": 0.0,
            "frozenCash": 0.0,
            "urPnl": 0.0,
            "cashAvailable": 0.0
        },
        {
            "uid": "1323056886107491328",
            "currency": "USDT",
            "cash": 499.90922659263174,
            "withdrawableCash": 499.90922659263174,
            "frozenCash": 0.0,
            "urPnl": 0.0,
            "cashAvailable": 499.90922659263174
        },
        {
            "uid": "1323056886107491328",
            "currency": "TUSDT",
            "cash": 1000.0,
            "withdrawableCash": 1000.0,
            "frozenCash": 0.0,
            "urPnl": 0.0,
            "cashAvailable": 1000.0
        },
        {
            "uid": "1323056886107491328",
            "currency": "BTC",
            "cash": 9.999288458956643,
            "withdrawableCash": 0.0,
            "frozenCash": 9.999288458956643,
            "urPnl": 2.573443933625344E-5,
            "cashAvailable": 9.999190074639152
        }
    ]
}
```

### `Query Account Settings` <a href="#queryaccountsettings" id="queryaccountsettings"></a>

#### **Limit:**

Speed limit: 60 times/1min, Speed limit rule: apiKey

#### **Request Url:**

```bash
GET  /trade/queryAccountSettings
```

#### **Parameters:**

None

#### **Response:**

| Name                 | Type    | Example               | Description                                              |
| -------------------- | ------- | --------------------- | -------------------------------------------------------- |
| `uid`                | string  | `1323056886107491328` | User id                                                  |
| `currency`           | string  | `USDT`                | currency                                                 |
| `twoWayPosition`     | boolean | `true`                | Two way position                                         |
| `individualPosition` | boolean | `false`               | Individual position                                      |
| `multiPosition`      | boolean | `false`               | false means closed positions, true means split positions |

#### **Example:**

```json
{
  "code": 0,
  "message": "OK",
  "result": [
    {
      "uid": "1323056886107491328",
      "currency": "ETH",
      "twoWayPosition": false,
      "individualPosition": true
    },
    {
      "uid": "1323056886107491328",
      "currency": "USDT",
      "twoWayPosition": true,
      "individualPosition": false
    },
    {
      "uid": "1323056886107491328",
      "currency": "TUSDT",
      "twoWayPosition": false,
      "individualPosition": true
    },
    {
      "uid": "1323056886107491328",
      "currency": "BTC",
      "twoWayPosition": true,
      "individualPosition": false
    }
  ]
}
```

## Private Websocket Endpoints

### Receiving data requires two steps：

* Step 1: User login
* Step 2：Subscription event

### `User Login` <a href="#userlogin" id="userlogin"></a>

#### **Parameters:**

| Name        | Type   | Required | Default | Description                                                                                                                                                                     |
| ----------- | ------ | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `op`        | string | `YES`    | `login` | Operation event login                                                                                                                                                           |
| `txId`      | string | `YES`    | `--`    | txId is a unique string, format: TXyyyyMMdd-HHmmss-ms-serial number, TX year-month-day-hour-minute-second-millisecond-unique serial number, for example TX20220809-142413-671-1 |
| `apiKey`    | string | `YES`    | `--`    | Apply at the individual center, apikey/apiSecret                                                                                                                                |
| `expires`   | long   | `YES`    | `--`    | Expiration milliseconds, usually set to the current time plus 10 seconds                                                                                                        |
| `signature` | string | `YES`    | `--`    | signature=sha256(apiSecret+method+path+expires)Note: The + needs to be removed to generate a signature                                                                          |

#### **Example:**

```json
{
	"op": "login",
	"txId" :"TX20200317-133934-511-458",
    "apiKey": "Ffs9IfPXEgeZa0aDebgkS4h1In73w2a0IyqYcfnVraGCcjLFKPR6bpGxw0iiMVzl",
	"signature": "6532a891aa0b950bf28d82cf71bbce4a379029417d855de76e793654a1247e89",
	"expires": "1787218464317"
}
```

#### **Response:**

| Name   | Type   | Example                     | Description                                                                                                                                                                     |
| ------ | ------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `txId` | string | `TX20200317-133934-511-458` | txId is a unique string, format: TXyyyyMMdd-HHmmss-ms-serial number, TX year-month-day-hour-minute-second-millisecond-unique serial number, for example TX20220809-142413-671-1 |

#### **Example:**

```json
{
  "txId": "TX20200317-133934-511-458",
  "errCode": 0,
  "key": null
}
```

### `User Account Update` <a href="#useraccountupdate" id="useraccountupdate"></a>

#### **Parameters:**

| Name        | Type   | Required | Default   | Description                                                                                            |
| ----------- | ------ | -------- | --------- | ------------------------------------------------------------------------------------------------------ |
| `op`        | string | `YES`    | `--`      | subscribe/unsubscribe                                                                                  |
| `channel`   | string | `YES`    | `channel` | Event name                                                                                             |
| `apiKey`    | string | `YES`    | `--`      | Apply at the individual center, apikey/apiSecret                                                       |
| `expires`   | long   | `YES`    | `--`      | Expiration milliseconds, usually set to the current time plus 10 seconds                               |
| `signature` | string | `YES`    | `--`      | signature=sha256(apiSecret+method+path+expires)Note: The + needs to be removed to generate a signature |

#### **Example:**

```json
{
  "op": "subscribe",
  "apiKey": "Ffs9IfPXEgeZa0aDebgkS4h1In73w2a0IyqYcfnVraGCcjLFKPR6bpGxw0iiMVzl",
  "signature": "6942114e809638701c001f1f2f633fe92727e42b54376a7c7fd594fc170e5819",
  "expires": "1787218464317",
  "channel": "accountUpdate"
}
```

#### **Response:**

| Name               | Type   | Example               | Description       |
| ------------------ | ------ | --------------------- | ----------------- |
| `uid`              | string | `1323056886107491328` | User id           |
| `currency`         | string | `USDT`                | currency          |
| `cash`             | double | `0.01215991`          | cash              |
| `withdrawableCash` | double | `0`                   | Withdrawable cash |
| `frozenCash`       | double | `0`                   | Frozen cash       |
| `urPnl`            | double | `0`                   | Unrealized pnl    |
| `cashAvailable`    | double | `0`                   | Available cash    |

#### **Example:**

```json
{
  "account": {
    "uid": "1323056886107491328",
    "currency": "USDT",
    "cash": 499.6878667490653,
    "withdrawableCash": 0.0,
    "frozenCash": 499.6878667490653,
    "urPnl": 0.03929670132261469,
    "cashAvailable": 494.72519861532174
  },
  "key": "Ffs9IfPXEgeZa0aDebgkS4h1In73w2a0IyqYcfnVraGCcjLFKPR6bpGxw0iiMVzl",
  "event": "accountUpdate"
}
```

### `User Position Update` <a href="#userpositionupdate" id="userpositionupdate"></a>

#### **Parameters:**

| Name        | Type   | Required | Default          | Description                                                                                            |
| ----------- | ------ | -------- | ---------------- | ------------------------------------------------------------------------------------------------------ |
| `op`        | string | `YES`    | `--`             | subscribe/unsubscribe                                                                                  |
| `channel`   | string | `YES`    | `positionUpdate` | Event name                                                                                             |
| `apiKey`    | string | `YES`    | `--`             | Apply at the individual center, apikey/apiSecret                                                       |
| `expires`   | long   | `YES`    | `--`             | Expiration milliseconds, usually set to the current time plus 10 seconds                               |
| `signature` | string | `YES`    | `--`             | signature=sha256(apiSecret+method+path+expires)Note: The + needs to be removed to generate a signature |

#### **Example:**

```json
{
  "op": "subscribe",
  "apiKey": "Ffs9IfPXEgeZa0aDebgkS4h1In73w2a0IyqYcfnVraGCcjLFKPR6bpGxw0iiMVzl",
  "signature": "6942114e809638701c001f1f2f633fe92727e42b54376a7c7fd594fc170e5819",
  "expires": "1787218464317",
  "channel": "positionUpdate"
}
```

#### **Response:**

| Name                 | Type    | Example               | Description                                                                                                                           |
| -------------------- | ------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `uid`                | string  | `1323056886107491328` | The User ID                                                                                                                           |
| `currency`           | string  | `USDT`                | Currency of account, eg: BTC, ETH, USDT                                                                                               |
| `symbol`             | string  | `BTCUSDT`             | The contract symbol                                                                                                                   |
| `side`               | string  | `--`                  | Direction of the position. Direction type: `Long`, `Short`                                                                            |
| `qty`                | double  | `11.0`                | Position quantity                                                                                                                     |
| `price`              | double  | `4754.24`             | Price of position                                                                                                                     |
| `closableQty`        | double  | `11.0`                | Closable quantity                                                                                                                     |
| `pnlRate`            | double  | `-0.001`              | Pnl rate                                                                                                                              |
| `value`              | double  | `11.0`                | Position value by currency                                                                                                            |
| `positionLeverage`   | double  | `11.0`                | Position leverage                                                                                                                     |
| `liquidationPrice`   | double  | `11.0`                | Liquidation price                                                                                                                     |
| `pnl`                | double  | `1.1`                 | Realized pnl                                                                                                                          |
| `urPnL`              | double  | `1.1`                 | Unrealized pnl                                                                                                                        |
| `deposit`            | double  | `1.1`                 | deposit                                                                                                                               |
| `lastPrice`          | double  | `1.1`                 | Last price                                                                                                                            |
| `created`            | long    | `1570759718825`       | Timestamp when the position is created                                                                                                |
| `trailingStopPrice`  | double  | `--`                  | Trailing stop price                                                                                                                   |
| `stopLossPrice`      | double  | `--`                  | Stop loss price for advanced order, conflict with trailingStop                                                                        |
| `stopWinPrice`       | double  | `--`                  | Stop win price for advanced order                                                                                                     |
| `stopWinType`        | string  | `--`                  | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market |
| `trailingStop`       | double  | `--`                  | Trailing stop value for advanced order, conflict with stopLossPrice                                                                   |
| `individualPosition` | boolean | false                 | Individual position                                                                                                                   |

#### **Example:**

```json
{
  "position": {
    "uid": "1323056886107491328",
    "currency": "BTC",
    "symbol": "BTCUSDT",
    "side": "Short",
    "qty": 100.0,
    "individualPosition": false,
    "price": 25736.8,
    "closableQty": 100.0,
    "pnlRate": -1.1547384662514797,
    "value": 0.0037344734597817746,
    "positionLeverage": 30.0,
    "trailingStopPrice": 0.0,
    "stopLossPrice": 0.0,
    "stopWinType": null,
    "stopWinPrice": 0.0,
    "trailingStop": 0.0,
    "pnl": -4.389851219720317E-6,
    "urPnL": -1.5101346944019543E-4,
    "liquidationPrice": 0.0,
    "deposit": 1.2951623097406568E-4,
    "created": 1686049269000,
    "lastPrice": 26766.9
  },
  "key": "Ffs9IfPXEgeZa0aDebgkS4h1In73w2a0IyqYcfnVraGCcjLFKPR6bpGxw0iiMVzl",
  "event": "positionUpdate"
}
```

### `User Order Update` <a href="#userorderupdate" id="userorderupdate"></a>

#### **Parameters:**

| Name        | Type   | Required | Default       | Description                                                                                            |
| ----------- | ------ | -------- | ------------- | ------------------------------------------------------------------------------------------------------ |
| `op`        | string | `YES`    | `--`          | subscribe/unsubscribe                                                                                  |
| `channel`   | string | `YES`    | `orderUpdate` | Event name                                                                                             |
| `apiKey`    | string | `YES`    | `--`          | Apply at the individual center, apikey/apiSecret                                                       |
| `expires`   | long   | `YES`    | `--`          | Expiration milliseconds, usually set to the current time plus 10 seconds                               |
| `signature` | string | `YES`    | `--`          | signature=sha256(apiSecret+method+path+expires)Note: The + needs to be removed to generate a signature |

#### **Example:**

```json
{
  "op": "subscribe",
  "apiKey": "Ffs9IfPXEgeZa0aDebgkS4h1In73w2a0IyqYcfnVraGCcjLFKPR6bpGxw0iiMVzl",
  "signature": "6942114e809638701c001f1f2f633fe92727e42b54376a7c7fd594fc170e5819",
  "expires": "1787218464317",
  "channel": "orderUpdate"
}
```

#### **Response:**

| Name            | Type    | Example                         | Description                                                                                                                                                        |
| --------------- | ------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`            | string  | `O101-20230531-025722-174-1016` | The order ID                                                                                                                                                       |
| `uid`           | string  | `1323056886107491328`           | The User ID                                                                                                                                                        |
| `symbol`        | string  | `BTCUSDT`                       | The contract symbol                                                                                                                                                |
| `created`       | long    | `1570759718825`                 | Timestamp when the order is created                                                                                                                                |
| `modified`      | long    | `1551062936784`                 | Timestamp when this order was updated last time                                                                                                                    |
| `clientOrderId` | string  | `213443`                        | An unique order ID which is defined by user                                                                                                                        |
| `side`          | string  | `--`                            | Direction of the order. Direction type: `Buy`, `Sell`                                                                                                              |
| `type`          | string  | `--`                            | The order type, includes: `LIMIT`, `Market`                                                                                                                        |
| `tif`           | string  | `GTC`                           | Type of advanced order, Available values : FILL\_OR\_KILL, GOOD\_TILL\_CANCEL, IMMEDIATE\_OR\_CANCEL, QUEUE\_OR\_CANCEL                                            |
| `currency`      | string  | `USDT`                          | Currency of account, eg: BTC, ETH, USDT                                                                                                                            |
| `price`         | double  | `8200`                          | The order price                                                                                                                                                    |
| `qty`           | double  | `11.0`                          | Order quantity                                                                                                                                                     |
| `openPosition`  | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `ordStatus`     | boolean | `true`                          | Open position or Close position order, eg: true or false                                                                                                           |
| `cumQty`        | double  | `11.0`                          | The number of orders that have been executed                                                                                                                       |
| `avgPx`         | double  | `4754.24`                       | Average price of filled orders                                                                                                                                     |
| `ordStatus`     | string  | `FILLED`                        | The order status, includes: `PENDING_NEW`, `NEW`, `PARTIALLY_FILLED`, `FILLED`, `PENDING_CANCEL`, `CANCELED`, `REJECTED`, `PENDING_REPLACE`, `REPLACED`, `WAITING` |
| `iceberg`       | boolean | `false`                         | The order is iceberg                                                                                                                                               |
| `showQty`       | double  | `1.0`                           | The order showQty                                                                                                                                                  |
| `pnl`           | double  | `1.1`                           | Pnl incurred for this order.                                                                                                                                       |
| `fee`           | double  | `1.1`                           | Fees incurred for this order.                                                                                                                                      |
| `triggerPrice`  | double  | `--`                            | Trigger price for conditional order                                                                                                                                |
| `triggerType`   | string  | `--`                            | Trigger type of price for conditional order, eg: LAST or INDEX, it will be LAST if not providedAvailable values : INDEX, LAST, MARK                                |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |
| `stopLossPrice` | double  | `--`                            | Stop loss price for advanced order, conflict with trailingStop                                                                                                     |
| `stopWinPrice`  | double  | `--`                            | Stop win price for advanced order                                                                                                                                  |
| `stopWinType`   | string  | `--`                            | Stop win type of price for advanced order, eg: Limit or Market, it's required if stopWinPrice is set Available values : Limit, Market                              |
| `trailingStop`  | double  | `--`                            | Trailing stop value for advanced order, conflict with stopLossPrice                                                                                                |

#### **Example:**

```json
{
  "order": {
    "id": "O101-20230607-085005-846-2198",
    "clientOrderId": "213443",
    "uid": "1323056886107491328",
    "symbol": "BTCUSDT",
    "created": 1686127805000,
    "modified": 1686127805000,
    "side": "Buy",
    "type": "Market",
    "tif": "GOOD_TILL_CANCEL",
    "currency": "BTC",
    "price": 0.0,
    "qty": 100.0,
    "openPosition": false,
    "cumQty": 0.0,
    "avgPx": 0.0,
    "ordStatus": "NEW",
    "iceberg": false,
    "showQty": 0.0,
    "source": "Normal",
    "pnl": 0.0,
    "fee": 0.0,
    "triggerPrice": null,
    "triggerType": null,
    "stopLossPrice": null,
    "stopWinType": null,
    "stopWinPrice": null,
    "trailingStop": null
  },
  "key": "Ffs9IfPXEgeZa0aDebgkS4h1In73w2a0IyqYcfnVraGCcjLFKPR6bpGxw0iiMVzl",
  "event": "orderUpdate"
}
```

### Code Description <a href="#codedescription" id="codedescription"></a>

| Code    | Description                                                          |
| ------- | -------------------------------------------------------------------- |
| `0`     | OK                                                                   |
| `20003` | Need to login before attempt any action                              |
| `20004` | System is offline                                                    |
| `20013` | Transaction sent too fast                                            |
| `20014` | Account id doesn't exist                                             |
| `20032` | Request is refused                                                   |
| `20035` | Balance is not enough                                                |
| `20040` | User setting doesn't exist                                           |
| `20041` | Ip address is prohibited                                             |
| `20043` | Parameter format is wrong                                            |
| `20045` | Order too fast                                                       |
| `20048` | Order too many                                                       |
| `20088` | Login blocked                                                        |
| `20089` | Operation too fast                                                   |
| `20093` | Subuser doesn't exist                                                |
| `20094` | Subaccount doesn't exist                                             |
| `20095` | Subaccount has been frozen                                           |
| `20096` | Min Qty count limit                                                  |
| `20097` | Subaccount cash not zero                                             |
| `20109` | The account has expired, please contact the administrator            |
| `20111` | Account has triggered risk control, please contact the administrator |
| `20117` | Invalid token value                                                  |
| `20118` | Invalid order price                                                  |
| `20120` | User State disallows this action                                     |
| `20121` | Operate frequently, try again 60 seconds later                       |
| `20122` | Operate frequently, try again 24 hours later                         |
| `20125` | Fund in account is changing, please try again later                  |
| `20135` | No permission                                                        |
| `20138` | Cancel limit exceeded. Try again in 24 hours                         |
| `20140` | Too many completed orders                                            |
| `20141` | Too many incompleted orders                                          |
| `20146` | Manage amount more than 30                                           |
| `21010` | Exceeds the open position line                                       |
| `21011` | Exceeds the max leverage setting                                     |
| `21012` | Can't trade real contract with virtual currency                      |
| `21013` | Can't trade virtual contract with real currency                      |
| `23016` | Transaction is still pending                                         |
| `23017` | Order qty inquiry error                                              |
| `24001` | Symbol not found                                                     |
| `24002` | Invalid market                                                       |
| `24003` | Invalid currency                                                     |
| `24004` | Order quantity should be an integer multiple of lot size             |
| `24005` | Order price should be an integer multiple of tick                    |
| `25001` | Order field is empty                                                 |
| `25002` | Order field error                                                    |
| `25004` | Order id already exists                                              |
| `25005` | Order id not found                                                   |
| `25006` | Order already completed                                              |
| `25007` | Account state disallow this action                                   |
| `25008` | Daily order exceeds limit                                            |
| `25009` | Invalid order quantity                                               |
| `25010` | Data conversion error                                                |
| `25011` | Order quantity must be greater than 0                                |
| `25012` | Order price must be greater than 0                                   |
| `25013` | Can't amend up order qty                                             |
| `25014` | One of price & qty must be specified to amend                        |
| `25015` | Cant allocate account for order                                      |
| `25016` | Invalid order type                                                   |
| `25017` | Invalid order side                                                   |
| `25018` | Exchange order id not found                                          |
| `25019` | No price for credit calculation                                      |
| `25020` | Quote is invalid                                                     |
| `25021` | Insufficient fund                                                    |
| `25022` | There is pending order for this instrument                           |
| `25025` | Not enough closable qty for position                                 |
| `25027` | Invalid trigger price                                                |
| `25029` | Position exists in the account, please close it first                |
| `25030` | Nothing is changed                                                   |
| `25031` | Invalid leverage value                                               |
| `25032` | Invalid Stop loss price                                              |
| `25033` | Invalid Stop win price                                               |
| `25034` | Can't add deposit for none-individual position                       |
| `25035` | Empty position                                                       |
| `25036` | No enough position deposit to extract                                |
| `25037` | Maintenance margin is not enough                                     |
| `25038` | Initial margin is not enough                                         |
| `25039` | Risk limit is not correct                                            |
| `25040` | Risk limit is exceeded                                               |
| `25041` | Can't amend risk order                                               |
| `25042` | Can't cancel risk order                                              |
| `25043` | Price of buy order can't be less than stop loss                      |
| `25044` | Price of buy order can't be greater than stop win                    |
| `25045` | Price of sell order can't be greater than stop loss                  |
| `25046` | Price of sell order can't be less than stop win                      |
| `25048` | Account cash is not enough                                           |
| `25049` | Risk limit is not enough                                             |
| `25051` | Order price is out range of index price limitation                   |
| `25052` | Closing position, please wait                                        |
| `25053` | Please close position first                                          |
| `25062` | Net position would exceed the limit                                  |
| `25063` | Invalid trigger type                                                 |
| `25064` | Invalid shown quantity                                               |
| `25065` | Hidden order can't be passive                                        |
| `25066` | Can't set both trailing stop & stop loss                             |
| `25067` | Please change only one parameter each time                           |
| `25068` | Can only set trigger price for conditional order                     |
| `25069` | Invalid trailing stop value                                          |
| `25070` | Invalid stop win type                                                |
| `25071` | Risk setting is not allowed for close position order                 |
| `25072` | Operating reversal order, please wait                                |
| `25073` | Operating close position, please wait                                |
| `25074` | Operating close position and cancel order, please wait               |
| `25078` | The symbol is restricted from trading                                |
| `25079` | The account currency is restricted from trading                      |
| `25080` | The parameter value exceeds the upper limit                          |
| `29000` | The total limit of key is exceeded                                   |
| `29001` | Invalid key value                                                    |
| `29002` | Key disabled                                                         |
| `29003` | Key has no permission                                                |
| `29004` | Wrong signature value                                                |
| `29005` | Request expired                                                      |
| `29006` | Invalid ip address                                                   |
| `29008` | Api key exists for user                                              |
| `29009` | Access token is wrong                                                |
| `29010` | Access token has expired                                             |
| `29011` | Param is wrong                                                       |
| `29014` | Request too frequently, please try again later                       |


# Block Trade

[User Guide](/trubit-pro/blocktrading/user-guide)

[BlockTrading Api](/trubit-pro/blocktrading/blocktrading-api)


# User Guide

## Getting Started

The TruBit Business account manager opens a digital assets account for the API client’s UID. After the client logs into the TB Pro Web using the UID, they generate an API public and private key and configure the IP whitelist. Once completed, provide the UID to the TB account manager to enable OPEN API access.

![guide-1](https://667726841-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOcgSwPEO1WP2OtRQfugH%2Fuploads%2Fgit-blob-8a740a29865cbb4e82fa151d841beaea04fee811%2Fblocktrading-user-guide-1.png?alt=media)

* Register TruBit UID: <https://www.trubit.com/new/signup>
* How to get an API key and configure the White List: <https://www.trubit.com/new/user/interface>

***

## On-ramp Process (Pay-in)

![guide-2](https://667726841-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOcgSwPEO1WP2OtRQfugH%2Fuploads%2Fgit-blob-7a4af49b2f0526dcf69e8df74f74f177b9a39a35%2Fblocktrading-user-guide-2.png?alt=media)

### 1. Getting Ready for Your On Ramp

Here’s what you need to get started: Country, Merchant ID, Token type, Fiat type, Fiat amount, Order type, and Payment ID.

**1.1 Country**

* Call the Get Country List with Symbol Rate API to find your country.

**1.2 Merchant ID**

* Call Get Merchant List to retrieve the Merchant ID linked to your UID and note it down for your on ramp.

**1.3 Token and Fiat Types**

* Call Get Self Data List to discover the supported trading pairs and fiat currencies.
  * Note: This might also be referred to as Get Trading Pair List.

**1.4 Fiat Amount**

* Use orderAmount to specify how much fiat you want to buy, accurate to two decimal places.
* Note: If it exceeds two decimal places, the system will round down.

**1.5 Order Type**

* For on ramps, always set OrderType to BUY.

**1.6 Payment Method**

* Use Get Self Data List to find the supported payment methods for each trading pair and record the corresponding Payment ID.
* Check the payment method supported by your order at this step.

### 2. Create On Ramp Order

**2.1 Call the `Get User Quote` API to get a quote**

Send the following fields:

* Country
* Token
* Fiat

**2.2 Call the`ADD Order` API to place a buy order**

Fields to be sent:

* "country": from Get Country List with Symbol Rate
* "mcId": from Get Merchant List
* "cryptoCurrency": from Get Country List with Symbol Rate
* "fiatCurrency": from Get Country List with Symbol Rate
* "orderAmount": enter the fiat amount
* "orderType": fixed as "BUY"
* "paymentId": from the autoApiFiatPaymentList field in Get Self Data List **2.3 Retrieve an Order ID** After placing the order, use Get Order Details to query the order information and status. The returned information will be:

```
{
    "orderId": "433576705563561984",
    "userId": "1489875904414977024",
    "accountId": "1489875904414977025",
    "cryptoCurrency": "USDT",
    "cryptoLogo": "https://xxxx.png",
    "fiatCurrency": "MXN",
    "orderPrice": "20.07",
    "quantity": "0.4982",
    "fiatAmount": "10",
    "orderType": "BUY",
    "paymentType": 1,
    "orderStatus": 40,
    "hasRefund": 0,
    "hasSelf": 2,
    "orderApprovedTime": "1725849618000",
    "orderTimeFrameMinute": 15,
    "orderConfirmTimestamp": "1725849542",
    "orderExpireTimestamp": "1725850518",
    "completedTime": "1725849542000",
    "mark": "",
    "deptPaymentInfo": {
        "id": 0,
        "name": "Automated SPEI - Arcus",
        "logo": "https://xxxx.png",
        "color": "",
        "realName": "TRUBIT API",
        "paymentFieldList": [
            {
                "index": 1,
                "textType": 1,
                "title": "Cuenta CLABE",
                "promptText": "Cuenta CLABE de 18 d\u00edgitos",
                "maxLimit": 100,
                "text": "706180101615753153",
                "picUrl": [],
                "tempPicUrl": [],
                "isOptional": false,
                "isAccount": true
            },
            {
                "index": 2,
                "textType": 4,
                "title": "Banco",
                "promptText": "",
                "maxLimit": 100,
                "text": "ARCUS",
                "picUrl": [],
                "tempPicUrl": [],
                "isOptional": false,
                "isAccount": false
            }
        ]
    },
    "mcId": 227,
    "mcName": "TRUBIT API",
    "traclingNumber": "",
    "companyName": "API TEST ACCOUNT",
    "createTime": "1725849542000",
    "updateTime": "1725849618000"
}

```

**2.4 Customer Payment**

The customer makes a payment using the information in the paymentFieldList.

**2.5 Poll for Order Status**

After the payment, the customer needs to periodically call Get Order Details to query the status of the order.

***

## Off Ramp Process (Pay-out)

![guide-3](https://667726841-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOcgSwPEO1WP2OtRQfugH%2Fuploads%2Fgit-blob-032c30860bc7faebb2a5eafd2cccacb55f8342a8%2Fblocktrading-user-guide-3.png?alt=media)

### 1. Getting Started

The required information to initiate an off ramp includes: Country, Merchant ID, Token type, Fiat type, the amount of Tokens to sell, Order Type, and Payment ID.

**1.1 Country**

* Call the Get Country List with Symbol Rate API to query the country list.

**1.2 Merchant ID**

* Call Get Merchant List to retrieve the Merchant ID under the UID and record the Merchant ID for the off ramp.

**1.3 Token and Fiat Types**

* Call Get Self Data List to get the supported trading pairs and fiat currencies.
* *Note: This may be replaced with Get Trading Pair List.*

**1.4 Amount of Tokens to Sell**

* Use quantity to input the number of tokens to sell, accurate to two decimal places. *- Note: If the amount exceeds two decimal places, the system will round down and keep two decimal places.*

**1.5 Order Type**

* Set OrderType to SELL for the off ramp.

**1.6 Payment ID**

* If a payment method has not been set up, bind it first:
  1. Retrieve basic information by calling Get Merchant List to get the Merchant ID.
  2. Use Get Self Data List to obtain the list of supported payment methods for each trading pair and record the corresponding Payment ID.
  3. At this step, query the payment method supported by the order and record the Payment ID.
  4. Use Get Payment Config List to get details on all supported payment methods and required fields (including validation expressions).
  5. At this step, use the Payment ID to query the fields required for the selected payment method.
  6. Add the payment method via the Add Payment API. (Refer to payments.fieldList for field requirements.)
  7. If successful, it returns true.
  8. Use Get My Payment Methods API to verify if the payment method has been added successfully.
  9. Once added successfully, you can proceed with the off ramp. Ensure the Payment ID is noted for future off ramps using the same Merchant ID.

### 2. Create the Off Ramp Order

**2.1 Call Get `User Quote` API to get a quote**

Send the following fields to retrieve a quote:

* Country
* Token
* Fiat

**2.2 Use `ADD Order` API to place an off ramp order**

Check if the trading pair supports the Payment ID for the off ramp: *- Note: The merchant must have a successfully bound payment method to initiate the off ramp.*

**2.3 Place the Off Ramp Order**

Send the following fields:

```
    sell_amount = 0.2 （Token amount）
    add_order({
        "country": country,
        "mcId": mc_id,
        "cryptoCurrency":token,
        "fiatCurrency": fiat,
        "quantity":sell_amount,
        "orderType": "SELL",
        "paymentId": payment_id,
    })
```

**2.4 Retrieve an Order ID**

After placing the order, use Get Order Details to query the order information and status.

**2.5 Order Status**

When the order status shows 50 (Paid), it indicates the system has completed the off ramp.

* Once the merchant receives the payment, they can call the Finish Order API to complete the transaction.
* New Requirement: If the order is not confirmed within 30 minutes, the system will automatically complete it. If there are any issues, contact the OTC account manager immediately.

***

### Other Features

**1. Balance Inquiry**

* Use Account Management to check account balances.

**2. Retrieve Order List**

* Use the Get Order List API to retrieve orders, passing time period and status parameters.
  * If no time period is provided, all orders will be returned.
  * If no status is provided, orders of all statuses will be returned. **3. Deposit Token**

Refer to the relevant table to understand the supported tokens and chains, and use the Get Deposit AddressAPI to retrieve deposit addresses.

| Token ID | Chain Type                  |
| -------- | --------------------------- |
| USDT     | ERC20,TRC20,BEP,Polygon     |
| USDC     | ERC20,BEP20,Polygon,Stellar |
| Other    | Contact the account manager |

**4. Special Notes**

* If the customer overpays during an on ramp, contact the TB account manager to initiate a refund via the Broker management backend. The customer’s funds will be refunded through the original payment method.


# Block Trade Api

## General API Information

Endpoint `https://api-otc.trubit.com`

* All endpoints return either a JSON object or array.
* Data is returned in **ascending** order. Oldest first, newest last.
* All time and timestamp related fields are in milliseconds.
* HTTP `4XX` return codes are used for for malformed requests; the issue is on the sender's side.
* HTTP `429` return code is used when breaking a request rate limit.
* HTTP `418` return code is used when an IP has been auto-banned for continuing to send requests after receiving `429` codes.
* HTTP `5XX` return codes are used for internal errors; the issue is on broker's side. It is important to **NOT** treat this as a failure operation; the execution status is **UNKNOWN** and could have been a success.
* Any endpoint can return an ERROR; the error payload is as follows:

```javascript
{
  "code": -1121,
  "msg": "Invalid symbol."
}
```

* Specific error codes and messages defined in another document.
* For `GET` endpoints, parameters must be sent as a `query string`.
* For `POST`, `PUT`, and `DELETE` endpoints, the parameters may be sent as a `query string` or in the `request body` with content type `application/x-www-form-urlencoded`. You may mix parameters between both the `query string` and `request body` if you wish to do so.
* Parameters may be sent in any order.
* If a parameter sent in both the `query string` and `request body`, the `query string` parameter will be used.

### Endpoint security type

* Each endpoint has a security type that determines the how you will interact with it.
* API-keys are passed into the Rest API via the `X-BH-APIKEY` header.
* API-keys and secret-keys **are case sensitive**.
* API-keys can be configured to only access certain types of secure endpoints. For example, one API-key could be used for TRADE only, while another API-key can access everything except for TRADE routes.
* By default, API-keys can access all secure routes.

### SIGNED (TRADE and USER\_DATA) Endpoint security

* `SIGNED` endpoints require an additional parameter, `signature`, to be sent in the `query string` or `request body`.
* Endpoints use `HMAC SHA256` signatures. The `HMAC SHA256 signature` is a keyed `HMAC SHA256` operation. Use your `secretKey` as the key and `totalParams` as the value for the HMAC operation.
* The `signature` is **not case sensitive**.
* `totalParams` is defined as the `query string` concatenated with the `request body`.

### SIGNED Endpoint Examples for POST /openapi/v1/order

Here is a step-by-step example of how to send a vaild signed payload from the Linux command line using `echo`, `openssl`, and `curl`.

| Key       | Value                                                            |
| --------- | ---------------------------------------------------------------- |
| apiKey    | tAQfOrPIZAhym0qHISRt8EFvxPemdBm5j5WMlkm3Ke9aFp0EGWC2CGM8GHV4kCYW |
| secretKey | lH3ELTNiFxCQTmi9pPcWWikhsjO04Yoqw3euoHUuOLC3GYBW64ZqzQsiOEHXQS76 |

| Parameter   | Value         |
| ----------- | ------------- |
| requestBody | {"id":0}      |
| timestamp   | 1538323200000 |

#### Example 1: As a query string

* **queryString:** symbol=ETHBTC\&side=BUY\&type=LIMIT\&timeInForce=GTC\&quantity=1\&price=0.1\&recvWindow=5000\&timestamp=1538323200000
* **requestBodyString:** {"id":0}
* **HMAC SHA256 signature:**

```shell
[linux]$ echo -n "timestamp=1538323200000{"id":0}" | openssl dgst -sha256 -hmac "lH3ELTNiFxCQTmi9pPcWWikhsjO04Yoqw3euoHUuOLC3GYBW64ZqzQsiOEHXQS76"
(stdin)= 5fafd5098eca1e135037f335fe6a9ec6884271cb6933bd7f5ed6a3582f1f0eea
```

* **curl command:**

```shell
(HMAC SHA256)
[linux]$ curl -H "X-BH-APIKEY: tAQfOrPIZAhym0qHISRt8EFvxPemdBm5j5WMlkm3Ke9aFp0EGWC2CGM8GHV4kCYW" -X POST 'https://$HOST?1538323200000&signature=5fafd5098eca1e135037f335fe6a9ec6884271cb6933bd7f5ed6a3582f1f0eea' -d '{"id":0}'
```

## How to obtain apiKey and secretKey

<https://www.trubit.com/new/user/interface>

After creating the apiKey and secretKey, you need to set the IP whitelist.

![图片](https://667726841-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOcgSwPEO1WP2OtRQfugH%2Fuploads%2Fgit-blob-4580796fa37ff127ce074a6b9bc1a2cb2a918b60%2Fimg.png?alt=media) ![图片](https://667726841-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOcgSwPEO1WP2OtRQfugH%2Fuploads%2Fgit-blob-cf841ef58ba594fecc2a2f39c4f9f27649b293b6%2Fimg_1.png?alt=media) ![图片](https://667726841-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOcgSwPEO1WP2OtRQfugH%2Fuploads%2Fgit-blob-d4953ca9ea16e2ea91d7d68dbc29a11434e7fd43%2Fimg_2.png?alt=media)

## Endpoints

### 1. Base Data

#### Get Country List with Symbol Rate

* **Endpoint**: `/openapi/v1/otc/base/symbol_rate/country/list`
* **Method**: GET
* **Request Query Parameters**:
  * `hasValid` (optional, Integer) - Filters countries by validation status.
* **Response**: JSON containing the list of countries with symbol rates.

```
{
  "countryList": [
    {
        "country": "Mexico",  (string: name of the country)
        "abbr": "MX",  (string: abbreviation of the country)
        "flagUrl": "http://xxx"  (string: url of the country flag)
    }
  ]
}
```

Example

```
{
    "countryList": [
        {
            "country": "Mexico",
            "abbr": "MX",
            "flagUrl": "https://xxx.png",
            "buySwitch": 1,
            "sellSwitch": 1
        },
        {
            "country": "Argentina",
            "abbr": "AR",
            "flagUrl": "https://xxx.png",
            "buySwitch": 1,
            "sellSwitch": 1
        },
        {
            "country": "Brazil",
            "abbr": "BR",
            "flagUrl": "https://xxxx.png",
            "buySwitch": 1,
            "sellSwitch": 1
        },
        {
            "country": "Colombia",
            "abbr": "CO",
            "flagUrl": "https://xxxx.png",
            "buySwitch": 0,
            "sellSwitch": 0
        },
        {
            "country": "Hong Kong",
            "abbr": "HK",
            "flagUrl": "https://xxxx.png",
            "buySwitch": 0,
            "sellSwitch": 1
        }
    ]
}

```

#### Get Self Data List

* **Endpoint**: `/openapi/v1/otc/base/symbol/self/list_data`
* **Method**: GET
* **Request Query Parameters**:
  * `country` (string: name of the country)
  * `hasValid` (number: whether to query only valid data \[0: no (default), 1: yes])
* **Response**: JSON containing self data list for symbols.

```
{
        "fiatList": [ (array: list of fiat currencies)
            {
                "name": "MXN", (string: name of the fiat currency)
                "symbolList": [ (string: association list of crypto currencies)
                    "USDT",
                    "MMXN"
                ]
            },
            {
                "name": "ARS",
                "symbolList": [
                    "USDT",
                    "BTC"
                ]
            }
        ],
        "tokenList": [ (array: list of tokens)
            {
                "name": "USDT",  (string: name of the token)
                "symbolList": [ (string: association list of fiat currencies)
                    "MXN",
                    "ARS",
                    "VES",
                    "COP",
                    "TWD",
                    "MYR"
                ]
            },
            {
                "name": "MMXN",
                "symbolList": [
                    "MXN"
                ]
            }   
        ]
    }
```

### 2. Rate Management

#### Get User Quote

* **Endpoint**: `/openapi/v1/otc/rate/user_quote/find`
* **Method**: POST
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Body**:

```
{
  "country": "", (string: name of the country)
  "fiatCurrency": "", (string: name of the fiat currency)
  "cryptoCurrency": "" (string: name of the crypto currency)
}
```

* **Response**: JSON containing user quote information.

```

{
  "hasOpen": 0,  (number: Whether it is open or not[0: no, 1: yes])
  "fiatCurrency": "",  (string: name of the fiat currency)
  "cryptoCurrency": "",  (string: name of the crypto currency)
  "buyRate": 0.0,  (number: buy rate)
  "sellRate": 0.0  (number: sell rate)
}
```

### 3. Payment Management

#### Get Payment Config List

* **Endpoint**: `/openapi/v1/otc/payment/list`
* **Method**: GET
* **Request Query Parameters**:
  * `country` (string: name of the country)
* **Response**: JSON containing the list of payment configurations.

```
 {
        "currencys": [  (array: list of currencies)
            {
                "id": 1, (number: id of the currency)
                "fiatCurrency": "USD" (string: name of the fiat currency)        
            }
        ], 
        "payments": [ (array: list of payments)
            {
                "id": 1,  (number: id of the payment)
                "country": "Mexico", (string: name of the country)
                "paymentType": 0,  (number: type of the payment [0: manual(default), 1: auto])
                "fieldList": [ (array: list of custom fields)
                     {
                        "index": 0, / (number: index of the field)
                        "textType": 1,    (enum: type of the text [1: number, 2: letter, 3: number+letter, 4: string, 5: image])
                        "title": "test",  (string: title of the field)
                        "promptText": "Enter number",  (string: default text of the field)
                        "isAccount": true,  (boolean: whether the field is an account)
                        "isOptional": false, (boolean: whether the field is required [true: required(default), false: optional])
                        "maxLimit": 30,    (number: maximum length of the field)
                        "text": "1234567890" (string: text of the field)
                      }
                 ], 
                "fieldNum": 1,               
                "logo": "http://paypal/123", 
                "paymentName": "Paypal" 
            }
       ]
     }
```

Example Mexico

```

{
    "currencys": [
        {
            "id": 1,
            "fiatCurrency": "MXN"
        },
        {
            "id": 3,
            "fiatCurrency": "ARS"
        }
    ],
    "payments": [
        {
            "id": 58,
            "country": "Mexico",
            "paymentName": "Automated SPEI - Arcus",
            "paymentType": 1,       
            "waitPayMoneyMinute": 0,
            "waitReceiveMoneyMinute": 0,
            "fieldList": [
                {
                    "index": 1,
                    "textType": 1,
                    "title": "Cuenta CLABE",
                    "promptText": "Cuenta CLABE de 18 d\u00edgitos",
                    "maxLimit": 100,
                    "text": "",
                    "picUrl": [],
                    "tempPicUrl": [],
                    "isOptional": false,
                    "isAccount": true
                },
                {
                    "index": 2,
                    "textType": 4,
                    "title": "Banco",
                    "promptText": "",
                    "maxLimit": 100,
                    "text": "",
                    "picUrl": [],
                    "tempPicUrl": [],
                    "isOptional": false,
                    "isAccount": false
                }
            ],
            "fieldNum": 2
        }
    ]
}
```

#### Add Payment

* **Endpoint**: `/openapi/v1/otc/payment/add`
* **Method**: POST
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Body**:

```
{
   "mcId": 1, (number: id of the merchant)
   "country": "Mexico", (string: name of the country)
   "fiatCurrency": "USD",(string: name of the fiat currency)
   "paymentConfigId": 1, (number: id of the payment configuration)
   "paymentLogo": "http://localhost/123",  (string: url of the payment logo)
   "paymentMethodName": "Paypal",  (string: name of the payment method)
   "realName": "xiaoming",  (string: name of the real name)
   "fieldJson": [  (array: list of custom fields)
       {
           "index": 0,  (number: index of the field)
           "textType": 1, (enum: type of the text [1: number, 2: letter, 3: number+letter, 4: string, 5: image])
           "title": "Account",  (string: title of the field)
           "promptText": "",   (string: default text of the field)
           "isAccount": true,  (boolean: whether the field is an account)
           "isOptional": false, (boolean: whether the field is required [true: required(default), false: optional])
           "maxLimit": 30,      (number: maximum length of the field)
           "text": "1234567890",  (string: text of the field)
           "picUrl":["http://localhost/1", "http://localhost/2"], (array: list of image links)
           "tempPicUrl":["http://localhost/1", "http://localhost/2"]             (array: list of temporary image links)
       }
   ],
   "remark": "", (string: remark of the payment method)
}
```

* **Response**: JSON containing the result of the add payment operation.

```
{
    "result": true,
    "msg": "",
    "data": {
        "id": 1  (number: id of the payment)
    }
}
```

#### Get My Payment Methods

* **Endpoint**: `/openapi/v1/otc/payment/my/list`
* **Method**: GET
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Query Parameters**:
  * `mcId` (number: id of the merchant)
  * `country` (optional,string: name of the country)
  * `fiat` (optional,string: name of the fiat currency)
  * `status` (optional,enum: status of the payment method \[0: all(default), 1: valid, 2: authenticating, 3: authentication failed])
  * `currentPage` (optional,number: current page number)
  * `pageSize` (optional,number: number of results per page)
* **Response**: JSON containing the list of user's payment methods.

```
 {
    "currentPage": 1,  (number: current page number)
    "size": 10,  (number: number of results per page)
    "total": 100,  (number: total number of results)
    "record":[ (array: list of payment methods)
      { 
        "id": 1,  (number: id of the payment method)
        "mcId": 1,  (number: id of the merchant)
        "paymentConfigId": 1, (number: id of the base payment method)
        "paymentType": 0,  (enum: type of the payment method [0: manual(default), 1: automatic])
        "country": "Mexico",  (string: name of the country)       
        "fiatCurrency": "USD", (string: name of the fiat currency)
        "paymentMethodName": "xiaoming",  (string: name of the payment method)       
        "realName": "xiaoming", (string: name of the real name)
        "fieldJson": [  (array: list of custom fields)
            {
                "index": 0,  (number: index of the field)
                "textType": 1, (enum: type of the text [1: number, 2: letter, 3: number+letter, 4: string, 5: image])
                "title": "Account",  (string: title of the field)
                "promptText": "",  (string: default text of the field)
                "isAccount": true, (boolean: whether the field is an account)
                "isOptional": false,  (boolean: whether the field is required [true: required(default), false: optional])
                "maxLimit": 30,        (number: maximum length of the field)
                "text": "1234567890",  (string: text of the field)
                "picUrl":["http://localhost/1", "http://localhost/2"],  (array: list of image links)
                "tempPicUrl":["http://localhost/1", "http://localhost/2"],  (array: list of temporary image links)
                "boxSize":"" (string: size of the box)
            }
        ], 
        "status": 1, (enum: status of the payment method [1: normal, 2: authenticating, 3: authentication failed])
        "hasRefundAccount": 0,  (enum: whether the payment method is a refund account [0: no, 1: yes])
        "remark": "",  (string: remark of the payment method)
        "createTime":1234566  (number: creation time of the payment method)
        }        
     ]
}
```

### 4. Merchant Management

#### Get Merchant List

* **Endpoint**: `/openapi/v1/otc/mc/list`
* **Method**: GET
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Query Parameters**:
  * `merchantName` (optional,string: name of the merchant)
  * `email` (optional,string: email)
* **Response**: JSON containing the list of merchants.

```
[
        {    
            "id": 1,  (number: id of the merchant)
            "country": "Mexico",  (string: name of the country)
            "merchantName": "TestMc",  (string: name of the merchant)
            "email": "test@gmail.com",  (string: email)
            "paymentId": 26,  (number: id of the payment method)
            "paymentMethodName": "Paypal",  (string: name of the payment method)
            "fiat": "MXN",  (string: name of the fiat currency)
            "balance": "100.00",  (number: balance of fiat currency)
            "buyLimit":"10000.00",  (number: buy limit of the fiat currency)
            "buyUsed":"2000.00",  (number:  buy used of the fiat currency)
            "sellLimit":"10000.00",  (number: sell limit of the fiat currency)
            "sellUsed":"2000.00"  (number: sell used of the fiat currency)
        }
]
```

#### ADD Merchant Info

* **Endpoint**: `/openapi/v1/otc/mc/add`
* **Method**: POST
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Parameters**:

**Add CLABE Merchant Parameters**

```
{
    "trench": "CLABE", (string: Channel [CVU/CLABE])
    "merchantName": "meap", (string: Merchant Name (Unique))
    "email": "test@gmail.com",(string: Email (Unique))
    "mcType": "COMPANY", (string: Merchant Type [PERSONAL, COMPANY])
    "remark": "xiaoming",  (string: Remark)  
      
    "curp": "xiaoming",  (string: CURP(curp or rfc choose one to fill in))
    "rfc": "xiaoming",  (string: RFC(curp or rfc choose one to fill in))
    "cardIssueDate": "xiaoming",  (string: Card Issue Date (yyyy-MM-dd))
    "cardExpireDate": "xiaoming",  (string: Card Expiry Date(yyyy-MM-dd))
    "address": "xiaoming",  (string: Address)
    "city": "xiaoming",  (string: City)
    "state": "xiaoming",  (string: State )
    "zipCode": "xiaoming",  (string: Zip Code)
    "phone": "xiaoming",  (string: Phone)
        
    "companyName": "xiaoming",  (string: Company Name (Fill in when mcType value is COMPANY))
    "aliasName": "xiaoming",  (string: Alias Name (Fill in when mcType value is COMPANY))
    "companyType": "xiaoming",  (string: Company Type (Fill in when mcType value is COMPANY))
    "incorporationDate": "xiaoming",  (string: Incorporation Date (yyyy-MM-dd) [Fill in when mcType value is COMPANY])
    
    "birthday": "xiaoming",  (string: Birthday (yyyy-MM-dd) [Fill in when mcType value is PERSONAL])
    "name": "xiaoming",  (string: Name (Fill in when mcType value is PERSONAL))
    "fatherSurname": "xiaoming",  (string: Father's Surname (Fill in when mcType value is PERSONAL))
    "motherSurname": "xiaoming"  (string: Mother's Surname (Fill in when mcType value is PERSONAL))  
}
```

**Add CVU Merchant Parameters**

```
{
    "trench": "CLABE", (string: Channel [CVU/CLABE])
    "merchantName": "meap", (string: Merchant Name (Unique))
    "email": "test@gmail.com",(string: Email (Unique))
    "mcType": "PERSONAL", (string: Merchant Type [PERSONAL, COMPANY])
    "remark": "xiaoming",  (string: Remark)  
      
    "cuit": "20315085801",  (string: CUIT)
    "name": "xiaoming",  (string: Full Name (Remove Diacritics))
}
```

* **Response**: JSON containing the result of the add merchant operation.

```
{
    "result": true,
    "msg": "",
    "data": {
        "id": 1  (number: id of the merchant)
    }
}
```

#### Get Merchant Transfer List

* **Endpoint**: `/openapi/v1/otc/mc/tran/list`
* **Method**: GET
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Parameters**:
  * `startTime` (number: optional, timestamp of the start time(millisecond))
  * `endTime` (number: optional, timestamp of the end time(millisecond))
  * `mcSettingsId` (number, optional, id of the merchant)
  * `type` (number, optional, enum: type \[0: all(default), 1: deposit, 2: withdraw, 3: Online Refund, 5: Offline Refund])
  * `status` (number, optional, enum: status \[0: all(default), 1: init, 2: completed, 3: canceled])
  * `currentPage` (number,default 1)
  * `pageSize` (number,default 10, max 1000)
* **Response**: JSON containing the list of orders.

```
{
    "currentPage": 1,  (number: current page number)
    "size": 10, (number: number of results per page)
    "total": 100, (number: total number of results)   
    "record":[ (array: list of orders)
        {
            "id": "482242167403036672", (number: id of the order)
            "userId": "1172300499489225472", (number: id of the user)
            "orderId": "482242123023106048", (number: id of the order)
            "bankOrderId": "M67REZ8NPD4L65RN4KVGOP", (string: name of the bank order id)
            "country": "Argentina", (number: id of the merchant)
            "mcSettingsId": 4, (number: id of the merchant)
            "merchantName": "AR. Tracey Ernser", (string: name of the merchant name)
            "fiat": "ARS", (string: name of the fiat currency)
            "amount": "1096.74", (decimal: order amount)
            "type": 2, (enum: order status [1: deposit, 2: withdraw, 3: Online Refund, 5: Offline Refund])
            "status": 2, (enum: status [1: init, 2: completed, 3: canceled])
            "accountNumber": "0000775900000000000123",
            "bankName": "Ar Auto API", (string: name of the bank name)
            "createTime": "1737452292000", (string: timestamp of the create time(millisecond))
            "updateTime": "1737452344000" (string: timestamp of the update time(millisecond))
        }
     ]
    }
}
```

### 5. Order Management

#### Get Order List

* **Endpoint**: `/openapi/v1/otc/order/list`
* **Method**: GET
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Parameters**:
  * `currentPage` (number,default 1)
  * `pageSize` (number,default 10)
  * `isPending` (optional, boolean: whether the order is pending \[true: pending, false: not pending])
* **Response**: JSON containing the list of orders.

```
{
    "currentPage": 1,  (number: current page number)
    "size": 10, (number: number of results per page)
    "total": 100, (number: total number of results)
    "pendingOrders": 4 (number: number of pending orders)
    "record":[ (array: list of orders)
        {
        "orderId": "419798134177140736",  (number: id of the order)
        "userId": "1434127291173059584",  (number: id of the user)
        "accountId": "1434127291173059585",  (number: id of the user account)
        "cryptoCurrency": "USDT", (string: name of the crypto currency)
        "cryptoLogo": "https://xxx.png",  (string: logo of the crypto currency)
        "fiatCurrency": "MXN",  (string: name of the fiat currency)
        "orderPrice": "700.00",  (decimal: order price)
        "quantity": "10.00",  (decimal: order quantity)
        "fiatAmount": "7000.00", (decimal: order amount)
        "orderType": "SELL ",L  (enum: order type [BUY: buy, SELL: sell])
        "orderStatus": "30",  (enum: order status [10: pending, 30: approved, 31: support documents pending, 40: pending payment, 50: paid, 60: released, 70: canceled, 80: rejected by self])
        "deptPaymentMethodName": "Mercadopago (Mexico)",  (string: name of the merchant payment method)
        "deptPaymentMethodColor": "#4658C1", (string: color of the merchant payment method)
        "orderApprovedTime": "1722229752000", (number: timestamp of the order approved)
        "hasRefund": 1, (enum: whether the order is a refund order [0: no, 1: yes])
        "hasSelf": 1,  (enum: whether the order is a self order [0: no, 1: yes])
     ]
    }
}
```

#### Get Order Detail

* **Endpoint**: `/openapi/v1/otc/order/detail`
* **Method**: GET
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Parameters**:
  * `orderId` (number: id of the order)
  * `clientId` (string: id of the client)
* **Response**: JSON containing the details of the specified order.

```
{
    "orderId": "1", (number: id of the order)
    "clientId": "ebab8a9663704e7cbbeb",  (string: id of the client)
    "userId": "1", (number: id of the user)
    "accountId": "1", (number: id of the user account)
    "cryptoCurrency": "token", (string: name of the crypto currency)
    "cryptoLogo": "token logo", (string: logo of the crypto currency)
    "fiatCurrency": "MXN", (string: name of the fiat currency)
    "orderPrice": "1", (decimal: order price)
    "quantity": "1", (decimal: order quantity)
    "fiatAmount": "1", (decimal: order amount)
    "orderType": "BUY", (enum: order type [BUY: buy, SELL: sell])
    "orderStatus": "10", (enum: order status [10: pending, 30: approved, 31: support documents pending, 40: pending payment, 50: paid, 60: released, 70: canceled, 80: rejected by self])
    "orderApprovedTime": "", (number: timestamp of the order approved)
    "orderTimeFrameMinute": "", (number: time frame of the payment (minute))
    "orderConfirmTimestamp": "", (number: timestamp of the order confirmed (second))
    "orderExpireTimestamp": "", (number: timestamp of the order expired (second))
    "mark": "",                (string: remark)
    "mcId": 1,(number: id of the merchant)
    "mcName": "pel",(string: name of the merchant)
    "traclingNumber": "987654321",(number: transaction number)
    "companyName": "System",(string: name of the company)
    "hasRefund": 1,(enum: whether the order is a refund order [0: no, 1: yes])
    "hasSelf": 1,(enum: whether the order is a self order [0: no, 1: yes])
    "paymentType": 1,(enum: type of the payment method [0: manual(default), 1: automatic])
    "deptPaymentInfo": { (object: merchant payment method information)
        "id": "1", (number: id of the payment method)
        "name": "Paypal",(string: name of the payment method)
        "logo": "http://localhost/123",(string: logo of the payment method)
        "color": "",(string: color of the payment method)
        "paymentFieldList": [  (array: list of custom fields)
            {
                "index": 0,(number: index of the field)
                "textType": 1,(enum: type of the text [1: number, 2: letter, 3: number+letter, 4: string, 5: image])
                "title": "Account",(string: title of the field)
                "promptText": "",(string: default text of the field)
                "isAccount": true,(boolean: whether the field is an account)
                "isOptional": false,(boolean: whether the field is required [true: required(default), false: optional])
                "maxLimit": 30,(number: maximum length of the field)
                "text": "1234567890",(string: text of the field)
                "picUrl":["http://localhost/1", "http://localhost/2"],(array: list of image links)
                "tempPicUrl":["http://localhost/1", "http://localhost/2"],              (array: list of temporary image links)
            }
        ]
     }, 
     "userPaymentInfo": { (object: user payment method information)
        "id": "1", (number: id of the payment method)
        "name": "Paypal",(string: name of the payment method)
        "logo": "http://localhost/123",(string: logo of the payment method)
        "color": "",(string: color of the payment method)
        "paymentFieldList": [  (array: list of custom fields)
            {
                "index": 0,(number: index of the field)
                "textType": 1,(enum: type of the text [1: number, 2: letter, 3: number+letter, 4: string, 5: image])
                "title": "Account",(string: title of the field)
                "promptText": "",(string: default text of the field)
                "isAccount": true,(boolean: whether the field is an account)
                "isOptional": false,(boolean: whether the field is required [true: required(default), false: optional])
                "maxLimit": 30,(number: maximum length of the field)
                "text": "1234567890",(string: text of the field)
                "picUrl":["http://localhost/1", "http://localhost/2"],(array: list of image links)
                "tempPicUrl":["http://localhost/1", "http://localhost/2"],(array: list of temporary image links)
            }
        ]
     }
}
```

Buy Order Example

```
{
    "orderId": "433576705563561984",
    "userId": "1489875904414977024",
    "accountId": "1489875904414977025",
    "cryptoCurrency": "USDT",
    "cryptoLogo": "https://xxxx.png",
    "fiatCurrency": "MXN",
    "orderPrice": "20.07",
    "quantity": "0.4982",
    "fiatAmount": "10",
    "orderType": "BUY",
    "paymentType": 1,
    "orderStatus": 40,
    "hasRefund": 0,
    "hasSelf": 2,
    "orderApprovedTime": "1725849618000",
    "orderTimeFrameMinute": 15,
    "orderConfirmTimestamp": "1725849542",
    "orderExpireTimestamp": "1725850518",
    "completedTime": "1725849542000",
    "mark": "",
    "deptPaymentInfo": {
        "id": 0,
        "name": "Automated SPEI - Arcus",
        "logo": "https://xxxx.png",
        "color": "",
        "realName": "HONGYI TANG API",
        "paymentFieldList": [
            {
                "index": 1,
                "textType": 1,
                "title": "Cuenta CLABE",
                "promptText": "Cuenta CLABE de 18 d\u00edgitos",
                "maxLimit": 100,
                "text": "706180101615753153",
                "picUrl": [],
                "tempPicUrl": [],
                "isOptional": false,
                "isAccount": true
            },
            {
                "index": 2,
                "textType": 4,
                "title": "Banco",
                "promptText": "",
                "maxLimit": 100,
                "text": "ARCUS",
                "picUrl": [],
                "tempPicUrl": [],
                "isOptional": false,
                "isAccount": false
            }
        ]
    },
    "mcId": 227,
    "mcName": "HONGYI TANG API",
    "traclingNumber": "",
    "companyName": "API TEST ACCOUNT",
    "createTime": "1725849542000",
    "updateTime": "1725849618000"
}
```

Sell Order Example

```
{
    "orderId": "433592805818896384",
    "userId": "1489875904414977024",
    "accountId": "1489875904414977025",
    "cryptoCurrency": "USDT",
    "cryptoLogo": "https://xxx.png",
    "fiatCurrency": "MXN",
    "orderPrice": "19.91",
    "quantity": "0.2",
    "fiatAmount": "3.98",
    "orderType": "SELL",
    "paymentType": 1,
    "orderStatus": 60,
    "hasRefund": 0,
    "hasSelf": 2,
    "orderApprovedTime": "1725853455000",
    "orderTimeFrameMinute": 240,
    "orderConfirmTimestamp": "1725853380",
    "orderExpireTimestamp": "1725867854",
    "completedTime": "1725853833000",
    "mark": "",
    "deptPaymentInfo": {
        "id": 58,
        "name": "Automated SPEI - Arcus",
        "logo": "https://xxx.png",
        "color": "",
        "realName": "",
        "paymentFieldList": []
    },
    "userPaymentInfo": {
        "id": 221,
        "name": "Automated SPEI - Arcus",
        "logo": "https://xxx.png",
        "color": "",
        "realName": "test-api-add",
        "paymentFieldList": [
            {
                "index": 1,
                "textType": 1,
                "title": "Cuenta CLABE",
                "promptText": "Cuenta CLABE de 18 d\u00edgitos",
                "maxLimit": 100,
                "text": "012180015049733082",
                "picUrl": [],
                "tempPicUrl": [],
                "isOptional": false,
                "isAccount": true
            },
            {
                "index": 2,
                "textType": 4,
                "title": "Banco",
                "promptText": "",
                "maxLimit": 100,
                "text": "BBVA",
                "picUrl": [],
                "tempPicUrl": [],
                "isOptional": false,
                "isAccount": false
            }
        ]
    },
    "mcId": 227,
    "mcName": "HONGYI TANG API",
    "traclingNumber": "2024090890706GA27Y4BFDRDHAD3X",
    "companyName": "API TEST ACCOUNT",
    "createTime": "1725853381000",
    "updateTime": "1725853833000"
}

```

#### Finish Order

* **Endpoint**: `/openapi/v1/otc/order/finish`
* **Method**: POST
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Body**:

```
{
    "orderId": 1123123123,  (number: id of the order)
}
```

* **Response**: JSON containing the result of the order finish.

```
{
  "result": true,
  "msg": ""
}
```

#### Add Order

* **Endpoint**: `/openapi/v1/otc/order/add`
* **Method**: POST
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Body**:

```
{       
    "country":"Mexico", (string: name of the country)
    "clientId":"ebab8a9663704e7cbbeb",  (optional, string: id of the client (Unique))
    "mcId":3,  (number: id of the merchant)
    "cryptoCurrency":"USDT", (string: name of the crypto currency)
    "fiatCurrency":"MXN", (string: name of the fiat currency)
    "quantity":100.00, (decimal: order quantity)
    "orderAmount":1000.00, (decimal: order amount)
    "orderType":"SELL",(enum: order type [BUY: buy, SELL: sell])
    "paymentId":"91",  (number: id of the payment method)
}       
```

* **Response**: JSON containing the result of the add order operation.

```
{
    "orderId": 1123123123,  (number: id of the order)
}
```

#### Order Invoice Upload

* **Endpoint**: `/openapi/v1/otc/pic/upload`
* **Method**: POST
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Parameters**: order status is \[31: support documents pending], Use this interface to upload invoices
  * `orderId` (number: id of the order)
  * `files` (file: Upload multiple file, This parameter does not participate in signature. numbwr max 5. Maxinum upload file size 5MB. format support \[jpg,png,jpeg,pdf])
* **Response**: JSON containing the result of the order invoice upload.

```
{
  "result": true,
  "msg": "SUCCESS"
}
```

### 6. Deposit Management

#### Get Deposit Address

* **Endpoint**: `/openapi/v1/otc/depositAddress`
* **Method**: GET
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Request Query Parameters**:
  * `tokenId` (String) - ID of the token
  * `chainType` (optional, String) - Type of the blockchain (default: "")
* **Response**: JSON containing the deposit address.

```
{
    "allowDeposit": false, (boolean: whether the deposit is allowed)
    "address": "", (string: address of the deposit)
    "addressExt": "", (string: address tag)
    "minQuantity": "", (string: minimum amount of the deposit)
    "needAddressTag": false, (boolean: whether the address tag is required)
    "requiredConfirmNum": 0, (number: required confirmation number)
    "canWithdrawConfirmNum": 0, (number: maximum confirmation number)
    "tokenType": "" (string: type of the token)
}
```

Example tokenId = USDT ,chainType = ERC20

```
{
    "allowDeposit": true,
    "address": "0x895f6ab44fb0da1102ab1beb4995e42d74***41",
    "addressExt": "",
    "minQuantity": "5",
    "needAddressTag": false,
    "requiredConfirmNum": 64,
    "canWithdrawConfirmNum": 64,
    "tokenType": "ERC20_TOKEN"
}
```

| Token Id | ChainType |
| -------- | --------- |
| USDT     | ERC20     |
| USDT     | TRC20     |

### 7. Account Management

#### Get Account Info

* **Endpoint**: `/openapi/v1/otc/account`
* **Method**: GET
* **Authorization**: Requires signature and account verification
* **Headers**: Requires signature
  * `X-BH-APIKEY` (string: API key)
* **Response**: JSON containing account information.

```
{
  "accountId": 0, (number: id of the account)
  "accountName": "", (string: name of the account)
  "accountType": 0, (number: type of the account)
  "accountIndex": 0, (number: index of the account)
  "canTrade": false, (boolean: whether the account can trade)
  "canDeposit": false, (boolean: whether the account can deposit)
  "canWithdraw": false, (boolean: whether the account can withdraw)
  "balances": [
    {
      "asset": "", (string: name of the asset)
      "assetId": "", (string: id of the asset)
      "assetName": "", (string: name of the asset)
      "total": "", (string: total amount of the asset)
      "free": "", (string: free amount of the asset)
      "locked": "" (string: locked amount of the asset)
    }
  ],
  "updateTime": 0 (number: update time of the account)
}
```

Example

```
{
    "balances": [
        {
            "asset": "USDT",
            "assetId": "USDT",
            "assetName": "USDT",
            "total": "0.2982",
            "free": "0.2982",
            "locked": "0"
        }
    ]
}
```

### 8. Webhooks

#### Order Notice Info

* **Method**: POST
* **Authorization**: Callback message authentication, The joint commission trubit platform obtains the public key.
* **Headers**: Requires signature
  * `signature` (string: To verify that a webhook request is coming from trubit, you can use the signature header. The value of the header is a RSA-SHA256 signature of the request body, Use hexadecimal encoding.)
* **Request Body**:

```
{
    "orderId": "473130522693193728", (number: id of the order)
    "clientId": "ebab8a9663704e7cbbeb",  (string: id of the client)
    "userId": "455472", (number: id of the user)
    "mcSettingsId": "10", (number: id of the merchant)
    "orderType": "SELL", (enum: order type [BUY: buy, SELL: sell])
    "fiatCurrency": "MXN", (string: name of the fiat currency)
    "orderAmount": "99", (decimal: order amount)
    "fiatFee": "0", (decimal: fiat fee)
    "cryptoCurrency": "USDT", (string: name of the crypto currency)
    "quantity": "5", (decimal: order quantity)
    "orderPrice": "19.8158", (decimal: order price)
    "orderStatus": "60", (enum: order status [10: pending, 30: approved, 40: pending payment, 50: paid, 60: released, 70: canceled])
    "createTime": "1735279907000", (string: timestamp of the create time(millisecond))
    "updateTime": "1735280582000", (string: timestamp of the update time(millisecond))
    "timestamp": "1735280582453" (string: timestamp of the update time(millisecond))
}
```

* **Response**:

```
{
    "callbackStatus": "SUCCESS", (string: callback status, If SUCCESS is returned, the message is successfully notified)
}
```


# Other


# Welcome to TruBit-Python

An official Python implementation of the lastest Open API for Broker.

## Install

```bash
pip install broker-trade-client
```

or download from github

Note: pip install may be fail. We are working on fix this. if so, just download from github

## Usage

#### REST API

Init broker client:

```python
b = BrokerClient(entry_point='', api_key='', secret='')
```

Init broker options client:

```python
b = BrokerOptionClient(entry_point='', api_key='', secret='')
```

Init broker contract client:

```python
b = BrokerContractClient(entry_point='', api_key='', secret='')
```

Request with proxies:

```python
proxies = {
  "http": "http://ip:port",
  "https": "http://ip:port",
}

b = BrokerClient(entry_point='', api_key='', secret='', proxies=proxies)
```

#### Web Socket

**Init**

Init broker websocket client:

```python
client = BrokerWss(entry_point='', rest_entry_point='', api_key='', secret='')
```

**Subscribe**

Subscribe trades:

```python
client.subscribe_to_trades(symbol='BTCUSDT', callback=handler)
```

Subscribe Kline/Candlestick:

```python
client.subscribe_to_kline(symbol='BTCUSDT', interval='5m', callback=handler)
```

Subscribe market tickers:

```python
client.subscribe_to_realtimes(symbol='BTCUSDT,ETHUSDT', callback=handler)
```

Subscribe book depth tickers:

```python
client.subscribe_to_depth(symbol='BTCUSDT', callback=handler)
```

Subscribe user data:

```python
client.user_data_stream(callback=handler)
```

**Start**

Start websocket thread

```python
client.start()
```

## API List

### Public API

#### ping

```python
b.ping()
```

#### time

```python
b.time()
```

#### broker info

```python
b.broker_info()
```

#### depth

```python
b.depth('BTCUSDT')
```

#### trades

```python
b.trades('BTCUSDT')
```

#### klines

```python
b.klines('BTCUSDT')
```

#### ticker 24hr

```python
b.ticker_24hr('BTCUSDT')
```

### Private API

#### new order

```python
 b.order_new(symbol='BTCUSDT', side='BUY', type='LIMIT', quantity='0.01', price='1000', timeInForce='GTC')
```

#### get order

```python
b.order_get(order_id='')
```

#### cancel order

```python
b.order_cancel(order_id='')
```

#### open orders

```python
b.open_orders()
```

#### history orders

```python
b.history_orders()
```

#### account

```python
b.account()
```

#### my trades

```python
b.my_trades()
```

#### deposit orders

```python
b.deposit_orders()
```

## Examples

* [examples.py](https://github.com/Galactic-Tech/GitBook/blob/main/Other/examples/examples.py)
* [option-examples.py](https://github.com/Galactic-Tech/GitBook/blob/main/Other/examples/option-examples.py)
* [contract-examples.py](https://github.com/Galactic-Tech/GitBook/blob/main/Other/examples/contract-examples.py)
* [ws-examples.py](https://github.com/Galactic-Tech/GitBook/blob/main/Other/examples/ws-examples.py)


