# API Doc


# General API Information

### General API Information

* The following base endpoint is available.&#x20;
  * **<https://trade.mn/api>**
* Timestamp related fields are in **milliseconds**.


# API Key Setup

* Some endpoints will require an API Key.&#x20;
* Once API key is created, it is recommended to set IP restrictions on the key for security reasons.
* **Never share your API key/secret key with ANYONE.**


# HTTP Return Codes

* HTTP `4XX` return codes are used for malformed requests; the issue is on the sender's side.
* HTTP `403` return code is used when the WAF Limit (Web Application Firewall) has been violated.
* HTTP `409` return code is used when a cancelReplace order partially succeeds. (i.e. if the cancellation of the order fails but the new order placement succeeds.)
* 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 Trade.mn's side.


# General Information on Endpoints

* For `GET` endpoints, parameters must be sent as a `query string`.
* For `POST`, `PUT`, and `DELETE` endpoints, the parameters must be sent as a `request body` with content type `application/x-www-form-urlencoded`.
* Parameters may be sent in any order.


# Endpoint security type

* Each endpoint has a security type that determines how you will interact with it. This is stated next to the NAME of the endpoint.
* If no security type is stated, assume the security type is NONE.
* API-keys are passed into the Rest API via the `X-Apikey` header.
* 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. |
| WALLET        | Endpoint requires sending a valid API-Key and signature. |
| USER\_DATA    | Endpoint requires sending a valid API-Key.               |

##


# SIGNED (TRADE) Endpoint security

* `SIGNED` endpoints require an additional header `X-Signature`.
* Endpoints use `HMAC SHA256` signatures. The `HMAC SHA256 signature` is a keyed `HMAC SHA256` operation..


# 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.


# Public API Endpoints


# Terminology

These terms will be used throughout the documentation, so it is recommended especially for new users to read to help their understanding of the API.

* `base asset` refers to the asset that is the `quantity` of a symbol. For the symbol TRD/MNT, TRD would be the `base asset`.
* `quote asset` refers to the asset that is the `price` of a symbol. For the symbol TRD/MNT, MNT would be the `quote asset`.


# ENUM definitions

**Account and Symbol Permissions (permissions):**

* `SPOT`

**Order status (status):**

| Status             | Description                                                 |
| ------------------ | ----------------------------------------------------------- |
| `NEW`              | The order has been accepted by the engine.                  |
| `PARTIALLY_FILLED` | A part of the order has been filled.                        |
| `FILLED`           | The order has been completed.                               |
| `CANCELED`         | The order has been canceled by the user.                    |
| `PENDING_CANCEL`   | Currently unused                                            |
| `REJECTED`         | The order was not accepted by the engine and not processed. |

**Order types (orderTypes, type):**

* `LIMIT`
* `MARKET`

**Order side (side):**

* `BUY`
* `SELL`


# General endpoints

#### Exchange information

```
GET /api/v3/exchangeInfo
```

Current exchange symbol information. (Бирж дээр арилжаалагдаж буй хослолуудын мэдэээл)

**Response:**

```javascript
{
  "symbols": [
    {
      "baseAssetCode": "TRD",
      "quoteAssetCode": "MNT",
      "commission": 0.02,
      "baseFraction": 3,
      "quoteFraction": 3,
      "symbol": "TRD/MNT"
    },
    {
      "baseAssetCode": "BTC",
      "quoteAssetCode": "MNT",
      "commission": 0.02,
      "baseFraction": 8,
      "quoteFraction": 2,
      "symbol": "BTC/MNT"
    }
  ]
}
```


# Market Data endpoints


# Order book (USER\_DATA)

```
GET /api/v3/depth
```

Get order book. (Захиалгын сангийн мэдэээл)

**Parameters:**

| Name      | Type   | Mandatory | Description |
| --------- | ------ | --------- | ----------- |
| symbol    | STRING | YES       |             |
| timestamp | LONG   | YES       |             |

**Response:**

```javascript
{
  "sell": {
    "10": 100, // price: quantity
    "11": 11
  },
  "buy": {
    "1": 25000,
    "5": 2121,
    "6": 5000
  }
}
```


# Recent trades list (USER\_DATA)

```
GET /api/v3/trades
```

Get recent trades. (Сүүлд биелсэн хэлцлүүд)

**Parameters:**

