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

# Client Setup

> Connect to Cryptorobot.ai using the official npm client over WebSockets

## Install the Client SDK

The recommended way to interact with Cryptorobot.ai is via the official typed client package over WebSockets:

```bash theme={null}
npm install @cryptorobot.ai/client
```

## Connect & Authenticate

```typescript theme={null}
import { createClient } from '@cryptorobot.ai/client';

// Connect via WebSocket (recommended)
const client = createClient('https://api.cryptorobot.ai');

// Authenticate with email/password
const { accessToken, user } = await client.authenticate({
  strategy: 'local',
  email: 'you@example.com',
  password: 'your-password'
});

console.log('Logged in as:', user.email);
```

## Using Services

All API endpoints are exposed as typed services:

```typescript theme={null}
// List strategies (paginated)
const strategies = await client.service('strategies').find({
  query: { $limit: 10, $sort: { createdAt: -1 } }
});
console.log(strategies.total, strategies.data);

// Get a single resource
const strategy = await client.service('strategies').get('507f1f77bcf86cd799439011');

// Create a resource
const exchange = await client.service('exchanges').create({
  name: 'binance',
  apiKey: 'your-api-key',
  secret: 'your-secret'
});

// Update a resource
await client.service('strategies').patch('507f1f77bcf86cd799439011', {
  name: 'Updated Strategy Name'
});

// Delete a resource
await client.service('strategies').remove('507f1f77bcf86cd799439011');
```

## Real-Time Events

The WebSocket connection automatically receives real-time events for services you interact with:

```typescript theme={null}
// Listen for new pod events
client.service('traders/pods/events').on('created', (event) => {
  console.log('New pod event:', event);
});

// Listen for ticker updates
client.service('exchanges/ticker').on('patched', (ticker) => {
  console.log('Price update:', ticker.symbol, ticker.last);
});

// Listen for trade executions
client.service('trades').on('created', (trade) => {
  console.log('Trade executed:', trade.side, trade.amount, trade.symbol);
});
```

## REST Alternative

For environments where WebSockets aren't available, you can use REST:

<Tabs>
  <Tab title="REST Client">
    ```typescript theme={null}
    import { createClient } from '@cryptorobot.ai/client';

    const client = createClient('https://api.cryptorobot.ai', { transport: 'rest' });

    await client.authenticate({
      strategy: 'local',
      email: 'you@example.com',
      password: 'your-password'
    });

    const strategies = await client.service('strategies').find();
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    # Login
    curl -X POST https://api.cryptorobot.ai/authentication \
      -H "Content-Type: application/json" \
      -d '{"strategy": "local", "email": "you@example.com", "password": "your-password"}'

    # Authenticated request
    curl https://api.cryptorobot.ai/strategies \
      -H "Authorization: Bearer eyJhbGciOi..."
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    BASE_URL = 'https://api.cryptorobot.ai'

    auth = requests.post(f'{BASE_URL}/authentication', json={
        'strategy': 'local',
        'email': 'you@example.com',
        'password': 'your-password'
    }).json()

    headers = {'Authorization': f'Bearer {auth["accessToken"]}'}
    strategies = requests.get(f'{BASE_URL}/strategies', headers=headers).json()
    ```
  </Tab>
</Tabs>

## Base URL

```
https://api.cryptorobot.ai
```

## Required Headers (REST only)

| Header          | Value                              | Required                    |
| --------------- | ---------------------------------- | --------------------------- |
| `Content-Type`  | `application/json`                 | For POST/PATCH/PUT          |
| `Authorization` | `Bearer <token>` or `ApiKey <key>` | For authenticated endpoints |

## Query Parameters

### Pagination

```typescript theme={null}
// SDK
await client.service('strategies').find({ query: { $limit: 10, $skip: 20 } });

// REST
// GET /strategies?$limit=10&$skip=20
```

### Sorting

```typescript theme={null}
// Sort by createdAt descending
await client.service('strategies').find({ query: { $sort: { createdAt: -1 } } });

// REST: GET /strategies?$sort[createdAt]=-1
```

### Field Selection

```typescript theme={null}
// Only return name and type fields
await client.service('strategies').find({ query: { $select: ['name', 'type'] } });

// REST: GET /strategies?$select[]=name&$select[]=type
```

### Filtering

```typescript theme={null}
// Exact match
await client.service('strategies').find({ query: { type: 'momentum' } });

// Comparison operators
await client.service('trades').find({
  query: { createdAt: { $gte: '2024-01-01', $lte: '2024-12-31' } }
});

// In array
await client.service('exchanges').find({
  query: { name: { $in: ['binance', 'bybit'] } }
});
```

## Response Format

### Paginated List (Find)

```json theme={null}
{
  "total": 42,
  "limit": 25,
  "skip": 0,
  "data": [{ "_id": "...", "name": "Strategy A" }]
}
```

### Single Resource (Get / Create / Patch)

```json theme={null}
{
  "_id": "507f1f77bcf86cd799439011",
  "name": "My Strategy",
  "createdAt": "2024-01-15T10:30:00.000Z",
  "updatedAt": "2024-01-15T10:30:00.000Z"
}
```

### Error

```json theme={null}
{
  "name": "NotAuthenticated",
  "message": "Invalid access token",
  "code": 401,
  "className": "not-authenticated"
}
```
