# API documentations

## Gradient Orderbook API Reference

**Base URL:** `https://api.gradient.trade`

This is the complete API reference for the Gradient Orderbook API. All endpoints are rate-limited to **60 requests per minute** (1 request per second) based on IP address.

***

### Rate Limiting

All endpoints have a global rate limit of **60 requests per minute** (1 request per second).

* Rate limits are based on **IP address**
* When rate limit is exceeded, the API returns a `429 Too Many Requests` status code
* Rate limit headers are included in responses:
  * `X-RateLimit-Limit`: Maximum number of requests allowed
  * `X-RateLimit-Remaining`: Number of requests remaining in the current window
  * `X-RateLimit-Reset`: Time when the rate limit resets

#### Rate Limit Response

```json
{
  "success": false,
  "message": "Too many requests from this IP, please try again later."
}
```

***

### Health Check Endpoints

#### Get Server Status

Check if the server is running.

**Endpoint:** `GET https://api.gradient.trade/`

**Rate Limit:** 60 requests per minute

**Response:**

```json
{
  "success": true,
  "message": "Server is running",
  "timestamp": "2025-11-09T20:47:52.783Z"
}
```

***

#### Get Health Status

Check server health status.

**Endpoint:** `GET https://api.gradient.trade/health`

**Rate Limit:** 60 requests per minute

**Response:**

```json
{
  "success": true,
  "message": "Server is healthy",
  "timestamp": "2025-11-09T20:47:52.783Z"
}
```

***

#### Get Socket.IO Health

Check Socket.IO service status.

**Endpoint:** `GET https://api.gradient.trade/socket-health`

**Rate Limit:** 60 requests per minute

**Response:**

```json
{
  "success": true,
  "message": "Socket.IO service is running",
  "timestamp": "2025-11-09T20:47:52.783Z"
}
```

***

### System Status Endpoints

#### Get Retry Statistics

Get blockchain retry statistics.

**Endpoint:** `GET https://api.gradient.trade/retry-stats`

**Rate Limit:** 60 requests per minute

**Response:**

```json
{
  "success": true,
  "data": {
    // Retry statistics object
  },
  "timestamp": "2025-11-09T20:47:52.783Z"
}
```

**Error Response:**

```json
{
  "success": false,
  "message": "Failed to get retry statistics",
  "error": "Error message"
}
```

***

#### Get RPC Monitor Status

Get RPC monitor status.

**Endpoint:** `GET https://api.gradient.trade/rpc-monitor`

**Rate Limit:** 60 requests per minute

**Response:**

```json
{
  "success": true,
  "data": {
    // RPC monitor status object
  },
  "timestamp": "2025-11-09T20:47:52.783Z"
}
```

**Error Response:**

```json
{
  "success": false,
  "message": "Failed to get RPC monitor status",
  "error": "Error message"
}
```

***

### Order Endpoints

#### Get Active Orders

Get active orders for a specific token with pagination and filtering.

**Endpoint:** `GET https://api.gradient.trade/api/order/active`

**Rate Limit:** 60 requests per minute

**Query Parameters:**

| Parameter       | Type   | Required | Description                                   |
| --------------- | ------ | -------- | --------------------------------------------- |
| `tokenAddress`  | string | Yes      | Ethereum token address                        |
| `orderType`     | string | No       | Filter by order type: `buy` or `sell`         |
| `executionType` | string | No       | Filter by execution type: `limit` or `market` |
| `page`          | number | No       | Page number for pagination (default: 1)       |
| `limit`         | number | No       | Number of results per page (default: 10)      |

**Example Request:**

```bash
curl "https://api.gradient.trade/api/order/active?tokenAddress=0x123...&orderType=buy&page=1&limit=20"
```

**Response:**

