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

# 实时价格与图表

> 通过 Solana Tracker Datastream WebSocket 流式传输实时代币价格与 OHLCV K 线——构建实时图表、行情、价格告警与交易仪表盘。

Datastream WebSocket 为您提供任意 Solana 代币的实时价格推送。连接一次即可接收即时价格更新——无需轮询。

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

## 连接

所有 Datastream 频道使用同一个 WebSocket 连接。发送 JSON 消息以加入和离开 room。

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

ws.onopen = () => {
  console.log("Connected");
};

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

***

## 按代币订阅价格

订阅 `price-by-token:{tokenAddress}` 以获取主池的价格更新。主池通常是流动性最高的池,意味着可交易资金最多。

```javascript theme={null}
const token = "9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump";

// Join
ws.send(JSON.stringify({ type: "join", room: `price-by-token:${token}` }));

// Receive
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === "joined") {
    console.log(`Subscribed to ${msg.room}`);
  }
  if (msg.type === "message") {
    const { price, price_quote, pool, time } = msg.data;
    console.log(`$${price} (${price_quote} SOL) at ${new Date(time).toISOString()}`);
  }
};

// Leave when done
ws.send(JSON.stringify({ type: "leave", room: `price-by-token:${token}` }));
```

**Payload:**

```json theme={null}
{
  "type": "message",
  "room": "price-by-token:9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump",
  "data": {
    "price": 0.008006,
    "price_quote": 0.00010064,
    "pool": "EWiYmq3nWQpoTkcU4UfGYEoYvDHduDsXhpPvqmoqpump",
    "token": "9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump",
    "time": 1723728065246
  }
}
```

***

## 聚合价格

订阅 `price:aggregated:{tokenAddress}` 以获得由多个池综合得出的单一价格。消息包含中位数、平均值、最低、最高和池数量。适用于在多个池中交易的高流动性代币。

```javascript theme={null}
const sol = "So11111111111111111111111111111111111111112";

ws.send(JSON.stringify({ type: "join", room: `price:aggregated:${sol}` }));

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === "message") {
    const { price, aggregated } = msg.data;
    console.log(`Price: $${price}`);
    console.log(`Median: $${aggregated.median} (${aggregated.poolCount} pools)`);
    console.log(`Range: $${aggregated.min} — $${aggregated.max}`);
  }
};
```

**Payload:**

```json theme={null}
{
  "price": 153.70,
  "aggregated": {
    "median": 153.68,
    "average": 153.67,
    "min": 153.36,
    "max": 153.71,
    "poolCount": 10
  },
  "topPools": [...]
}
```

***

## 按池订阅价格

订阅 `price:{poolId}` 以获取某个特定池的价格更新。当您关注特定的 DEX 或流动性来源时使用。

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

***

## 所有池价格

订阅 `price:{tokenAddress}`(不带 `aggregated`)以接收代币所有交易池的单独价格更新。

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

***

## 代币变化(完整更新)

订阅 `token:{tokenAddress}` 以获取综合的池更新——价格、流动性、市值、供应量和安全数据都在一条消息中。

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

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === "message") {
    const d = msg.data;
    console.log(`Price: $${d.price.usd}`);
    console.log(`Liquidity: $${d.liquidity.usd}`);
    console.log(`Market Cap: $${d.marketCap.usd}`);
    console.log(`LP Burn: ${d.lpBurn}%`);
  }
};
```

仅主池(在多池代币上噪音更少):

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

***

## 实时交易

订阅 `transaction:{tokenAddress}` 以即时查看每笔兑换。

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

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === "message") {
    const trades = Array.isArray(msg.data) ? msg.data : [msg.data];
    trades.forEach(t => {
      const side = t.type === "buy" ? "BUY " : "SELL";
      console.log(`${side} $${t.volume.toFixed(2)} by ${t.wallet}`);
    });
  }
};
```

按池过滤:

```javascript theme={null}
ws.send(JSON.stringify({
  type: "join",
  room: `transaction:${token}:${poolId}`
}));
```

***

## 构建实时图表

将价格流与 [OHLCV REST 端点](/cn/data-api/get-ohlcv-data-for-a-token)结合,构建实时图表。OHLCV 表示开盘、最高、最低、收盘和成交量。使用 REST 加载历史 K 线,然后用 WebSocket 行情更新最新 K 线。

```javascript theme={null}
const token = "9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump";
const headers = { "x-api-key": "YOUR_API_KEY" };

// 1. Load historical candles via REST
const now = Math.floor(Date.now() / 1000);
const candles = await fetch(
  `https://data.solanatracker.io/chart/${token}?type=1m&time_from=${now - 3600}&time_to=${now}`,
  { headers }
).then(r => r.json());

let currentCandle = candles[candles.length - 1];

// 2. Stream live price updates
const ws = new WebSocket("wss://datastream.solanatracker.io/YOUR_API_KEY");

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

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

  const { price, time } = msg.data;
  const candleStart = Math.floor(time / 60000) * 60;

  if (candleStart > currentCandle.time) {
    // New candle
    candles.push(currentCandle);
    currentCandle = { time: candleStart, open: price, high: price, low: price, close: price, volume: 0 };
  } else {
    // Update current candle
    currentCandle.close = price;
    currentCandle.high = Math.max(currentCandle.high, price);
    currentCandle.low = Math.min(currentCandle.low, price);
  }

  // Render candles + currentCandle to your chart library
};
```

### 开源图表示例

我们有两个开源图表实现可作为起点:

<CardGroup cols={2}>
  <Card title="Liveline 图表" href="https://github.com/solanatracker/solana-liveline-chart-example">
    使用 Datastream WebSocket 的极简实时折线图。是自定义 UI 的良好起点。
  </Card>

  <Card title="TradingView 高级图表" href="https://github.com/solanatracker/solana-tradingview-advanced-chart-example">
    完整的 TradingView 高级图表集成,Datastream 提供实时 K 线更新。
  </Card>
</CardGroup>

***

## 成交量与统计

### 代币成交量

订阅 `volume:token:{tokenAddress}` 获取聚合成交量更新:

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

### 代币统计

订阅 `stats:token:{tokenAddress}` 获取多时间范围统计(1m、5m、1h、6h、24h 买/卖笔数、成交量、独立交易者):

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

获取单一总览快照:

```javascript theme={null}
ws.send(JSON.stringify({ type: "join", room: `stats:token:${token}:total` }));
```

***

## Room 参考

| Room 模式                      | 您获得的内容           |
| ---------------------------- | ---------------- |
| `price-by-token:{token}`     | 主池的价格            |
| `price:aggregated:{token}`   | 跨池中位数/平均/最低/最高   |
| `price:{pool}`               | 一个池的价格           |
| `price:{token}`              | 所有池的价格           |
| `token:{token}`              | 完整池状态(价格、流动性、市值) |
| `token:{token}:primary`      | 仅主池状态            |
| `transaction:{token}`        | 代币上的所有兑换         |
| `transaction:{token}:{pool}` | 特定池中的兑换          |
| `volume:token:{token}`       | 聚合成交量            |
| `stats:token:{token}`        | 多时间范围统计          |

<CardGroup cols={2}>
  <Card title="价格与图表(REST)" href="/cn/guides/price-and-charts">
    用于历史 OHLCV、价格快照和 ATH 数据的 REST 端点。
  </Card>

  <Card title="代币发现流" href="/cn/guides/datastream-tokens">
    流式传输新代币、毕业中代币和市场事件。
  </Card>
</CardGroup>
