> For the complete documentation index, see [llms.txt](https://docs.pretoke.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pretoke.xyz/api-reference/errors-and-rate-limits.md).

# Errors & Rate Limits

## Error envelope

Every error response follows a consistent structure:

```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "quantity must be greater than 0",
    "fields": [{ "field": "quantity", "rule": "positive" }]
  },
  "requestId": "b3f1c2a0-..."
}
```

{% hint style="info" %}
`fields` is only present on validation errors that can be attributed to specific request fields.
{% endhint %}

## HTTP status → error code mapping

| HTTP Status | `error.code`          | Meaning                                               |
| ----------- | --------------------- | ----------------------------------------------------- |
| 400         | `VALIDATION_ERROR`    | Request body/params failed validation                 |
| 401         | `UNAUTHORIZED`        | Missing, invalid, or expired auth token               |
| 403         | `FORBIDDEN`           | Authenticated, but not allowed to perform this action |
| 404         | `RESOURCE_NOT_FOUND`  | The requested resource doesn't exist                  |
| 429         | `RATE_LIMIT_EXCEEDED` | Too many requests — slow down                         |
| 500         | `INTERNAL_ERROR`      | Unexpected server-side failure                        |

Service-specific error codes (like `ORDER_NOT_FOUND`) are passed through as-is when a downstream service already formatted a structured error.

***

## Rate limits

Enforced per authenticated user (or per client IP if unauthenticated), using a **sliding 60-second window**:

| Category  | Limit         | Endpoints                                                                                           |
| --------- | ------------- | --------------------------------------------------------------------------------------------------- |
| **Read**  | 100 req / 60s | Most `GET` endpoints (events, markets, positions, trades, notifications, etc.)                      |
| **Trade** | 10 req / 60s  | `POST /orders`, `POST /trade/amm`, `POST /trade/market`, `POST /withdraw`, `POST /redeem/:marketId` |

### Response headers

Every response includes:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
```

### When you exceed the limit

```
HTTP/1.1 429 Too Many Requests
Retry-After: 12
```

```json
{ "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "Too many requests" }, "requestId": "..." }
```

{% hint style="warning" %}
Wait for the duration in `Retry-After` (seconds) before retrying. Making additional requests during this window will extend the cooldown.
{% endhint %}

### Handling rate limits in code

{% tabs %}
{% tab title="JavaScript" %}

```javascript
async function apiCall(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.status === 429) {
      const retryAfter = parseInt(response.headers.get('Retry-After') || '5', 10);
      console.log(`Rate limited. Retrying in ${retryAfter}s...`);
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      continue;
    }

    return response.json();
  }
  throw new Error('Max retries exceeded');
}
```

{% endtab %}

{% tab title="Python" %}

```python
import time
import requests

def api_call(url, headers, max_retries=3):
    for attempt in range(max_retries):
        response = requests.get(url, headers=headers)

        if response.status_code == 429:
            retry_after = int(response.headers.get("Retry-After", 5))
            print(f"Rate limited. Retrying in {retry_after}s...")
            time.sleep(retry_after)
            continue

        return response.json()

    raise Exception("Max retries exceeded")
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const axios = require('axios');

async function apiCall(config, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await axios(config);
    } catch (error) {
      if (error.response?.status === 429) {
        const retryAfter = parseInt(error.response.headers['retry-after'] || '5', 10);
        console.log(`Rate limited. Retrying in ${retryAfter}s...`);
        await new Promise(r => setTimeout(r, retryAfter * 1000));
        continue;
      }
      throw error;
    }
  }
  throw new Error('Max retries exceeded');
}
```

{% endtab %}
{% endtabs %}

***

## Idempotency

{% hint style="success" %}
`POST /withdraw` and `POST /redeem/:marketId` are deduplicated server-side for a short window after submission. Resubmitting the same request while the original is still processing returns a `200`/`202`-level response with `"status": "duplicate"` — this is not an error, it means your original request is being handled and it's safe to retry on network failures without risking a double-send.
{% endhint %}

```json
{ "data": { "status": "duplicate", "message": "Withdrawal already in progress" }, "requestId": "..." }
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.pretoke.xyz/api-reference/errors-and-rate-limits.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
