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

# 流式实时交易与转账

> 通过 WebSocket 订阅任意 Solana 代币的实时兑换交易——构建实时交易推送、上线狙击检测、巨鲸提醒、跟单触发器与机器人。

Datastream WebSocket 在交易记录到 Solana 后的几毫秒内即时推送任意代币的兑换交易。一次连接和一个 room 即可为您的处理器提供每一笔买入和卖出。

<Info>
  **URL:** `wss://datastream.solanatracker.io/{apiKey}`\
  适用于 Premium、Business 和 Enterprise 方案。
</Info>

***

## 订阅某代币的交易

加入 `transaction:{tokenAddress}` room 以接收代币的所有兑换:

```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:**

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

***

## 巨鲸提醒

按美元成交量过滤接收的交易,当大额买入或卖出发生时触发巨鲸提醒:

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

***

## 在上线时检测狙击买入

当新代币上线时,头几笔交易通常来自狙击机器人。这些是在前几秒内买入的自动化钱包。关注早期买入,以及相对于代币年龄而言的大笔美元规模:

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

***

## 跟单触发器

监视特定钱包(KOL、巨鲸、您关注的交易者)的交易,当他们买入时触发跟单交易:

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

***

## 完整的实时交易推送(带重连)

生产可用的推送,带有自动重连和干净关闭:

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

***

## 交易字段参考

| 字段           | 类型                  | 描述                                   |
| ------------ | ------------------- | ------------------------------------ |
| `tx`         | string              | 交易签名                                 |
| `type`       | `"buy"` \| `"sell"` | 交易方向                                 |
| `volume`     | number              | 美元交易规模                               |
| `solVolume`  | number              | SOL 交易规模                             |
| `priceUsd`   | number              | 交易时的代币价格                             |
| `amount`     | number              | 交易的代币数量                              |
| `wallet`     | string              | 交易者的钱包地址                             |
| `time`       | number              | Unix 时间戳(毫秒)                         |
| `program`    | string              | 使用的 DEX(`raydium`、`pumpfun`、`okx` 等) |
| `token.from` | object              | 卖出的代币                                |
| `token.to`   | object              | 收到的代币                                |

***

## 相关指南

* [狙击者与 Bundler 检测](/cn/guides/sniper-detection) — 从历史数据中识别狙击钱包
* [钱包追踪](/cn/guides/wallet-tracking) — 追踪某个钱包在每个代币上的所有交易
* [KOL 追踪](/cn/guides/kol-tracking) — 查找顶级交易者并构建跟单推送
* [实时价格与图表](/cn/guides/datastream-prices) — 在交易数据旁边同时流式传输价格更新