```json
{
  "success": true,
  "message": "Active orders retrieved successfully",
  "data": [
    {
      "id": "order-id",
      "owner": "0x...",
      "orderType": "buy",
      "executionType": "limit",
      "token": {
        "address": "0x...",
        "symbol": "TOKEN",
        "decimals": 18,
        "logoURI": "https://...",
        "name": "Token Name"
      },
      "amount": "1000.0",
      "filledAmount": "500.0",
      "remainingAmount": "500.0",
      "filledPercent": 50.0,
      "price": "0.001",
      "executionPrice": null,
      "executionUsdPrice": null,
      "ethAmount": "1.0",
      "ethRemainingAmount": "0.5",
      "ethFilledAmount": "0.5",
      "expirationTime": 1234567890,
      "expiresIn": "2d 5h",
      "status": "active",
      "createdAt": "2025-01-13T12:00:00.000Z",
      "updatedAt": "2025-01-13T12:00:00.000Z",
      "usdPrice": null,
      "createTransactionHash": "0x...",
      "cancelTransactionHash": null,
      "expireTransactionHash": null,
      "fulfillTransactionHash": null,
      "partialFulfillTransactionHashes": []
    }
  ],
  "aggregates": {
    "totalSellRemainingAmount": "1000000000000000000",
    "totalSellRemainingAmountFormatted": "1.0",
    "totalBuyRemainingAmount": "2000000000000000000",
    "totalBuyRemainingAmountFormatted": "2.0",
    "tokenDecimals": 18,
    "priceInEth": "0.001"
  },
  "pagination": {
    "currentPage": 1,
    "totalPages": 5,
    "totalCount": 20,
    "hasNextPage": true,
    "hasPrevPage": false,
    "limit": 20
  }
}
```

**Error Responses:**

* `400 Bad Request` - Missing or invalid token address
* `404 Not Found` - Token not found

***

#### Get Order by ID

Get a specific order by its ID.

**Endpoint:** `GET https://api.gradient.trade/api/order/{orderId}`

**Rate Limit:** 60 requests per minute

**Path Parameters:**

| Parameter | Type   | Required | Description  |
| --------- | ------ | -------- | ------------ |
| `orderId` | string | Yes      | The order ID |

**Example Request:**

```bash
curl "https://api.gradient.trade/api/order/0x123abc..."
```

**Response:**

```json
{
  "success": true,
  "message": "Order retrieved successfully",
  "data": {
    "id": "0x123abc...",
    "owner": "0x...",
    "orderType": "sell",
    "executionType": "limit",
    "token": {
      "address": "0x...",
      "symbol": "TOKEN",
      "decimals": 18,
      "logoURI": "https://...",
      "name": "Token Name"
    },
    "amount": "1000.0",
    "filledAmount": "1000.0",
    "remainingAmount": "0.0",
    "filledPercent": 100.0,
    "price": "0.001",
    "executionPrice": "0.001",
    "executionUsdPrice": 1.5,
    "ethAmount": "1.0",
    "ethRemainingAmount": "0.0",
    "ethFilledAmount": "1.0",
    "expirationTime": 1234567890,
    "expiresIn": "Expired",
    "status": "filled",
    "createdAt": "2025-01-13T12:00:00.000Z",
    "updatedAt": "2025-01-13T12:00:00.000Z",
    "usdPrice": null,
    "createTransactionHash": "0x...",
    "cancelTransactionHash": null,
    "expireTransactionHash": null,
    "fulfillTransactionHash": "0x...",
    "partialFulfillTransactionHashes": []
  }
}
```

**Error Responses:**

* `400 Bad Request` - Missing order ID
* `404 Not Found` - Order not found

***

### Token Endpoints

#### Get Token Information

Get comprehensive token information including price, volume, and market data.

**Endpoint:** `GET https://api.gradient.trade/api/token/info`

**Rate Limit:** 60 requests per minute

**Query Parameters:**

| Parameter | Type   | Required | Description            |
| --------- | ------ | -------- | ---------------------- |
| `address` | string | Yes      | Ethereum token address |

**Example Request:**

```bash
curl "https://api.gradient.trade/api/token/info?address=0x123..."
```

**Response:**

```json
{
  "success": true,
  "data": {
    "name": "Token Name",
    "symbol": "TOKEN",
    "chainId": 1,
    "logoURI": "https://...",
    "decimals": 18,
    "pairAddress": "0x...",
    "buyTax": 0,
    "sellTax": 0,
    "usdPrice": 1.5,
    "priceChange": 5.2,
    "volume24h": 1000000.0,
    "buyVolumeUsd24h": 600000.0,
    "sellVolumeUsd24h": 400000.0,
    "buySellRatio24h": 1.5,
    "marketCap": 10000000.0
  }
}
```

**Response Fields:**

