How to Stream Live Gold Prices Using GoldAPI.io WebSockets Integration

Build a real-time gold price WebSocket feed for bullion dealer quotes, live dashboards, inventory valuation, and customer price updates with GoldAPI.io.

Stream live gold prices using GoldAPI.io WebSockets instead of API polling

A live gold-price dashboard, bullion dealer quote screen, or inventory valuation tool should update when the gold market moves. Repeated REST API polling can work for occasional lookups, but a persistent GoldAPI.io price WebSockets connection is a better fit when an application needs continuous quote price updates.

GoldAPI.io WebSockets push normalized JSON updates for gold, silver, platinum, palladium, and supported foreign-exchange (FX) pairs. Your application requests a short-lived WS connection token, opens one secure web socket connection, authenticates, and subscribes to concrete channels such as metals:XAUUSD.

This guide shows how to stream live gold prices with Node.js using the same connection flow and message payloads documented in the GoldAPI.io WebSocket protocol reference.

Useful links:

When should you use a GoldPI.io WebSockets vs API?

Use REST when you need a price at a specific moment, such as loading the latest gold price during a page request. Use WebSockets when the screen or workflow should stay synchronized without repeatedly asking for the same resource.

Common live precious-metals use cases include:

  • A gold or silver price dashboard that updates without a page refresh.
  • A bullion dealer workflow that recalculates customer buy and sell quotes as bid and ask prices change.
  • A dealer counter display showing spot price, spread, and intraday movement.
  • E-commerce quote price updates for coins, bars, scrap gold, and jewelry.
  • Inventory valuation for gold, silver, platinum, and palladium holdings.
  • Internal risk, treasury, and market-monitoring screens.
  • Price alerts and automation triggered by a threshold or spread.

For a bullion dealer, keep commercial rules in your own backend. A streamed spot price can feed your pricing engine, but premiums, discounts, assay costs, refining, tax, shipping, insurance, and quote-expiry policy remain business-specific.

GoldAPI.io WebSocket access by plan

GoldAPI.io provides different WebSocket allowances by plan.

PlanWebSocket accessConnections and channelsMonthly usage
FreeIncluded for evaluation1 concurrent connection, up to 10 channels150 shared REST, WebSockets-token, and MCP market-data requests
ProNot includedNo WebSockets accessUnlimited REST only
BusinessIncluded for productionUp to 5 concurrent connections, 20 channels per connectionUnlimited REST and production WebSockets access

For a Free account, each successful call that issues a WebSockets token consumes one request from the shared monthly allowance. Opening the WebSockets connection and receiving price.update messages do not consume another monthly request for every update.

The Free plan is useful for building and evaluating a live gold dashboard. Business is the appropriate plan when a production bullion dealer workflow needs more connections, more subscribed channels, and continuous operational use. Pro deliberately remains a REST-only plan.

How GoldAPI.io WebSocket authentication works

The GoldAPI.io WebSockets uses a dedicated WebSocket key, not the normal REST API key.

The secure connection flow is:

  1. Sign in to the GoldAPI.io dashboard and obtain the dedicated WebSocket API key.
  2. From a trusted backend, send the key to POST /api/ws/token in the x-ws-api-key header.
  3. Read the short-lived token and websocketUrl from the response.
  4. Connect to wss://ws.goldapi.io/v1.
  5. Send an auth message containing the short-lived token.
  6. Wait for authenticated, then subscribe to one or more concrete channels.
  7. Process price.update messages and maintain the application heartbeat.

Do not embed the dedicated WebSocket key in public browser JavaScript or a mobile application. A browser should receive only the short-lived session token from your backend.

Request a short-lived GoldAPI.io WebSocket token

The token request is an HTTPS request:

POST /api/ws/token HTTP/1.1
Host: www.goldapi.io
x-ws-api-key: YOUR_DEDICATED_WEBSOCKET_API_KEY

