# WebSocket Channels

> Receive balance, PnL, runner and thesis events for your launches, plus the live SOL price, over the Centrifugo WebSocket.

Proxima pushes account events over a [Centrifugo](https://centrifugal.dev/) WebSocket. Use it to keep balances and
PnL up to date without polling the REST API. Payloads are JSON, carried over the standard Centrifugo client
protocol, so any official Centrifugo SDK works.

| Environment | URL |
| --- | --- |
| Production | `wss://ws.proxima.tools/connection/websocket` |
| Development | `wss://ws.proximatool.dev/connection/websocket` |

Market data for a single token (candles, trades, holders) comes from a different socket; see
[Market datafeed](/realtime/datafeed/).

## Connect

The socket does not accept your session JWT. It takes a short-lived **connection token** issued by the REST API:

```http
GET https://api-mig.proxima.tools/auth/ws-token
Authorization: Bearer <session JWT>
```

```json
{ "token": "<centrifugo connection token>" }
```

Pass a `getToken` callback to the Centrifugo client instead of a static token. The client calls it before
connecting and again whenever the connection token expires, so renewal is automatic.

> **Info:** Connect with an **upgraded** session token, bound to a license. See [Authentication](/getting-started/authentication/#token-kinds).
> Reconnect, and request a new connection token, whenever you switch license.

## Channels

You do not subscribe to channels yourself. The connection token grants a set of **server-side subscriptions**, and
every publication arrives through the client-level `publication` event.

| Channel | Payload |
| --- | --- |
| `proxima:#{account_id}` | [Event envelope](#event-envelope) for your launches: `BalanceUpdate`, `LaunchInfoUpdate`, `Runners` or `Thesis`. |
| `proxima:#{license_key}` | The same envelopes, published on the license's channel. Read only one of the two account channels to avoid handling each event twice. |
| `live:price:solana` | [`{ "price": number }`](#live-sol-price), the SOL price in USD. |

The `account_id` is a claim in the payload of your upgraded session JWT. Decode the payload (no verification needed
for this purpose) to build the account channel name.

## Event envelope

Every publication on the account channel shares the same envelope:

| Field | Type | Description |
| --- | --- | --- |
| `launchId` | string | The launch the event concerns, as a decimal string. Compare it as a string. |
| `type` | string | `BalanceUpdate`, `LaunchInfoUpdate`, `Runners` or `Thesis`. Ignore publications without a `type`. |
| `data` | object \| array | Event payload, described below. An array with a single element should be unwrapped to that element. |

```json
{
  "launchId": "4821",
  "type": "LaunchInfoUpdate",
  "data": { "pnl_native": "1520000000", "pnl_usd": "284910000" }
}
```

### BalanceUpdate

Wallet balances of a launch changed, typically after a confirmed withdrawal, nuke or pool deploy. `data` is one
balance object or an array of them. Amounts are raw integer strings: lamports on Solana, wei on EVM chains.

| Field | Type | Description |
| --- | --- | --- |
| `wallet` | string | Wallet public key or address. |
| `token_balance` | string | Optional. Token balance in base units. |
| `native_balance` | string | Optional. Native balance in base units. |
| `quote_balance` | string | Optional. Quote-token balance in base units. |

A missing field means "unchanged": keep the value you already have.

```json
{
  "launchId": "4821",
  "type": "BalanceUpdate",
  "data": [
    { "wallet": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM", "token_balance": "12500000000000", "native_balance": "48210000" },
    { "wallet": "3Kz9pJ8rWm2vT6xYqB5nH4cL1dF7gA9sE2uR8tN6wQpM", "native_balance": "0" }
  ]
}
```

### LaunchInfoUpdate

The launch's PnL and buy and sell totals were recomputed. All values are integer strings, scaled the same way as
the REST launch info.

| Field | Type | Description |
| --- | --- | --- |
| `pnl_native` | string | PnL in the native currency. Always present. |
| `pnl_usd` | string | PnL in USD. Always present. |
| `total_buy_native`, `total_buy_tokens`, `total_buy_usd` | string | Optional. Totals bought. |
| `total_sell_native`, `total_sell_tokens`, `total_sell_usd` | string | Optional. Totals sold. |
| `extra_rewards_native`, `extra_rewards_usd` | string | Optional. Extra rewards earned. |

For the optional fields, `null`, `""` or a missing value means "unchanged".

### Runners

Results from the auto-buy and auto-sell runners of the launch.

| Field | Type | Description |
| --- | --- | --- |
| `autosellSolPnl` | string | Optional. Auto-sell PnL in SOL. |
| `autosellTokenSold` | string | Optional. Tokens sold by auto-sell. |
| `autobuySolPnl` | string | Optional. Auto-buy PnL in SOL. |
| `autobuyTokenBought` | string | Optional. Tokens bought by auto-buy. |

> **Info:** `Runners` is not emitted on every deployment yet, and its field casing may move to snake_case. Treat it as
> informational.

### Thesis

A new thesis (a public callout) about the launch's token, collected from a social feed. `data` has the same shape
as the items of the REST thesis endpoint. Upsert it by `id`.

| Field | Type | Description |
| --- | --- | --- |
| `id` | string | Thesis ID. |
| `source` | string | `pumpfun` or `fomo`. |
| `author_handle`, `author_name`, `x_username` | string \| null | Author identity. |
| `verified` | boolean \| null | The author is verified. |
| `is_dev` | boolean \| null | The author is the token's developer. |
| `text` | string | Thesis text. |
| `media_url` | string \| null | Attached media. |
| `created_at` | integer | Epoch milliseconds. |
| `likes` | integer \| null | Like count. |
| `mcap_at_call` | number \| null | Market cap when the callout was made (`pumpfun` only). |
| `multiple` | number \| null | Multiple since the callout (`pumpfun` only). |
| `pnl_usd` | number \| null | Author PnL in USD (`fomo` only). |
| `author_avatar_url`, `token_image_url` | string \| null | Images. |

## Live SOL price

Publications on `live:price:solana` carry the SOL price in USD as a plain decimal. Ignore values that are not
positive numbers.

```json
{ "price": 187.42 }
```

## Reconnection and recovery

- **Transport drops.** Centrifugo SDKs reconnect on their own with backoff. Keep the default settings.
- **Errors.** On a client `error` event, rebuild the client after a short delay (the web app waits 5 seconds) with
  the same `getToken`.
- **Token expiry.** Handled by `getToken`; no extra logic is needed.
- **Missed publications.** Track the highest publication `offset` you have processed per channel. When a
  `subscribed` event reports `recovered: false`, call `history(channel, { limit: 30 })` and replay publications with
  a higher offset. For account events, refetch the launch over REST instead: it is the source of truth.

## Example

A minimal Node.js listener using [`centrifuge`](https://www.npmjs.com/package/centrifuge) and
[`ws`](https://www.npmjs.com/package/ws). In a browser, drop the `ws` import and the `websocket` option.

```js

const API_URL = "https://api-mig.proxima.tools";
const WS_URL = "wss://ws.proxima.tools/connection/websocket";
const SESSION_JWT = process.env.PROXIMA_JWT; // upgraded session token

function accountChannel(jwt) {
  const payload = JSON.parse(Buffer.from(jwt.split(".")[1], "base64url").toString("utf8"));
  return payload.account_id ? `proxima:#${payload.account_id}` : null;
}

async function getToken() {
  const res = await fetch(`${API_URL}/auth/ws-token`, {
    headers: { Authorization: `Bearer ${SESSION_JWT}` },
  });
  if (!res.ok) throw new Error(`ws-token failed: ${res.status}`);
  return (await res.json()).token;
}

const eventChannel = accountChannel(SESSION_JWT);
const client = new Centrifuge(WS_URL, { getToken, websocket: WebSocket });

client.on("publication", ({ channel, data: message }) => {
  if (channel === "live:price:solana") {
    if (message.price > 0) console.log("SOL/USD", message.price);
    return;
  }
  if (channel !== eventChannel) return; // other account channels repeat the same events

  const { launchId, type } = message;
  const data = Array.isArray(message.data) && message.data.length === 1 ? message.data[0] : message.data;
  switch (type) {
    case "BalanceUpdate":
      for (const balance of [].concat(data)) console.log(launchId, balance.wallet, balance.native_balance);
      break;
    case "LaunchInfoUpdate":
      console.log(launchId, "pnl", data.pnl_native, data.pnl_usd);
      break;
    case "Thesis":
      console.log(launchId, "thesis", data.source, data.text);
      break;
    default:
      console.log(launchId, type, data);
  }
});

client.connect();
```
