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

# Stream Solana Wallet and Position PnL

> Subscribe to Solana wallet PnL, position changes, and summaries. Pair PnL rooms with price streams for live unrealized returns.

Use a PnL room to keep wallet totals or token positions current after loading a REST snapshot. Add a price room when the display needs unrealized PnL updates between trades.

> [!NOTE]
>
> PnL V2 Datastream is available on **Premium, Business, and Enterprise** plans.\
> Connect to `wss://datastream.solanatracker.io/{apiKey}` with your Data API key.

## Room types

Choose whether the display needs one position, all positions, or wallet totals:

| Room | What it emits | Use when |
| - | - | - |
| `pnl:{wallet}:{token}` | `tradeUpdate`, `balanceUpdate`, `priceUpdate` for one token | You're tracking one specific position |
| `pnl:{wallet}` | `tradeUpdate`, `balanceUpdate`, `priceUpdate` for all tokens | You want live updates on every position a wallet holds |
| `pnl:{wallet}:summary` | Total wallet PnL summary | You want aggregated wallet-level PnL totals |

> [!NOTE]
>
> PnL rooms report trades with `tradeUpdate`, balance changes with `balanceUpdate`, and periodic valuations with `priceUpdate`. Add a [price stream](#fastest-live-unrealized-pnl-combining-rooms) to update unrealized PnL between position events.

## Connecting

```javascript theme={null}
const ws = new WebSocket("wss://datastream.solanatracker.io/YOUR_API_KEY");

ws.onopen = () => {
  // subscribe to a room
  ws.send(JSON.stringify({
    type: "join",
    room: "pnl:WALLET_ADDRESS:TOKEN_ADDRESS"
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log(msg.type, msg.data);
};
```

## Room: pnl:\{wallet}:\{token}

Subscribe to one wallet-token position. Trade and balance notifications update the position; periodic `priceUpdate` messages refresh its price-dependent values.

**`tradeUpdate`** reports a buy or sell:

```json theme={null}
{
  "type": "message",
  "room": "pnl:DJqkH...D61:A7Fbn...pump",
  "data": {
    "type": "tradeUpdate",
    "wallet": "DJqkH...D61",
    "token": "A7Fbn...pump",
    "buyCount": 3,
    "sellCount": 1,
    "totalBuyUsd": 0.0257,
    "totalSellUsd": 0.0043,
    "avgCostPerToken": 0.000082,
    "currentBalance": 205.39,
    "currentPrice": 0.0000911,
    "currentValue": 0.01871,
    "holdingCostBasis": 0.01715,
    "realizedPnl": -0.00087,
    "unrealizedPnl": 0.00156,
    "proceeds": 0.0043,
    "totalTransactions": 4
  }
}
```

**`balanceUpdate`** reports a position balance update:

```json theme={null}
{
  "type": "message",
  "room": "pnl:DJqkH...D61:A7Fbn...pump",
  "data": {
    "type": "balanceUpdate",
    "wallet": "DJqkH...D61",
    "token": "A7Fbn...pump",
    "avgCostPerToken": 0.0000835,
    "currentBalance": 205.39,
    "currentPrice": 0.0000911,
    "currentValue": 0.01871,
    "holdingCostBasis": 0.01715,
    "unrealizedPnl": 0.00156
  }
}
```

### Subscribe example

```javascript theme={null}
ws.send(JSON.stringify({
  type: "join",
  room: "pnl:DJqkHSmx9XosFpNqdi2DevtNgaf52oow4pFpJECv6D61:A7FbnhhkY2R6hZhkT2oexNNFQyGG7cBZJLWmC32spump"
}));
```

## Room: pnl:\{wallet}

Subscribe to `pnl:{wallet}` for updates across a wallet's positions. You do not need a separate PnL subscription for each mint.

```javascript theme={null}
ws.send(JSON.stringify({
  type: "join",
  room: "pnl:DJqkHSmx9XosFpNqdi2DevtNgaf52oow4pFpJECv6D61"
}));

ws.onmessage = (event) => {
  const { data } = JSON.parse(event.data);
  if (!data) return;

  if (data.type === "tradeUpdate") {
    console.log(`Trade on ${data.token}: unrealized PnL $${data.unrealizedPnl.toFixed(4)}`);
  }
  if (data.type === "balanceUpdate") {
    console.log(`Price update for ${data.token}: value now $${data.currentValue.toFixed(4)}`);
  }
};
```

> [!TIP]
>
> Use `pnl:{wallet}` when building a live portfolio dashboard — you only need one room subscription per wallet.

## Room: pnl:\{wallet}:summary

Receive the wallet's total PnL summary whenever the aggregate changes. This room returns wallet-level totals, not individual positions.

```json theme={null}
{
  "type": "message",
  "room": "pnl:DJqkH...D61:summary",
  "data": {
    "averages": {
      "buy": 1.1751933473135445,
      "sell": 1.7625162156883138
    },
    "counts": {
      "buys": 1664,
      "sells": 745,
      "tokensHeldEver": 842,
      "tokensTraded": 862,
      "trades": 2409
    },
    "invested": 708.3246017180338,
    "openPositions": {
      "cost": 962.9218710198314,
      "value": 37.196319618271204
    },
    "pnl": {
      "realized": 604.7499789697601,
      "total": -421.18843262884593,
      "unrealized": -1025.938411598606
    },
    "proceeds": 1313.0745806877937,
    "roi": -59.46262936614906,
    "timing": {
      "firstTrade": 1704067810000,
      "lastTrade": 1778966213113
    }
  }
}
```

```javascript theme={null}
ws.send(JSON.stringify({
  type: "join",
  room: "pnl:DJqkHSmx9XosFpNqdi2DevtNgaf52oow4pFpJECv6D61:summary"
}));

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.room !== `pnl:${wallet}:summary`) return;
  const { data } = msg;

  console.log(`Total PnL: $${data.pnl.total.toFixed(2)}`);
  console.log(`Realized: $${data.pnl.realized.toFixed(2)}`);
  console.log(`Unrealized: $${data.pnl.unrealized.toFixed(2)}`);
  console.log(`ROI: ${data.roi.toFixed(2)}%`);
};
```

## Update unrealized PnL with price streams

Use PnL room values for cost basis, realized PnL, and token balance. A separate price stream can update the valuation between position events.

To update unrealized PnL on price ticks, pair the position room with one of these price rooms:

| Stream | What it gives you |
| - | - |
| `pnl:{wallet}` (or `pnl:{wallet}:{token}`) | Live cost basis, FIFO realized PnL, balance changes, trade fills |
| `price:aggregated:{token}` | Cross-pool price summary |
| `price-by-token:{token}` | Price from the primary pool |

Use the PnL room as the source of truth for `currentBalance` and `holdingCostBasis`, and recompute `unrealizedPnl = (currentBalance × livePrice) − holdingCostBasis` whenever a price tick arrives.

### Example: live unrealized PnL on a single position

```javascript theme={null}
const wallet = "DJqkHSmx9XosFpNqdi2DevtNgaf52oow4pFpJECv6D61";
const token  = "A7FbnhhkY2R6hZhkT2oexNNFQyGG7cBZJLWmC32spump";

const ws = new WebSocket("wss://datastream.solanatracker.io/YOUR_API_KEY");

const position = {
  balance: 0,
  costBasis: 0,
  realizedPnl: 0,
  livePrice: 0,
};

const recompute = () => {
  const value = position.balance * position.livePrice;
  const unrealized = value - position.costBasis;
  console.log(
    `value=$${value.toFixed(4)}  unrealized=$${unrealized.toFixed(4)}  realized=$${position.realizedPnl.toFixed(4)}`
  );
};

ws.onopen = () => {
  ws.send(JSON.stringify({ type: "join", room: `pnl:${wallet}:${token}` }));
  ws.send(JSON.stringify({ type: "join", room: `price:aggregated:${token}` }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type !== "message") return;
  const d = msg.data;

  if (d?.type === "tradeUpdate" || d?.type === "balanceUpdate") {
    position.balance   = d.currentBalance;
    position.costBasis = d.holdingCostBasis;
    if (d.type === "tradeUpdate") position.realizedPnl = d.realizedPnl;
    position.livePrice = d.currentPrice;
    recompute();
    return;
  }

  if (msg.room?.startsWith("price:aggregated:")) {
    position.livePrice = d.price;
    recompute();
  }
};
```

### Example: live unrealized PnL across an entire wallet

Subscribe to `pnl:{wallet}` for trade and balance updates on every position, then dynamically subscribe to a price room for each token the wallet holds.

> [!WARNING]
>
> Price streams can update often. In production, batch UI updates or throttle logs so every price tick does not flood your console or browser.

```javascript theme={null}
const wallet = "DJqkHSmx9XosFpNqdi2DevtNgaf52oow4pFpJECv6D61";
const ws = new WebSocket("wss://datastream.solanatracker.io/YOUR_API_KEY");
const positions = new Map(); // token -> { balance, costBasis, realizedPnl, livePrice }
const subscribed = new Set();

const portfolioUnrealized = () => {
  let total = 0;
  for (const p of positions.values()) {
    total += p.balance * p.livePrice - p.costBasis;
  }
  return total;
};

const subscribePrice = (token) => {
  if (subscribed.has(token)) return;
  subscribed.add(token);
  // Use price:aggregated for high-liquidity tokens, price-by-token for memecoins / single-pool
  ws.send(JSON.stringify({ type: "join", room: `price:aggregated:${token}` }));
};

ws.onopen = () => {
  ws.send(JSON.stringify({ type: "join", room: `pnl:${wallet}` }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type !== "message") return;
  const d = msg.data;

  if (d?.type === "tradeUpdate" || d?.type === "balanceUpdate") {
    const p = positions.get(d.token) ?? { balance: 0, costBasis: 0, realizedPnl: 0, livePrice: 0 };
    p.balance   = d.currentBalance;
    p.costBasis = d.holdingCostBasis;
    p.livePrice = d.currentPrice;
    if (d.type === "tradeUpdate") p.realizedPnl = d.realizedPnl;
    positions.set(d.token, p);
    subscribePrice(d.token);
  }

  if (msg.room?.startsWith("price:aggregated:")) {
    const token = msg.room.split(":")[2];
    const p = positions.get(token);
    if (!p) return;
    p.livePrice = d.price;
    positions.set(token, p);
  }

  console.log(`Portfolio unrealized PnL: $${portfolioUnrealized().toFixed(4)}`);
};
```

> [!TIP]
>
> **Choose a price source**
>
> * `price:aggregated:{token}` — Cross-pool median price.
> * `price-by-token:{token}` — primary-pool price. Slightly lower latency for memecoins or anything that effectively trades on a single pool.

### `priceUpdate` payload (PnL room)

A PnL `priceUpdate` is a periodic position refresh. Its cadence differs from the dedicated price streams:

```json theme={null}
{
  "type": "message",
  "room": "pnl:DJqkH...D61:A7Fbn...pump",
  "data": {
    "type": "priceUpdate",
    "wallet": "DJqkH...D61",
    "token": "A7Fbn...pump",
    "currentBalance": 205.39,
    "currentPrice": 0.0000911,
    "currentValue": 0.01871,
    "holdingCostBasis": 0.01715,
    "unrealizedPnl": 0.00156
  }
}
```

## Unsubscribing

Leave any room by sending a `leave` message:

```javascript theme={null}
ws.send(JSON.stringify({
  type: "leave",
  room: "pnl:DJqkHSmx9XosFpNqdi2DevtNgaf52oow4pFpJECv6D61:summary"
}));
```

## Related guides

> [card] [PnL guides](https://docs.solanatracker.io/guides/pnl-v2/index)
>
> Core PnL V2 concepts, endpoints, and how wallet indexing works.

> [card] [Live prices](https://docs.solanatracker.io/guides/datastream-prices.md)
>
> `price:aggregated` and `price-by-token` rooms — pair these with PnL for live unrealized PnL.

> [card] [Wallet PnL](https://docs.solanatracker.io/guides/pnl-v2/wallet-analysis.md)
>
> Analyze wallet PnL, positions, trade timing, and exposure with the REST API.

> [card] [Holdings and trades](https://docs.solanatracker.io/guides/wallet-tracking.md)
>
> Combine live wallet activity with PnL streams for a real-time portfolio dashboard.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.