# REST APIs Documentation

## Introduction

Defx offers both public and private REST APIs.

Public REST APIs provide market data such as:

* markets being traded
* price data for each market
* trade history

Private REST APIs allow you to manage both orders and funds:

* place and cancel orders
* see your currently active orders
* see your trading history
* see your currently active positions<br>

***

## Base URLs

### Testnet

The Base URL for testnet is: api.testnet.defx.com

### Mainnet

The Base URL for testnet is: api.defx.com

***

## Authentication <a href="#authentication" id="authentication"></a>

### **Public APIs**

Public APIs can be accessed without authentication using the GET method, where request parameters are embedded within the query string.

### Private APIs

Defx uses API keys to allow access to private APIs. You can obtain these keys by logging in and creating a key in the **More (on the top navigation) -> API** section. Doing so will provide you with both an **API Key** (which will serve as your username) and an **API Secret** (which will be used to sign messages).

All requests to private endpoints must include the following headers:

| Header             | Description                                             | VALUE                                                                                                                                  |
| ------------------ | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `X-DEFX-APIKEY`    | API Key                                                 | Your unique Defx API key                                                                                                               |
| `X-DEFX-TIMESTAMP` | Timestamp                                               | The current time in milliseconds since the Unix epoch                                                                                  |
| `X-DEFX-SIGNATURE` | An HMAC-SHA256 signature, created using your API Secret | timestamp (in ms) + query string (sorted by key in asc order) + body (as JSON string with no spaces or newlines or escaped characters) |

To prevent replay attacks, Defx requires that the timestamp in the request header be within 10 seconds of the server’s timestamp upon receiving the request. If the timestamp difference exceeds 10 seconds, the request will be considered unauthorized.

#### EXAMPLE <a href="#payload" id="payload"></a>

For the examples, assuming that the API key's value is `API_KEY` and the API secret's value is API\_SECRET. \
\
The signature is a HMAC-SHA256 hash generated using your `API_SECRET` on a concatenated string consisting of the `timestamp`, `query string` (if applicable), and the `request body`. The `request_body` should be a json string with no spaces, newlines or escaped characters. <br>

#### 1. Standard Request (No Query Parameters)

Use this example for the majority of API calls where data is passed only in the request body.

Signature Generation String: Concatenate the timestamp and the raw JSON body (with no spaces or newlines). `TIMESTAMP` + `JSON_BODY`

Example:

* Timestamp: `1707238375423`
* Request Body: `{"symbol":"BTC_USDC","side":"SELL","type":"LIMIT","quantity":"1","price":"5500"}`

```bash
sh
  # Generate signature using HMAC-SHA256 and your API_SECRET
echo -n '1707238375423{"symbol":"BTC_USDC","side":"SELL","type":"LIMIT","quantity":"1","price":"5500"}' | openssl dgst -sha256 -hmac "API_SECRET"

  97d09ab550f1559edf6db4f8bdf30c8a472e4b68114eeec4b424b5744aae7450
```

Once the signature is generated, this is sent as the header along with the payload as follows:

```hurl
curl --location 'https://api.defx.com/orders' \
--header 'X-DEFX-APIKEY: API_KEY' \
--header 'X-DEFX-SIGNATURE: 97d09ab550f1559edf6db4f8bdf30c8a472e4b68114eeec4b424b5744aae7450' \
--header 'X-DEFX-TIMESTAMP: 1707238375423' \
--header 'Content-Type: application/json' \
--data '{
    "symbol": "BTC_USDC",
    "side": "SELL",
    "type": "LIMIT",
    "quantity": "1",
    "price": "5500"
}'
```

#### 2. Complex Request (With Query Parameters)

Use this example for specific endpoints that require URL parameters. To prevent tampering, the query string must be included in the signature. The query string must be sorted alphabetically by key.

Signature Generation String: Concatenate the timestamp, the sorted query string, and the raw JSON body. `TIMESTAMP` + `QUERY_STRING` \
\
Example:

* Timestamp: `1707238375423`
* Query Params: `idType=clientOrderId&symbol=BTC_USDC` (Sorted ASC by key)
* Request Body: (Empty)

Signature Generation:

```bash
# Concatenate: TIMESTAMP + QUERY_STRING
echo -n '1707238375423idType=clientOrderId&symbol=BTC_USDC' | openssl dgst -sha256 -hmac "API_SECRET"

88facfa1e77413f45756458f9f428933851e67d533034d5b3b449e708ed0d15b
```

Final Request:

```hurl
curl --location --globoff --request DELETE 'https://api.defx.com/v1/auth/api/order/myNewClientOrderId?idType=clientOrderId&symbol=BTC_USDC' \
--header 'X-DEFX-APIKEY: API_KEY' \
--header 'X-DEFX-SIGNATURE: 88facfa1e77413f45756458f9f428933851e67d533034d5b3b449e708ed0d15b' \
--header 'X-DEFX-TIMESTAMP: 1707238375423' \
--data ''
```

Important Notes

* Alphabetical Sorting: Query parameters in the URL must always be sorted in ascending order (A-Z) by their keys before generating the signature.
* JSON Formatting: When a body is present, use the raw JSON string with no spaces, newlines, or escaped characters for the signature.
* Combined Requests: If a request requires both a query string and a body, the signature string is formed by `TIMESTAMP + QUERY_STRING + BODY`.

***

## Rate Limits <a href="#rate-limits" id="rate-limits"></a>

Coming Soon

***

## Data Types <a href="#data-types" id="data-types"></a>

Defx's public and private endpoints contain references to the following data types in the request object, and they are documented here for reference.

**string**

A sequence of characters enclosed in quotes, adhering to the standard JSON format. For further details, refer to the JSON specification.

**decimal**

A numeric value with a decimal point, encoded as a string in JSON. It consists of a sequence of digits, which may include a decimal point followed by more digits.

**timestamp**

Represents the time elapsed since January 1, 1970, UTC, measured in milliseconds. This value is a multiplication of the UNIX timestamp by 1000 and is expressed as a numerical value in JSON, not as a string.

**integer**

A whole number presented as a numerical value in JSON.

**array**

A structured list in JSON format, where each element may contain a described payload.

***

## HTTP Status Codes

| HTTP Status | Description                                                                                                                                                                               |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `200`       | Request was successful                                                                                                                                                                    |
| `30x`       | API endpoint has moved                                                                                                                                                                    |
| `400`       | There was an issue with the request format. When a 400 status is returned, you will receive the exact error as part of the response body to help you understand the nature of this error. |
| `401`       | The API key is missing the role necessary to access this private API endpoint                                                                                                             |
| `404`       | Unknown API entry point or Order not found                                                                                                                                                |
| `429`       | Rate Limiting was applied                                                                                                                                                                 |
| `500`       | The server encountered an error                                                                                                                                                           |
| `502`       | Technical issues are preventing the request from being satisfied                                                                                                                          |
| `503`       | The exchange is down for maintenance                                                                                                                                                      |
