> ## 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.

# Real-time & WebSockets

> Subscribe to live events via WebSockets

## Overview

Cryptorobot.ai uses **WebSockets** for real-time bidirectional communication. This enables:

* Live price ticker updates
* Trading bot event streams
* Order execution notifications
* System alerts and status changes

## Connecting

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { createClient } from '@cryptorobot.ai/client';

  const client = createClient('https://api.cryptorobot.ai');

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

  // Listen for events
  client.service('traders/pods/events').on('created', (event) => {
    console.log('Pod event:', event);
  });

  client.service('exchanges/ticker').on('patched', (ticker) => {
    console.log('Price update:', ticker);
  });
  ```

  ```python Python theme={null}
  import requests

  # Authenticate first
  response = requests.post('https://api.cryptorobot.ai/authentication', json={
      'strategy': 'local',
      'email': 'you@example.com',
      'password': 'your-password'
  })
  token = response.json()['accessToken']

  # Use the token for subsequent API calls
  headers = {'Authorization': f'Bearer {token}'}
  strategies = requests.get('https://api.cryptorobot.ai/strategies', headers=headers)
  ```
</CodeGroup>

## Event Types

Events follow the naming pattern: `<service> <method>`

| Event Name                    | Trigger              | Payload         |
| ----------------------------- | -------------------- | --------------- |
| `strategies created`          | New strategy created | Strategy object |
| `strategies patched`          | Strategy updated     | Strategy object |
| `strategies removed`          | Strategy deleted     | `{ _id }`       |
| `traders created`             | Bot created          | Trader object   |
| `traders patched`             | Bot status changed   | Trader object   |
| `traders pods events created` | Pod lifecycle event  | Event object    |
| `exchanges ticker patched`    | Price update         | Ticker data     |
| `trades created`              | Trade executed       | Trade object    |
| `models signals created`      | New signal fired     | Signal object   |
| `messages created`            | New notification     | Message object  |
| `events created`              | System event         | Event object    |

## Listening to Events

### Trading Bot Events

```javascript theme={null}
// Listen for all pod events (trades, errors, status changes)
client.service('traders/pods/events').on('created', (event) => {
  console.log(`[${event.type}] ${event.message}`);
  // { type: "trade_executed", podId: "pod-123", message: "Bought 0.1 BTC @ 42400", ... }
});

// Bot status changes
client.service('traders').on('patched', (trader) => {
  console.log(`Bot ${trader.name} is now ${trader.status}`);
  // status: "running" | "stopped" | "error"
});
```

### Price Updates

```javascript theme={null}
// Real-time ticker updates
client.service('exchanges/ticker').on('patched', (ticker) => {
  console.log(`${ticker.symbol}: ${ticker.last}`);
});
```

### Trade Notifications

```javascript theme={null}
// New trades executed by your bots
client.service('trades').on('created', (trade) => {
  console.log(`${trade.side} ${trade.amount} ${trade.symbol} @ ${trade.price}`);
});
```

### Signal Alerts

```javascript theme={null}
// ML model signal alerts
client.service('models/signals').on('created', (signal) => {
  console.log(`Signal: ${signal.type} ${signal.pair} - confidence: ${signal.confidence}`);
});
```

## Service Methods via WebSocket

You can also call API methods through the WebSocket connection (instead of REST):

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

const client = createClient('https://api.cryptorobot.ai');

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

// Find strategies (equivalent to GET /strategies)
const strategies = await client.service('strategies').find({
  query: { type: 'momentum' }
});
console.log(strategies.data);

// Create a resource (equivalent to POST /strategies)
const newStrategy = await client.service('strategies').create({
  name: 'New Strategy',
  type: 'momentum',
  pair: 'BTC/USDT'
});
console.log(newStrategy._id);

// Patch a resource (equivalent to PATCH /strategies/:id)
const updated = await client.service('strategies').patch('strat-456', {
  name: 'Updated Name'
});
console.log(updated);
```

## Channel Subscription

By default, you receive events for resources you own. The server automatically subscribes authenticated users to their personal channel.

<Note>
  You don't need to manually subscribe to channels. Authentication handles channel membership automatically based on your user ID and permissions.
</Note>

## Reconnection Handling

The client SDK handles reconnection automatically. You can listen for connection status changes:

```javascript theme={null}
client.on('disconnect', () => {
  console.log('Connection lost — attempting to reconnect...');
});

client.on('reconnect', () => {
  console.log('Reconnected successfully');
});
```

<Note>
  The client SDK automatically re-authenticates after reconnection using the stored JWT token.
</Note>

## Best Practices

<AccordionGroup>
  <Accordion title="Use WebSocket transport only">
    Set `transports: ['websocket']` to skip the HTTP long-polling upgrade handshake and connect faster.
  </Accordion>

  <Accordion title="Handle disconnections gracefully">
    Always implement reconnection logic. Network interruptions are normal in long-lived connections.
  </Accordion>

  <Accordion title="Don't poll — subscribe">
    Instead of polling REST endpoints for updates, listen to WebSocket events. This reduces latency and API load.
  </Accordion>

  <Accordion title="Use REST for initial data, WebSocket for updates">
    Fetch the initial state via REST (`GET /traders`), then subscribe to real-time updates via WebSocket (`traders patched`).
  </Accordion>

  <Accordion title="Rate limit event handlers">
    High-frequency events (like ticker updates) can fire many times per second. Throttle or debounce your handlers if updating UI.
  </Accordion>
</AccordionGroup>