| Name      | Type   | Mandatory | Description |
| --------- | ------ | --------- | ----------- |
| symbol    | STRING | YES       |             |
| timestamp | LONG   | YES       |             |

**Response:**

```javascript
[
  {
    "quantity": 1000,
    "price": 2.1,
    "timestamp": 1691987568000
  }
];
```


# Trading endpoints


# New order (TRADE)

```
POST /api/v3/order
```

Send in a new order. (Захиалга оруулах)

**Parameters:**

| Name      | Type    | Mandatory | Description |
| --------- | ------- | --------- | ----------- |
| symbol    | STRING  | YES       |             |
| side      | ENUM    | YES       |             |
| type      | ENUM    | YES       |             |
| quantity  | DECIMAL | NO        |             |
| price     | DECIMAL | NO        |             |
| total     | DECIMAL | NO        |             |
| timestamp | LONG    | YES       |             |

Some additional mandatory parameters based on order `type`:

| Type     | Additional mandatory parameters | Additional Information                                                                                                     |
| -------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `LIMIT`  | `quantity`, `price`             |                                                                                                                            |
| `MARKET` | `quantity` or `total`           | <p>When side is <code>SELL</code> quantity param is required.<br>When side is <code>BUY</code> total param is required</p> |

**Response RESULT:**

```javascript
{
  "status": true,
  "code": "0000",
  "msg": [
    "Амжилттай"
  ],
  "data": {
    "id": "faa1074c-ed19-4674-ba30-9844a31bfdd3",
    "symbol": "TRD/MNT",
    "side": "BUY",
    "price": 6,
    "qty": 1000,
    "total": 6000,
    "created_at": "2006-01-02T13:39:59.97487+08:00",
    "side_name": "Авах"
  }
}
```


# Cancel order (TRADE)

```
DELETE /api/v3/order
```

Cancel an active order. (Захиалга цуцлах)

**Parameters:**

| Name      | Type | Mandatory | Description |
| --------- | ---- | --------- | ----------- |
| id        | UUID | YES       |             |
| timestamp | LONG | YES       |             |

**Response:**

```javascript
{
  "status": true,
  "code": "0000",
  "msg": [
    "Амжилттай"
  ]
}
```


# Current open orders (TRADE)

```
GET /api/v3/order/active
```

Get all open orders on a symbol. **Careful** when accessing this with no symbol. (Идэвхтэй захиалгын жагсаалт)

**Parameters:**

| Name      | Type   | Mandatory | Description |
| --------- | ------ | --------- | ----------- |
| symbol    | STRING | NO        |             |
| timestamp | LONG   | YES       |             |

**Response:**

```javascript
[
  {
    "id": "a3f906e5-37ae-44fb-8f04-7016ce1fea1d",
    "symbol": "TRD/MNT",
    "side": "SELL",
    "price": "10",
    "qty": "100",
    "execQty": "0",
    "total": "1000",
    "createdAt": "2006-01-02T17:23:40.583463+08:00"
  },
];
```


# Trade history (TRADE)

```
GET /api/v3/order/trade/history
```

Get all account filled orders. (Арилжааны түүх)

**Parameters:**

| Name      | Type   | Mandatory | Description             |
| --------- | ------ | --------- | ----------------------- |
| symbol    | STRING | NO        |                         |
| page      | INT    | NO        | Default: 0              |
| size      | INT    | NO        | Default: 100; max 1000. |
| timestamp | LONG   | YES       |                         |

**Response:**

```javascript
{
  "items": [
    {
      "id": "acb59a7f-62c6-40ae-81e5-c92fb0223352",
      "orderId": "acb59a7f-62c6-40ae-81e5-c92fb0223351",
      "tradeAt": "2006-01-02T17:08:05.279+08:00",
      "symbol": "TRD/MNT",
      "side": "BUY",
      "sideName": "Авах",
      "price": "11",
      "quantity": "100",
      "total": "1100",
      "commission": "0.02",
      "commissionAssetCode": "TRD"
    },
  ],
  "page": 0,
  "size": 100,
  "total_pages": 1,
  "total": 1
}
```


# Wallet endpoints


# Wallet balance (WALLET)

```
GET /api/v3/wallet/balance
```

Get all asset information and balance. (Хэтэвчний үлдэгдэл болон койны мэдээлэл)

**Parameters:**

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

**Response:**