The response includes the temporary token, its expiry, the WebSocket URL, allowed channel capabilities, connection limits, and current token-request usage. Tokens currently last 15 minutes. When a token expires, request a new token and reconnect.

GoldAPI.io price WebSockets protocol

GoldAPI.io uses small JSON messages with a type field. Add a unique requestId to asynchronous client commands so your application can match acknowledgements and errors to the command that caused them.

1. Connection welcome

After opening the socket, the server announces the protocol version:

{
  "type": "welcome",
  "protocolVersion": 1
}

2. Authenticate the GoldAPI.io WebSocket connection

Send the short-lived token obtained from the HTTPS token endpoint:

{
  "type": "auth",
  "token": "GOLD_WS_SESSION_TOKEN",
  "requestId": "xauusd-auth"
}

A successful response describes the channel capabilities and limits granted to the account:

{
  "type": "authenticated",
  "requestId": "xauusd-auth",
  "allowedChannels": ["metals:*", "fx:*"],
  "maxConnections": 1,
  "maxChannelsPerConnection": 10,
  "expiresAt": "2026-10-22T12:15:00.000Z"
}

The wildcard values are capabilities. Subscribe to concrete channels rather than subscribing directly to metals:* or fx:*.

3. Subscribe to live XAU/USD prices

To stream live gold prices in US dollars, subscribe to metals:XAUUSD:

{
  "type": "subscribe",
  "channels": ["metals:XAUUSD"],
  "requestId": "xauusd-subscribe"
}

The server acknowledges the active subscription:

{
  "type": "subscribed",
  "requestId": "xauusd-subscribe",
  "channels": ["metals:XAUUSD"]
}

You can subscribe to multiple feeds in one command, subject to the plan limit:

{
  "type": "subscribe",
  "requestId": "dealer-markets",
  "channels": [
    "metals:XAUUSD",
    "metals:XAGUSD",
    "metals:XPTUSD",
    "metals:XAUAUD",
    "fx:USDEUR"
  ]
}

4. Process a live gold price update

The price.update payload uses REST-compatible field names. This makes it easier to reuse price formatting, spread calculations, and valuation code across GoldAPI.io REST and WebSockets integrations.

{
  "type": "price.update",
  "channel": "metals:XAUUSD",
  "publishedAt": 1792651200,
  "data": {
    "timestamp": 1792651200,
    "datetime": "2026-10-22T06:40:00.000Z",
    "metal": "XAU",
    "currency": "USD",
    "exchange": "FOREXCOM",
    "symbol": "FOREXCOM:XAUUSD",
    "open_time": 1792627200,
    "open_price": 4166.13,
    "prev_close_price": 4166.13,
    "low_price": 4163.755,
    "high_price": 4187.87,
    "price": 4175.12,
    "unit": "troy_ounce",
    "change": 8.99,
    "change_percent": 0.22,
    "ask": 4175.42,
    "bid": 4174.71,
    "spread": 0.71,
    "range": 24.115
  }
}

Use data.price for the current spot display, or apply bid and ask according to your workflow. A bullion dealer might derive indicative customer quotes from these values and then add premiums or discounts in a separate pricing service.

5. Maintain the heartbeat

Send an application-level ping approximately every 25 seconds:

{
  "type": "ping",
  "requestId": "xauusd-ping-1"
}

The corresponding pong contains a whole-second Unix timestamp:

{
  "type": "pong",
  "requestId": "xauusd-ping-1",
  "timestamp": 1792651200
}

Complete Node.js example for streaming live gold prices using GoldAPI.io WebSockets

This example follows the same Node.js connection pattern used in the GoldAPI.io API documentation. It requests a token, opens the WebSocket, authenticates, subscribes to gold and silver channels, maintains the heartbeat, handles errors, and reconnects after closure.

Install the WebSocket package:

npm install ws

Store the dedicated key in an environment variable:

export GOLDAPI_WS_API_KEY="YOUR_DEDICATED_WEBSOCKET_API_KEY"

