# Follow a Launch in Realtime

> Keep a launch's balances, PnL and price chart up to date by combining one REST snapshot with the account WebSocket and the market datafeed.

This guide builds what the web app's launch page shows: wallet balances and PnL that move on their own, and a live
candle chart. You read the launch once over REST, then apply the changes pushed by two sockets:

- the [account WebSocket](/realtime/websocket/) for balances and PnL;
- the [market datafeed](/realtime/datafeed/) for candles and trades.

Those pages describe both protocols in full. This guide only chains them for one launch.

You need:

- an upgraded session token in `$PROXIMA_JWT` ([Quickstart](/getting-started/quickstart/));
- a launch you own, here `101250846193377`.

## 1. Load the snapshot

[Retrieve a launch](/reference/launches/#retrieve-launch) returns every wallet of the launch with its balances, and
the launch's PnL. Push events only carry what changed, so they need this starting point.

```bash
curl https://api-mig.proxima.tools/launch/get-launch-info/101250846193377 \
  -H "Authorization: Bearer $PROXIMA_JWT"
```

```json
{
  "dev": { "key": { "pubkey": "8M4PPg4goA6dH3HTQs7kFtJwgvb3dRgNaMioaGdgGsxA" }, "native_balance": "21400000", "token_balance": "20000000000000" },
  "funder": { "key": { "pubkey": "2iXMR8bo1TxZWW4gh8WdZdUXELjhGmQ8UBwbqGEYV2KF" }, "native_balance": "214000000" },
  "holder": [
    { "key": { "pubkey": "6i6zd3qY5tT7d1LwhqNkQ7pNXzeaqMQP6WjpJ14273VP" }, "native_balance": "3100000", "token_balance": "15873015873015" }
  ],
  "front_mev": [],
  "back_mev": [],
  "temp_holder": [],
  "pnl_native": "-12500000",
  "pnl_usd": "-2.31"
}
```

**Keep:** the whole object. Wallets are matched by `key.pubkey` in step 3.

## 2. Get a connection token

The account WebSocket does not take your session token. [Create a realtime token](/reference/authentication/#create-realtime-token)
issues a short-lived connection token.

```bash
curl https://api-mig.proxima.tools/auth/ws-token \
  -H "Authorization: Bearer $PROXIMA_JWT"
```

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

Events for your launches arrive on the channel `proxima:#{account_id}`. `account_id` is a claim in the payload of
your session token: decode the middle part of the JWT to read it.

**Keep:** a function that fetches this token, and the channel name. Centrifugo clients take the function as
`getToken` and call it again whenever the token expires.

## 3. Apply balance and PnL events

Connect to `wss://ws.proxima.tools/connection/websocket` with any Centrifugo client, as in the
[WebSocket example](/realtime/websocket/#example). You do not subscribe to anything: publications for all your
launches arrive through the client's `publication` event. Keep those whose `launchId` is your launch, compared as a
string, and patch the snapshot:

- `BalanceUpdate` carries one or more wallets. Overwrite only the balance fields that are present.
- `LaunchInfoUpdate` always carries `pnl_native` and `pnl_usd`. The other totals are optional: `null`, `""` or a
  missing value means "unchanged".

```js
// client and eventChannel come from the WebSocket example; launch is the snapshot from step 1.
const LAUNCH_ID = "101250846193377";

client.on("publication", ({ channel, data: event }) => {
  if (channel !== eventChannel || event.launchId !== LAUNCH_ID) return;

  if (event.type === "BalanceUpdate") {
    const updates = [].concat(event.data);
    const wallets = [launch.dev, launch.funder, ...launch.holder, ...launch.front_mev, ...launch.back_mev, ...launch.temp_holder];
    for (const wallet of wallets.filter(Boolean)) {
      const update = updates.find((u) => u.wallet === wallet.key?.pubkey);
      if (!update) continue;
      for (const field of ["native_balance", "token_balance", "quote_balance"]) {
        if (update[field] !== undefined) wallet[field] = update[field];
      }
    }
  }

  if (event.type === "LaunchInfoUpdate") {
    const data = Array.isArray(event.data) ? event.data[0] : event.data;
    launch.pnl_native = data.pnl_native;
    launch.pnl_usd = data.pnl_usd;
    for (const [field, value] of Object.entries(data)) {
      if (value !== null && value !== "") launch[field] = value;
    }
  }
});
```

The envelope and every field are described in [Event envelope](/realtime/websocket/#event-envelope).

> **Info:** Events also go out on `proxima:#{license_key}`. Handle one of the two account channels only, or every event
> arrives twice.

**Keep:** the patched snapshot. It is your live view of the launch.

## 4. Get a chart token

The datafeed authenticates per token address. [Create a chart token](/reference/charts/#create-chart-token) returns
the mint of the launch and a token for it. It only works for launches you own: a launch shared with you answers
`404`.

```bash
curl https://api-mig.proxima.tools/charts/101250846193377/subscribe \
  -H "Authorization: Bearer $PROXIMA_JWT"
```

```json
{ "ok": true, "chain": "sol", "mint": "2uTPPCyoFbbzZFzp1se6pCvSDx8MUYyUR3i99eP5pump", "token": "<chart token>" }
```

A pump.fun launch has its mint from creation, so this works on a draft too. On launchpads that assign the address
at deploy, as on EVM chains, the call answers `404` `Token not launched yet` until the deploy lands. Retry with
backoff (1 second, doubling up to 5 seconds), as the app does.

**Keep:** `mint` and `token`. The token is a JWT whose payload carries `exp`.

## 5. Authenticate on the datafeed

The datafeed also wants your license key. [Retrieve the current session](/reference/authentication/#retrieve-current-session)
returns it as `license_key`.

```bash
curl https://api-mig.proxima.tools/auth/me \
  -H "Authorization: Bearer $PROXIMA_JWT"
```

Open `wss://datafeed.proxima.tools/ws` and send `authenticate` with both values. Frames are Protocol Buffers. They are
shown here as JSON; [Framing](/realtime/datafeed/#framing) explains the encoding. Note the British spelling of
`licenceKey`.

```json
{ "rpcRequest": { "id": "01d931e2-7df2-46c9-a123-c0582ec07e5b", "authenticate": { "token": "<chart token>", "licenceKey": "<license_key>" } } }
```

Wait for the response before you send anything else for this mint.

**Keep:** the open socket. Steps 6 and 7 use it.

## 6. Load the candles and subscribe

Follow the four calls of [History](/realtime/datafeed/#history), in order:

1. `getConfig`, for the resolutions the server supports.
2. `resolveSymbol` with `{ "symbol": "<mint>" }`. Keep the `ticker` it returns.
3. `getBars` with the `ticker`, a [resolution](/realtime/datafeed/#resolutions) and a time range. Repeat it for
   older pages until `noData` is `true`.
4. `subscribeBars` with the same `ticker` and resolution, and a `subscriberUid` you choose.

```json
{ "rpcRequest": { "id": "7c6b5a49-3827-4165-9a8b-1c2d3e4f5a6b", "subscribeBars": { "symbol": "2uTPPCyoFbbzZFzp1se6pCvSDx8MUYyUR3i99eP5pump", "resolution": "1S", "subscriberUid": "chart-1S" } } }
```

From then on, each `bar` push with your `subscriberUid` replaces the last candle or appends a new one. The same
socket also pushes `trade`, `holder`, `volume` and `priceChange` for the mint; see [Live updates](/realtime/datafeed/#live-updates).
The [datafeed example](/realtime/datafeed/#example) runs steps 4 to 6 in one script.

**Keep:** the `subscriberUid`, to subscribe again after a reconnect.

## 7. Stay in sync

Both sockets need a little care to keep running:

| What | When | What to do |
| --- | --- | --- |
| Connection token | It expires | Nothing: the Centrifugo client calls `getToken` again. |
| Account WebSocket | The client reports `recovered: false` after a reconnect | Some events were lost. Reload the snapshot (step 1). |
| Chart token | About 90 seconds before `exp` | Request a new one (step 4) and send `authenticate` again on the open socket. Subscriptions stay in place. |
| Datafeed socket | It closes | Reconnect after a few seconds, authenticate again, resend `subscribeBars` and reload the candles. Pushes are not replayed. |

[Reconnection and recovery](/realtime/websocket/#reconnection-and-recovery) and
[Reconnection](/realtime/datafeed/#reconnection) give the details.

## Next steps

- [WebSocket channels](/realtime/websocket/): `Runners` and `Thesis` events, and the live SOL price.
- [Market datafeed](/realtime/datafeed/): trades, holders and the full Protobuf schema.
- [Sell automatically](/guides/auto-sell/): put the PnL you are watching to work.
- [Datafeed HTTP](/reference/datafeed-http/): symbol stats and wallet reads without a socket.