| Field              | Type   | Description                      |
| ------------------ | ------ | -------------------------------- |
| `name`             | string | Token name                       |
| `symbol`           | string | Token symbol                     |
| `chainId`          | number | Blockchain chain ID              |
| `logoURI`          | string | Token logo URL                   |
| `decimals`         | number | Token decimals                   |
| `pairAddress`      | string | Liquidity pair address           |
| `buyTax`           | number | Buy tax percentage               |
| `sellTax`          | number | Sell tax percentage              |
| `usdPrice`         | number | Current USD price                |
| `priceChange`      | number | 24h price change percentage      |
| `volume24h`        | number | 24-hour trading volume in USD    |
| `buyVolumeUsd24h`  | number | 24-hour buy volume in USD        |
| `sellVolumeUsd24h` | number | 24-hour sell volume in USD       |
| `buySellRatio24h`  | number | Buy/sell ratio for last 24 hours |
| `marketCap`        | number | Market capitalization in USD     |

**Error Responses:**

* `400 Bad Request` - Missing or invalid token address
* `404 Not Found` - Token not found or invalid address

**Note:** If the token is not in the database, the API will fetch it from the blockchain and save it automatically. For new tokens, `volume24h` will be 0.

***

#### Get Token Reserves

Get token reserves (ETH and token reserves) from the liquidity pool.

**Endpoint:** `GET https://api.gradient.trade/api/token/token-reserves`

**Rate Limit:** 60 requests per minute

**Query Parameters:**

| Parameter | Type   | Required | Description            |
| --------- | ------ | -------- | ---------------------- |
| `address` | string | Yes      | Ethereum token address |

**Example Request:**

```bash
curl "https://api.gradient.trade/api/token/token-reserves?address=0x123..."
```

**Response:**

```json
{
  "success": true,
  "data": {
    "reserveETH": "1000000000000000000",
    "reserveToken": "2000000000000000000"
  }
}
```

**Response Fields:**

| Field          | Type   | Description                               |
| -------------- | ------ | ----------------------------------------- |
| `reserveETH`   | string | ETH reserve in wei (raw format)           |
| `reserveToken` | string | Token reserve in token units (raw format) |

**Error Responses:**

* `400 Bad Request` - Missing or invalid token address

***

### Response Format

All API responses follow a consistent format:

#### Success Response

```json
{
  "success": true,
  "message": "Optional success message",
  "data": {
    /* Response data */
  },
  "pagination": {
    /* Pagination info if applicable */
  }
}
```

#### Error Response

```json
{
  "success": false,
  "message": "Error message",
  "error": "Detailed error information"
}
```

***

### Error Handling

The API uses standard HTTP status codes:

* `200 OK` - Request successful
* `400 Bad Request` - Invalid request parameters
* `404 Not Found` - Resource not found
* `429 Too Many Requests` - Rate limit exceeded
* `500 Internal Server Error` - Server error

All errors are handled by a global error handler and return consistent error response format.

***

### Code Examples

#### JavaScript/TypeScript

```typescript
// Get active orders
const response = await fetch(
  'https://api.gradient.trade/api/order/active?tokenAddress=0x123...&page=1&limit=20',
);
const data = await response.json();

// Get token info
const tokenResponse = await fetch('https://api.gradient.trade/api/token/info?address=0x123...');
const tokenData = await tokenResponse.json();
```

#### Python

```python
import requests

# Get active orders
response = requests.get(
    'https://api.gradient.trade/api/order/active',
    params={
        'tokenAddress': '0x123...',
        'page': 1,
        'limit': 20
    }
)
data = response.json()

# Get token info
token_response = requests.get(
    'https://api.gradient.trade/api/token/info',
    params={'address': '0x123...'}
)
token_data = token_response.json()
```

#### cURL

```bash
# Get active orders
curl "https://api.gradient.trade/api/order/active?tokenAddress=0x123...&page=1&limit=20"

# Get token info
curl "https://api.gradient.trade/api/token/info?address=0x123..."

# Get order by ID
curl "https://api.gradient.trade/api/order/0x123abc..."
```

***

### Security Features

* **CSRF Protection** - All endpoints are protected against CSRF attacks
* **Helmet** - Security headers are set automatically
* **CORS** - Configurable CORS policy
* **Rate Limiting** - IP-based rate limiting on all endpoints
* **Input Validation** - All inputs are validated before processing

***

### Support

For API support and questions, please contact the Gradient team.

**API Base URL:** `https://api.gradient.trade`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.gradient.trade/gradient-api/api-documentations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
