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:
- GoldAPI.io WebSocket API overview
- WebSocket protocol documentation
- GoldAPI.io dashboard
- Plans and quotas
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.
| Plan | WebSocket access | Connections and channels | Monthly usage |
|---|---|---|---|
| Free | Included for evaluation | 1 concurrent connection, up to 10 channels | 150 shared REST, WebSockets-token, and MCP market-data requests |
| Pro | Not included | No WebSockets access | Unlimited REST only |
| Business | Included for production | Up to 5 concurrent connections, 20 channels per connection | Unlimited 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:
- Sign in to the GoldAPI.io dashboard and obtain the dedicated WebSocket API key.
- From a trusted backend, send the key to
POST /api/ws/tokenin thex-ws-api-keyheader. - Read the short-lived token and
websocketUrlfrom the response. - Connect to
wss://ws.goldapi.io/v1. - Send an
authmessage containing the short-lived token. - Wait for
authenticated, then subscribe to one or more concrete channels. - Process
price.updatemessages 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_KEYThe 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 wsStore 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.jsTurn 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 updatesThis 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:
- Confirm that
message.typeisprice.update. - Route by
message.channel, not only by the symbol insidedata. - Check
publishedAtordata.timestampbefore replacing a newer cached quote. - Store the newest market snapshot in a fast cache.
- Recalculate only products affected by that metal and currency.
- Push changed dealer quotes to dashboards or customer sessions.
- 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/v1Alternatively, 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_UNAVAILABLEaffects the identified channel. Keep the connection open and wait for valid data.TOKEN_EXPIREDis followed by close code4001. 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.