Create stream-gold.js:

// Node.js 18+ · npm install ws
const WebSocket = require('ws');

const channels = ['metals:XAUUSD', 'metals:XAGUSD'];
let heartbeatTimer;

async function getWebSocketSession() {
  const response = await fetch('https://www.goldapi.io/api/ws/token', {
    method: 'POST',
    headers: {
      'x-ws-api-key': process.env.GOLDAPI_WS_API_KEY
    }
  });
  const session = await response.json();

  if (!response.ok) {
    throw new Error(session.error || 'Unable to issue WebSocket token');
  }
  return session;
}

function startHeartbeat(socket) {
  const ping = () => {
    if (socket.readyState !== WebSocket.OPEN) return;
    socket.send(JSON.stringify({
      type: 'ping',
      requestId: 'prices-ping-' + Date.now()
    }));
  };
  ping();
  heartbeatTimer = setInterval(ping, 25000);
}

async function connect() {
  const session = await getWebSocketSession();
  const socket = new WebSocket(session.websocketUrl);

  socket.on('open', () => {
    socket.send(JSON.stringify({
      type: 'auth',
      token: session.token,
      requestId: 'prices-auth'
    }));
  });

  socket.on('message', rawMessage => {
    let message;
    try {
      message = JSON.parse(rawMessage.toString());
    } catch (error) {
      console.error('Invalid WebSocket message:', error);
      return;
    }

    if (message.type === 'error') {
      console.error('GoldAPI WebSocket error:', message.code, message.message);
      return;
    }

    if (message.type === 'authenticated') {
      socket.send(JSON.stringify({
        type: 'subscribe',
        channels,
        requestId: 'prices-subscribe'
      }));
      startHeartbeat(socket);
    }

    if (message.type === 'price.update') {
      const { metal, currency, price, bid, ask, change_percent } = message.data;
      console.log({ metal, currency, price, bid, ask, change_percent });
    }

    if (message.type === 'pong') {
      console.log('Heartbeat confirmed:', message.requestId);
    }
  });

  socket.on('close', (code, reason) => {
    clearInterval(heartbeatTimer);
    console.log('WebSocket closed:', code, reason.toString());
    setTimeout(() => connect().catch(console.error), 1000);
  });

  socket.on('error', error => {
    console.error('WebSocket connection error:', error);
  });
}

connect().catch(console.error);

Run it with:

node stream-gold.js

Turn price updates into a bullion dealer workflow

A production dealer workflow normally separates market data from commercial pricing:

GoldAPI.io price.update
        ↓
Validate timestamp and channel
        ↓
Update latest market-price cache
        ↓
Apply product premium or purchase discount
        ↓
Round using dealer pricing rules
        ↓
Publish dashboard and customer quote updates

This separation gives the business one trusted market-price stream while allowing different rules for bars, coins, jewelry, scrap metal, wholesale customers, and retail customers.

For each update:

  1. Confirm that message.type is price.update.
  2. Route by message.channel, not only by the symbol inside data.
  3. Check publishedAt or data.timestamp before replacing a newer cached quote.
  4. Store the newest market snapshot in a fast cache.
  5. Recalculate only products affected by that metal and currency.
  6. Push changed dealer quotes to dashboards or customer sessions.
  7. Display the market timestamp and an appropriate quote-expiry time.

Avoid persisting every tick unless your reporting requirements genuinely need tick history. For many dashboards, keeping the current snapshot and periodic aggregates is more practical.

Browser dashboard architecture for GoldAPI.io WebSockets

Do not expose GOLDAPI_WS_API_KEY in browser source. A safer dashboard design is:

Browser dashboard
      ↓ requests temporary session
Your authenticated backend
      ↓ x-ws-api-key
POST https://www.goldapi.io/api/ws/token
      ↓ short-lived token only
Browser connects to wss://ws.goldapi.io/v1

