WebSocket 匯率 API

訂閱支援的貨幣對,透過持久連線接收匯率更新。請將 API 金鑰保存在伺服器上。

建立免費金鑰閱讀 API 參考

建立連線

連接 wss://api.exchangerate.dev/v1/stream,在 10 秒內傳送 auth,並在 authenticated 後傳送 subscribe。

連線範例

此伺服器端流程驗證金鑰,並訂閱 USD/EUR 及 USD/JPY。

Node.js 22+ · 伺服器端 WebSocket 用戶端
// Node.js 22+ · run on your server · set EXCHANGERATE_API_KEY in the environment
const key = process.env.EXCHANGERATE_API_KEY;
if (!key) throw new Error("EXCHANGERATE_API_KEY is required");

let retries = 0;
let stopped = false;
function connect() {
  const ws = new WebSocket("wss://api.exchangerate.dev/v1/stream");
  ws.addEventListener("open", () => {
    ws.send(JSON.stringify({ action: "auth", api_key: key }));
  });
  ws.addEventListener("message", ({ data }) => {
    const frame = JSON.parse(String(data));
    if (frame.type === "authenticated") {
      retries = 0;
      ws.send(JSON.stringify({ action: "subscribe", base: "USD", symbols: ["EUR", "JPY"] }));
    } else if (frame.type === "snapshot" || frame.type === "update") {
      if (frame.stale) return; // Keep the observation time; don't treat it as a fresh tick.
      console.log(frame.base, frame.symbol, frame.rate, frame.effective_at);
    } else if (frame.type === "state") {
      console.log(frame.base, frame.symbol, frame.state); // stale or unavailable
    } else if (frame.type === "error") {
      console.error(frame.code, frame.message);
      if (["invalid_api_key", "quota_exceeded", "connection_limit_exceeded", "subscription_limit_exceeded"].includes(frame.code)) {
        stopped = true;
        ws.close();
      }
    }
  });
  ws.addEventListener("close", () => {
    if (stopped) return;
    const delay = Math.min(30_000, 1_000 * 2 ** Math.min(retries++, 5));
    setTimeout(connect, delay + Math.random() * 250);
  });
}
connect();

WebSocket 連線需要驗證。

讀取每條訊息

訊息包含貨幣對、匯率、觀測時間及新鮮度狀態。請將 unavailable 和 stale 視為明確狀態。

JSON · 訊息範例;數值及時間僅供說明
{
  "type": "update",
  "base": "USD",
  "symbol": "JPY",
  "rate": "154.792",
  "effective_at": "2026-09-15T02:59:44Z",
  "source": "live",
  "source_type": "market",
  "market_session": "open",
  "derived": false,
  "stale": false
}

涵蓋範圍

只可訂閱目前涵蓋表列出的貨幣對。交叉盤要求兩條腿都有最新觀測。

AUD, CAD, CHF, EUR, GBP, JPY, MXN, NOK, NZD, PLN, SEK, SGD, USD, ZAR · 182 支援的貨幣對

更新是指示性觀測。請查看每條訊息的狀態及觀測時間。

查看目前涵蓋範圍

方案限制

連線數及每條連線的貨幣對數量取決於方案。每個獲准連線會消耗一個月度配額單位。

方案連線數每條連線的貨幣對商業使用
Free15
Basic325
Pro10100

每個獲准連線會消耗一個月度配額單位。

查看價格

商業使用

分發依賴此串流的產品前,請查看目前方案及商業使用條款。

安全重新連線

斷線後先等待再重新連線,重新驗證,等待 authenticated,然後重新訂閱。不要將金鑰放在 URL 或公開 JavaScript 中。

缺少的更新會保持缺少;串流不會編造數值。

可以匿名連線嗎?

不可以。WebSocket 連線需要 API 金鑰。可透過支援的 REST 端點進行匿名試用。

每個貨幣對都可以串流嗎?

不可以。WebSocket 涵蓋範圍按貨幣對區分。請查看涵蓋表,並明確處理不支援的訂閱。