```javascript
{
  "status": true,
  "code": "0000",
  "msg": [
    "Амжилттай"
  ],
  "data": {
    "acc": {
      "MAIN": {
        "walletCode": "SPOT",
        "transfer": 15999888.878080001,
        "assetAccs": [
          {
            "asset": "TRD",
            "free": "999879.61538",
            "freeze": "0",
            "locked": "110.9",
            "savings": "0",
            "freeTransfer": "5999277.69228",
            "freezeTransfer": "0",
            "lockedTransfer": "665.4",
            "savingsTransfer": "0",
            "isDeposit": true,
            "isWithdraw": true,
            "isTrade": true,
            "isSaving": true,
            "name": "Digital Exchange Coin"
          }
        ]
      }
    }
  }
}
```


# Wallet balance by asset (WALLET)

```
GET /api/v3/wallet/balance
```

Get single asset balance by code. (Койны үлдэгдэл)

**Parameters:**

| Name      | Type | Mandatory | Description |
| --------- | ---- | --------- | ----------- |
| timestamp | LONG | YES       |             |
| code      | TRD  | YES       |             |

**Response:**

```javascript
{
  "status": true,
  "code": "0000",
  "msg": [
    "Амжилттай"
  ],
  "data": {
    "free": "510.7858000000000001"
  }
}
```


# Websocket (Socket.io)

* The base endpoint is: **wss\://trade.mn:8989**

#### Join to a stream (TRD/MNT хослол руу холбогдох)

* Request

  ```javascript
  [
      "join",
      "TRD/MNT"
  ]
  ```

#### Change room (TRD/MNT хослолоос холболт салгаж BTC/MNT руу холбогдох)

* Request

  ```javascript
  [
      "change_room",
      "TRD/MNT",
      "BTC/MNT"
  ]
  ```

#### Order book (Авах, зарах захиалгын сангийн мэдээллийг хүлээн авах)

* Response

  ```javascript
  [
    "orders",
    {
      "sell": {
        "0.176": 501724.147, // price: quantity
        "0.177": 733316.15939547,
        "0.178": 104528.83,
        "0.179": 311643.429,
        "0.18": 17154859.47544444
      },
      "buy": {
        "0.144": 100201,
        "0.145": 110377.172,
        "0.146": 100201,
        "0.147": 100201,
        "0.148": 100201
      }
    }
  ]
  ```

#### Trades (Биелсэн захиалгын мэдээллийг хүлээн авах)

* Response

  ```javascript
  [
    "trades",
    [
      {
        "quantity": 41412.285,
        "price": 0.176,
        "timestamp": 1692937234298
      },
      {
        "quantity": 4587.715,
        "price": 0.176,
        "timestamp": 1692937234298
      },
    ]
  ]
  ```

#### Buy order update (Тухайн үнийн түвшин дээр байгаа тоо ширхэгийг мэдээллийг хүлээн авах - Авах захиалга)

* Response

  ```javascript
  [
    "buy_order_update",
    {
      "3512.1": 496.900256 // price: quantity
    }
  ]
  ```

#### Sell order update (Тухайн үнийн түвшин дээр байгаа тоо ширхэгийг мэдээллийг хүлээн авах - Зарах захиалга)

* Response

  ```javascript
  [
    "sell_order_update",
    {
      "3512.1": 496.900256 // price: quantity
    }
  ]
  ```

#### Matched order (Хэлцэл биелсэн мэдээллийг хүлээн авах)

* Response

  ```javascript
  [
    "matched_order",
    {
      "id": "e991afa9-404b-42a9-ab96-d2e23cfbdf68",
      "takerId": "e8c34e44-2449-4e3f-9935-7d31d4a93afc",
      "quantity": 13.418084,
      "price": 3513,
      "timestamp": 1692946624550
    }
  ]
  ```


# Error Codes

Any endpoint can return an ERROR

Sample Payload below:

```javascript
{
  "status": false,
  "code": "4001",
  "msg": [
    "API key олдсонгүй"
  ]
}
```

## Error codes for Trade.mn

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
{
  "status": false,
  "code": "4001",
  "msg": [
    "API key олдсонгүй"
  ]
}
```

**-4001 Validation error**

**-4004 Body parse error**

**-0014 Unavailable error**


# Postman Collections

* There is now a Postman collection containing the API endpoints for quick and easy use.
* This is recommended for new users who want to get a quick-start into using the API.
* For more information please refer to this page: [Trade.mn API Postman](https://documenter.getpostman.com/view/3270216/2s9Y5Wwhzm)


