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

# Everstrike API Usage Examples: REST and WebSockets

> Copy-paste examples for the Everstrike REST and WebSockets APIs — connect, authenticate, stream market data, and receive account updates in Python and JavaScript.

The Everstrike API lets you connect programs directly to the exchange for market data and account activity. This page provides working code samples for both the REST and WebSockets APIs, covering connection, authentication, subscribing to market updates, and handling account events.

<Note>
  Full API references live at [docs.testnet.everstrike.io](https://docs.testnet.everstrike.io) (REST) and [everstrikeio.github.io/everstrike-websockets-api](https://everstrikeio.github.io/everstrike-websockets-api/) (WebSockets). This page is a practical starter, not the reference.
</Note>

## Endpoints

| Environment | REST                                | WebSockets                        |
| ----------- | ----------------------------------- | --------------------------------- |
| Testnet     | `https://api.testnet.everstrike.io` | `wss://wss.testnet.everstrike.io` |
| Mainnet     | `https://api.everstrike.io`         | `wss://wss.everstrike.io`         |

Generate an API key and a secret key at [app.testnet.everstrike.io/app/api](https://app.testnet.everstrike.io/app/api) for testnet, or the equivalent mainnet URL.

## REST API

### List Trading Pairs

The `/pairs` endpoint returns every tradable market with tick size, lot size, leverage caps, and contract specifications. No authentication required.

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.everstrike.io/pairs
  ```

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

  response = requests.get("https://api.everstrike.io/pairs")
  pairs = response.json()["result"]
  print(list(pairs.keys())[:5])
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.everstrike.io/pairs');
  const { result } = await response.json();
  console.log(Object.keys(result).slice(0, 5));
  ```
</CodeGroup>

Use the returned key (for example, `USD_BTC_PERP`) whenever you reference a market from the REST or WebSockets API.

### Authenticated Requests

Authenticated endpoints require your API key and a signed request. Send orders, cancel orders, and read account state under the `/auth/*` path prefix.

```bash Cancel all open orders theme={null}
curl -X POST https://api.everstrike.io/auth/cancel/bulk \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -d '{"timestamp": 1700000000000, "signature": "YOUR_SIGNATURE"}'
```

Refer to the [full REST reference](https://docs.testnet.everstrike.io) for signing details and the complete endpoint list.

## WebSockets API

The WebSockets API streams order book, ticker, candle, trade, and liquidation updates for any subscribed pair. Authenticated connections also receive your personal order, position, and balance updates.

### Connect and Subscribe

<CodeGroup>
  ```python Python theme={null}
  #!/usr/bin/env python
  import asyncio
  import json
  import websockets

  API_KEY = "YOUR_API_KEY"  # Optional — omit for public data only

  async def run():
      uri = "wss://wss.testnet.everstrike.io"
      async with websockets.connect(uri) as ws:
          # Subscribe to all updates for the default BTC call option.
          await ws.send(json.dumps({"op": "sub_pair", "content": "USD_BTCCALL_PERP"}))

          # Optional: authenticate to receive personal order and position updates.
          await ws.send(json.dumps({"op": "auth_api", "content": API_KEY}))

          async for message in ws:
              parsed = json.loads(message)
              print(parsed["category"], parsed.get("pair"), parsed.get("result"))

  asyncio.get_event_loop().run_until_complete(run())
  ```

  ```javascript JavaScript theme={null}
  const WebSocket = require('ws');
  const socket = new WebSocket('wss://wss.testnet.everstrike.io');
  const API_KEY = 'YOUR_API_KEY'; // Optional — omit for public data only

  socket.on('open', () => {
    // Subscribe to all updates for the default BTC call option.
    socket.send(JSON.stringify({ op: 'sub_pair', content: 'USD_BTCCALL_PERP' }));

    // Optional: authenticate to receive personal order and position updates.
    socket.send(JSON.stringify({ op: 'auth_api', content: API_KEY }));

    // Keep the connection alive with a ping every 5 seconds.
    setInterval(() => socket.send(JSON.stringify({ op: 'status', content: 'ok' })), 5000);
  });

  socket.on('message', (raw) => {
    const message = JSON.parse(raw);
    console.log(message.category, message.pair, message.result);
  });
  ```
</CodeGroup>

### Subscribing to a Single Category

`sub_pair` subscribes to every category for a pair. To subscribe to just one channel, use `sub` with a `pair:category` string:

```json Subscribe to ticker only theme={null}
{ "op": "sub", "content": "USD_BTC_PERP:ticker" }
```

```json Unsubscribe from order book theme={null}
{ "op": "unsub", "content": "USD_BTC_PERP:depth" }
```

```json Unsubscribe from everything theme={null}
{ "op": "unsub_all", "content": "empty" }
```

Public categories: `depth`, `ticker`, `index`, `ohlcv`, `match`, `trades`, `liquidation`.

### Handling Messages

Every message contains `category`, `pair`, `result`, and `msg` fields. Dispatch on `category` to drive your application:

```javascript Message handler theme={null}
function handleMessage(message) {
  switch (message.category) {
    case 'ticker':      return console.info('New ticker:', message.result);
    case 'depth':       return console.info('Order book changed:', message.result);
    case 'ohlcv':       return console.info('New candle:', message.result.ohlcv);
    case 'trades':      return console.info('New trades:', message.result);
    case 'liquidation': return console.info('New liquidation:', message.result);
    case 'index':       return console.info('New mark price:', message.result.mark);

    // Requires authentication:
    case 'order_added':               return console.info('Order accepted:', message.result);
    case 'order_completed':           return console.info('Order fully filled:', message.result);
    case 'order_partially_completed': return console.info('Order partially filled:', message.result);
    case 'order_cancelled':           return console.info('Order cancelled:', message.result);
    case 'position_updated':          return console.info('Position updated:', message.result);
    case 'position_closed':           return console.info('Position closed:', message.result);

    case 'error': return console.error('Error:', message.msg);
    default:      return console.info('Unhandled:', message);
  }
}
```

### Authenticated Categories

Once authenticated with `auth_api`, you automatically receive updates for:

* `order_added`, `order_cancelled`, `order_triggered`
* `order_partially_completed`, `order_completed`
* `trigger_added`, `trigger_cancelled`, `trigger_failed`
* `deposit_added`, `deposit_completed`
* `withdrawal_completed`
* `position_updated`, `position_closed`

### Keeping the Connection Alive

Send a `status` ping every 5 seconds to prevent idle disconnection:

```json Ping theme={null}
{ "op": "status", "content": "empty" }
```

A connection that is neither subscribed to anything nor authenticated is closed after 30 seconds.

## Rate Limits

<Tabs>
  <Tab title="REST">
    | Limit            | Value                                                                    |
    | ---------------- | ------------------------------------------------------------------------ |
    | Requests         | Enforced per endpoint. Bulk order errors return `429 Too Many Requests`. |
    | Timestamp window | Requests with an old timestamp are rejected with `408 Request Timeout`.  |
  </Tab>

  <Tab title="WebSockets">
    | Limit                  | Value                                         |
    | ---------------------- | --------------------------------------------- |
    | Public subscriptions   | 10 categories per client                      |
    | Private subscriptions  | Unlimited (with authentication)               |
    | Concurrent connections | 10 per account and per IP                     |
    | Message rate           | 20 messages per second per account and per IP |
  </Tab>
</Tabs>

If you need more than 10 public subscriptions, split them across multiple connections.

## Trading Pairs

Pair keys follow a quote-first convention for perpetuals and base-first for spot:

| Instrument            | Example key                            |
| --------------------- | -------------------------------------- |
| Perpetual future      | `USD_BTC_PERP`, `USD_ETH_PERP`         |
| Perpetual call option | `USD_BTCCALL_PERP`, `USD_ETHCALL_PERP` |
| Perpetual put option  | `USD_BTCPUT_PERP`, `USD_ETHPUT_PERP`   |
| Spot                  | `BTC_USD`, `ETH_USD`                   |

Fetch the full canonical list from `https://api.everstrike.io/pairs`. Use the programmatic key, not the display symbol.

## Next Steps

<CardGroup cols={2}>
  <Card title="REST API Reference" icon="code" href="https://docs.testnet.everstrike.io">
    Full endpoint list, request signing, and response schemas.
  </Card>

  <Card title="WebSockets Reference" icon="bolt" href="https://everstrikeio.github.io/everstrike-websockets-api/">
    Complete message formats and category list.
  </Card>

  <Card title="MCP Server" icon="plug" href="/ai/mcp">
    Connect an AI client to live Everstrike market data.
  </Card>

  <Card title="Market Maker Bot" icon="github" href="https://github.com/everstrikeio/market_maker">
    Open-source reference implementation using the API.
  </Card>
</CardGroup>


## Related topics

- [Off-Chain Order Matching and Risk Engine on Everstrike](/technical-architecture/off-chain-matching.md)
- [Everstrike: Hybrid On-Chain and Off-Chain Architecture](/technical-architecture/technical-architecture.md)
- [Everstrike Terms of Service: Exchange User Agreement](/legal/terms-of-service.md)
- [Everstrike Privacy Policy: Your Data and Your Rights](/legal/privacy-policy.md)
- [Restricted Jurisdictions and Territories on Everstrike](/legal/restricted-jurisdictions-and-territories.md)
