> ## 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 token swaps over WebSocket

> Build a Solana trade feed with Datastream token and pool subscriptions. Filter swaps by size or wallet and handle reconnects.

Subscribe to `transaction:{tokenAddress}` for a token's live swap feed. Narrow the room to a pool or wallet when needed. Liquidity additions and removals use separate rooms.

<Tip>
  **Track liquidity too.** Subscribe to `liquidity:{mint}` for additions and removals, or use `events=all` on the token trade API to combine them with swaps. [Follow the liquidity guide](/guides/liquidity). Append `:enriched` to transaction or liquidity rooms for wallet identity.
</Tip>

<Info>
  **URL:** `wss://datastream.solanatracker.io/{apiKey}`\
  Available on Premium, Business, and Enterprise plans.
</Info>

## Subscribe to a token's trades

Join the `transaction:{tokenAddress}` room to receive all swaps for a token:

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

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

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

  // msg.data is an array of transactions
  msg.data.forEach(tx => {
    const side  = tx.type === "buy" ? "BUY " : "SELL";
    const usd   = tx.volume.toFixed(2);
    const price = tx.priceUsd.toFixed(6);
    console.log(`${side} $${usd} @ $${price} — ${tx.wallet.slice(0, 8)}... via ${tx.program}`);
  });
};
```

**Transaction payload:**

```json theme={null}
{
  "tx": "5V4apVkgHf49J5acYPiuh5rB89EGsF8ocSysgnD9vFfZsTtDamhN3MFDKJSq7Dn7Z6Y5XhjghuVYuvvYWnSFpnvW",
  "amount": 90,
  "priceUsd": 6.002467911111111,
  "solVolume": 2.956,
  "volume": 540.22,
  "type": "sell",
  "wallet": "F7R61te4Ac8xZ4pfkJUdF6iaaHy9tnM8nVRUPv8H8EMi",
  "time": 1760201288835,
  "program": "raydium",
  "token": {
    "from": { "name": "OFFICIAL TRUMP", "symbol": "TRUMP", "amount": 90 },
    "to":   { "name": "USD Coin",        "symbol": "USDC",  "amount": 540.22 }
  }
}
```

## Whale alerts

Filter incoming trades by USD volume to fire a whale alert when a large buy or sell hits:

```javascript theme={null}
const WHALE_THRESHOLD_USD = 10000; // $10k+

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

  msg.data.forEach(tx => {
    if (tx.volume >= WHALE_THRESHOLD_USD) {
      const side = tx.type === "buy" ? "🟢 WHALE BUY" : "🔴 WHALE SELL";
      console.log(`${side} — $${tx.volume.toLocaleString()} by ${tx.wallet}`);
      // trigger your alert: push notification, Discord webhook, etc.
    }
  });
};
```

## Detect sniper buys at launch

A launch feed can highlight early buys by combining trade time, token creation time, and trade size. Treat this as an activity filter, not a bot classification:

```javascript theme={null}
let launchTime = null; // First message sets the starting time.
const SNIPER_WINDOW_MS = 10_000; // first 10 seconds

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

  msg.data.forEach(tx => {
    if (!launchTime) launchTime = tx.time;

    const ageMs = tx.time - launchTime;
    const isEarly = ageMs < SNIPER_WINDOW_MS;

    if (isEarly && tx.type === "buy") {
      console.log(`🎯 Early buy (${(ageMs / 1000).toFixed(1)}s after launch)`);
      console.log(`   Wallet: ${tx.wallet}`);
      console.log(`   Amount: $${tx.volume.toFixed(2)}`);
    }
  });
};
```

## Copy-trading trigger

Filter for a set of wallet addresses to send activity to an alert handler:

```javascript theme={null}
// Wallets you want to copy-trade
const WATCHED_WALLETS = new Set([
  "FV1r15rbNKkJanXLheoJA7fXEq6NDuMJ3bukXuhJWyV1",
  "4Rz5xqikxtZ2s7wE9uQ6n2oLXQi6K65XGoYpKxf24Hqo"
]);

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

  msg.data.forEach(tx => {
    if (WATCHED_WALLETS.has(tx.wallet) && tx.type === "buy") {
      console.log(`📡 Copy-trade trigger: ${tx.wallet.slice(0, 8)}... bought $${tx.volume.toFixed(2)}`);
      // → call your swap API here
    }
  });
};
```

## Full live trade feed with reconnect

This example reconnects and rejoins the token room. Use the [connection guide](/guides/datastream-protocol) for heartbeat and authentication handling:

```javascript theme={null}
function startTradeFeed(token, onTrade) {
  let ws;
  let reconnectTimeout;

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

    ws.onopen = () => {
      console.log(`Subscribed to trades for ${token}`);
      ws.send(JSON.stringify({ type: "join", room: `transaction:${token}` }));
    };

    ws.onmessage = (event) => {
      const msg = JSON.parse(event.data);
      if (msg.type === "message") {
        msg.data.forEach(onTrade);
      }
    };

    ws.onclose = () => {
      console.log("Disconnected — reconnecting in 3s");
      reconnectTimeout = setTimeout(connect, 3000);
    };

    ws.onerror = (err) => {
      console.error("Stream error:", err.message);
      ws.close();
    };
  }

  connect();

  return () => {
    clearTimeout(reconnectTimeout);
    ws?.close();
  };
}

// Usage
const stop = startTradeFeed(
  "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN",
  (tx) => {
    const side = tx.type === "buy" ? "BUY " : "SELL";
    console.log(`${side} $${tx.volume.toFixed(2)} — ${tx.wallet.slice(0, 8)}...`);
  }
);

// Stop later: stop()
```

## Transaction fields reference

| Field | Type | Description |
| - | - | - |
| `tx` | string | Transaction signature |
| `type` | `"buy"` \| `"sell"` | Trade direction |
| `volume` | number | Trade size in USD |
| `solVolume` | number | Trade size in SOL |
| `priceUsd` | number | Token price at time of trade |
| `amount` | number | Token amount traded |
| `wallet` | string | Trader's wallet address |
| `time` | number | Unix timestamp (ms) |
| `program` | string | DEX used (`raydium`, `pumpfun`, `okx`, etc.) |
| `token.from` | object | Token sold |
| `token.to` | object | Token received |

## Related guides

* [Sniper & Bundler Detection](/guides/sniper-detection) — identify sniper wallets from historical data
* [Wallet Tracking](/guides/wallet-tracking) — track all trades across every token for a wallet
* [KOL Tracking](/guides/kol-tracking) — find top traders and build copy-trading feeds
* [Live Prices & Charts](/guides/datastream-prices) — stream price updates alongside trade data


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