> ## Documentation Index
> Fetch the complete documentation index at: https://docs.joyride.exchange/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Trading Assistant

> Natural-language AI assistant for trading, account management, and market analysis

## Overview

The AI Trading Assistant provides a conversational interface for interacting with the Joyride exchange. It can look up market data, analyze positions, and present actionable strategies. The model cannot place orders. A trade starts only when the user taps the strategy card's **Buy** or **Sell** button in the Joyride app.

The app keeps that trade intent while it completes any required setup. It connects the user's wallet when needed, opens the USDC deposit flow when the available balance is too low, and submits the original order after the deposit is credited. The visible action remains **Buy** or **Sell** throughout the flow.

Balance guidance is based on the latest account read. A genuine zero balance is treated as zero. If account data is temporarily unavailable, the assistant does not state a balance or claim that a trade is affordable.

## Authentication

The AI Chat endpoint uses **SIWS (Sign In With Solana)** authentication with JWT sessions, separate from the main exchange API's wallet header auth.

### Auth Flow

1. **Get a nonce:** `GET /v1/auth/nonce` — returns a random nonce valid for 5 minutes
2. **Sign the message:** Construct a SIWS message with the nonce and sign it with your Solana wallet
3. **Verify and get JWT:** `POST /v1/auth/verify` with wallet, signature, and nonce — returns a JWT
4. **Use the JWT:** Include `Authorization: Bearer <jwt>` on all `/v1/ai/chat` requests

## Sending Messages

Send a POST request to `/v1/ai/chat` with a JSON body:

```json theme={null}
{
  "message": "What's the current price of SOL?",
  "conversation_id": null
}
```

* `message` — your message text (max 10,000 characters)
* `conversation_id` — omit or set to `null` for a new conversation; include a UUID to continue an existing one

## SSE Response Format

Responses are streamed as **Server-Sent Events** (`text/event-stream`). Each event has a type and JSON data:

```
event: text
data: {"content":"SOL is currently trading at $200."}

event: done
data: {"conversation_id":"550e8400-...","usage":{"input_tokens":150,"output_tokens":45}}
```

### Event Types

| Event             | Description                                                      |
| ----------------- | ---------------------------------------------------------------- |
| `text`            | AI-generated text chunk (streamed incrementally)                 |
| `tool_start`      | Tool execution started — use for loading indicators              |
| `tool_result`     | Tool execution completed with text summary                       |
| `strategy`        | Trade recommendation card with a client-owned Buy or Sell action |
| `table`           | Tabular data (positions, orders, etc.)                           |
| `options_chain`   | Options chain display data                                       |
| `price_quote`     | Single instrument price quote                                    |
| `account_summary` | Account balance overview                                         |
| `order_status`    | Order placement/cancellation result                              |
| `error`           | Non-fatal error during processing                                |
| `done`            | Stream complete — contains conversation ID and token usage       |

### Data Conventions

SSE events use **human-readable units**, unlike the main REST API:

| Field    | SSE Events              | Main REST API                 |
| -------- | ----------------------- | ----------------------------- |
| Prices   | USD (e.g., `1.50`)      | Micros (e.g., `1500000`)      |
| Sizes    | Contracts (e.g., `2.0`) | Millicontracts (e.g., `2000`) |
| Balances | USD (e.g., `10000.0`)   | Micros (e.g., `10000000000`)  |

## Error Codes

| Code              | HTTP Status | Description                                                 |
| ----------------- | ----------- | ----------------------------------------------------------- |
| `UNAUTHORIZED`    | 401         | Missing or invalid JWT                                      |
| `RATE_LIMITED`    | 429         | Too many requests — retry after the specified delay         |
| `INVALID_REQUEST` | 400         | Empty message, message too long, or invalid conversation ID |
| `NOT_FOUND`       | 404         | Conversation not found or not owned by this wallet          |
| `INTERNAL_ERROR`  | 500         | Server error                                                |
| `LLM_UNAVAILABLE` | SSE         | Claude API is unreachable (sent as SSE error event)         |
| `LLM_ERROR`       | SSE         | Error during LLM streaming                                  |
| `TOOL_ERROR`      | SSE         | Tool execution failed                                       |

## Rate Limiting

The AI Chat endpoint is rate-limited to **20 requests per minute** per wallet (configurable via `AI_RATE_LIMIT_RPM`). When rate limited, the API returns HTTP 429 with the number of seconds to wait.

## Available Tools

The AI assistant has access to 16 read and presentation tools:

**Market data (7):** options chain, ticker, orderbook, spot prices, market config, instruments, and candles

**Account (6):** balance, positions, open orders, trade history, profile, and margin

**Presentation (3):** payout curve, suggested replies, and strategy cards

Mutating tools are intentionally absent. The app submits a tapped strategy through the user's authenticated exchange session, where the normal server-side risk and order validation still applies.