Alternatively, maintain one server-side GoldAPI.io connection and relay only the normalized prices your own authenticated users need. That architecture centralizes reconnect logic, dealer calculations, auditing, and access control.

Error handling and reconnection

GoldAPI.io webSockets protocol errors have a stable code and a human-readable message:

{
  "type": "error",
  "channel": "metals:XAUUSD",
  "code": "PRICE_UNAVAILABLE",
  "message": "No valid cached quote available."
}

Handle errors according to their scope:

  • PRICE_UNAVAILABLE affects the identified channel. Keep the connection open and wait for valid data.
  • TOKEN_EXPIRED is followed by close code 4001. Request a fresh token and establish a new connection.
  • A transport close should clear heartbeat timers before reconnecting.
  • Use bounded exponential backoff for repeated connection failures rather than reconnecting in a tight loop.
  • After reconnecting, authenticate again and restore the required subscriptions.
  • Never log the dedicated WebSocket API key or the short-lived token.

Start streaming precious-metals prices using GoldAPI.io WebSockets

Create or sign in to a GoldAPI.io account, obtain the dedicated WebSocket key, and test metals:XAUUSD with the Node.js example above. Use the WebSocket protocol documentation as the source of truth for message types, channel naming, authentication, errors, and limits.

Frequently Asked Questions

Answers to common questions about this GoldAPI.io integration.

Can I stream live gold prices with the GoldAPI.io Free plan?

Yes. The Free plan supports WebSocket evaluation with one connection and up to 10 channels. Each successful WebSocket token issuance uses one request from the shared 150-request monthly allowance; streamed price messages do not consume additional monthly requests.

Which GoldAPI.io plan is best for a bullion dealer WebSocket workflow?

Business is designed for production WebSocket workflows and includes up to five concurrent connections with 20 channels per connection. Free is suitable for evaluation, while Pro does not include WebSocket access.

Does every live gold price update count as an API request?

No. On Free accounts, issuing a WebSocket connection token consumes one shared monthly request. Opening the connection and receiving price.update messages do not increment the monthly request count.

Is the GoldAPI WebSocket API key the same as the REST API key?

No. GoldAPI.io provides a dedicated WebSocket API key in the dashboard. Exchange it from a trusted backend for a short-lived token, then use that token to authenticate the WebSocket connection.

Integration Guides To

Build With GoldAPI.io Today

Practical guides for WordPress, Shopify, Excel, Joomla, and Drupal.

WordPress integration icon
WordPress

How to Get Real-Time Gold and Silver Prices in WordPress

Step-by-step guide on integrating GoldAPI.io Price Call in WordPress site

Read article →
Shopify integration icon
Shopify

How to Get Real-Time Gold and Silver Prices in Shopify

Step-by-step guide on integrating GoldAPI.io Price Call in Shopify store

Read article →
Excel integration icon
Excel

How to Get Real-Time Gold and Silver Prices in Excel

Step-by-step guide on integrating GoldAPI.io Price Call in Excel spreadsheet

Read article →
WebSockets integration icon
WebSockets

How to Stream Live Gold Prices Using GoldAPI.io WebSockets Integration

Build a real-time gold price WebSocket feed for bullion dealer quotes, live dashboards, inventory valuation, and customer price updates with GoldAPI.io.

Read article →
FX WebSockets integration icon
FX WebSockets

How to Get Real-Time Currency FX Rates Using GoldAPI.io WebSockets

Stream live foreign-exchange rates, bid and ask prices, and currency-pair updates into FX dashboards, conversion tools, checkout pricing, and treasury workflows.

Read article →
MCP Server integration icon
MCP Server

How to Connect ChatGPT, Claude and Codex to the GoldAPI MCP Server

Connect AI agents to the hosted GoldAPI MCP Server for live and historical metal (gold, silver) prices, currency conversion, valuations, portfolio analysis and LBMA benchmarks.

Read article →