> ## 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.

# Transmitir swaps de tokens Solana por WebSocket

> Crea un feed de swaps Solana por token, pool o wallet. Filtra por importe y gestiona las reconexiones.

Únete a `transaction:{tokenAddress}` para recibir swaps de un token. Limita el alcance por pool o wallet; las altas y bajas de liquidez usan salas separadas.

<Tip>
  **Sigue también la liquidez.** Suscríbete a `liquidity:{mint}` para recibir depósitos y retiros, o usa `events=all` en la API de operaciones por token para combinarlos con swaps. [Consulta la guía de liquidez](/es/guides/liquidity). Añade `:enriched` a las salas de transacciones o liquidez para obtener identidad de wallets.
</Tip>

<Info>
  **URL:** `wss://datastream.solanatracker.io/{apiKey}`\
  Disponible en los planes Premium, Business y Enterprise.
</Info>

## Suscríbete a las operaciones de un token

Únete a la sala `transaction:{tokenAddress}` para recibir todos los swaps de un 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}`);
  });
};
```

**Payload de la transacción:**

```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 }
  }
}
```

## Alertas de ballenas

Filtra las operaciones entrantes por volumen en USD para disparar una alerta de ballena cuando llegue una compra o venta grande:

```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.
    }
  });
};
```

## Detecta compras de snipers en el lanzamiento

Combina la hora del trade, la creación del token y el tamaño de la compra para filtrar actividad temprana. Este filtro no demuestra que una wallet sea un bot:

```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)}`);
    }
  });
};
```

## Trigger de copy-trading

Filtra trades por una lista de wallets y envía la actividad a un gestor de alertas:

```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
    }
  });
};
```

## Feed completo de operaciones con reconexión

Este ejemplo reconecta y vuelve a entrar en la sala. Consulta la [guía de conexión](/es/guides/datastream-protocol) para gestionar heartbeats y autenticación:

```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()
```

## Referencia de campos de transacción

| Campo | Tipo | Descripción |
| - | - | - |
| `tx` | string | Firma de la transacción |
| `type` | `"buy"` \| `"sell"` | Dirección de la operación |
| `volume` | number | Tamaño de la operación en USD |
| `solVolume` | number | Tamaño de la operación en SOL |
| `priceUsd` | number | Precio del token en el momento de la operación |
| `amount` | number | Cantidad de token operada |
| `wallet` | string | Dirección de la wallet del trader |
| `time` | number | Timestamp Unix (ms) |
| `program` | string | DEX usado (`raydium`, `pumpfun`, `okx`, etc.) |
| `token.from` | object | Token vendido |
| `token.to` | object | Token recibido |

## Guías relacionadas

* [Detección de snipers y bundlers](/es/guides/sniper-detection) — identifica wallets sniper a partir de datos históricos
* [Seguimiento de wallets](/es/guides/wallet-tracking) — sigue todas las operaciones de una wallet en cada token
* [Seguimiento de KOLs](/es/guides/kol-tracking) — encuentra a los mejores traders y crea feeds de copy-trading
* [Precios y gráficos en vivo](/es/guides/datastream-prices) — transmite actualizaciones de precio junto con los datos de operaciones


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