How to Get Gold Spot (XAU) Prices via API
You need to pull live gold spot (XAU) prices into your app, chart the USD per ounce value, and backfill a short history so you can alert when XAU moves. By the end of this guide you’ll fetch the latest XAU and USDXAU quotes via Indices-API, parse them in code, understand how the base currency and units work, and be ready to extend into historical and fluctuation queries for production use.
What you will build
This walkthrough focuses on the concrete tasks developers ship first:
- Fetch the latest gold spot price (XAU) and its USD inverse (USDXAU) with one API call.
- Normalize price semantics (XAU per USD vs USD per XAU) so your UI and alerts use the correct value.
- Handle trading-day gaps, caching, and the fact that same-day historical “end_date” queries aren’t valid.
- Prepare your pipeline to extend into time-series and daily fluctuation data using the same symbol.
Symbols and price units for gold spot
Indices-API quotes are by default relative to USD. That matters for gold because you’ll typically need USD per ounce (USDXAU) for charts, but the API also returns the inverse rate (XAU) as “XAU per USD.”
- XAU: ounces of gold per 1 USD (XAU per USD; a small decimal).
- USDXAU: USD per 1 ounce of gold (USD per XAU; the chartable “price in dollars”).
- USD: the base currency marker (always 1 when base=USD).
Confirm symbol availability and exact codes on the Indices-API Supported Symbols page before deploying. If you also track gold-related equity indices (for example, the PHLX Gold/Silver Index, often abbreviated “XAU”), verify their symbol codes separately to avoid mixing instruments.
Get the latest gold spot quote (copy-paste)
Use the latest endpoint to pull live XAU rates. Replace YOUR_API_KEY with your key. If you don’t have one yet, you can Register for a 7‑day trial; the PRO plan is $49.99/month.
curl -s "https://indices-api.com/api/latest?access_key=YOUR_API_KEY"
Here is a real response sample you can rely on for field names and structure:
{"data":{"success":true,"timestamp":1793580060,"date":"2026-11-02","base":"USD","rates":{"XAU":0.000256429653,"USD":1,"USDXAU":3899.7050001857624}}}
What these fields mean (and what you’ll actually use)
- data.success: boolean status flag you should check before parsing.
- data.timestamp: Unix epoch (seconds). Convert to your app’s timezone for display. Use this for cache invalidation.
- data.date: ISO date (YYYY-MM-DD) associated with the rates. For latest, this is the service date; for historical endpoints, it is the requested date.
- data.base: default quote currency, here “USD.” That means “rates” values are quoted with USD as the base.
- data.rates.XAU: XAU per USD (amount of gold you get for 1 USD).
- data.rates.USD: always 1 when base is USD.
- data.rates.USDXAU: USD per XAU (price of 1 ounce of gold in USD). This is the number you chart.
Parse the latest XAU price in Python
The code below fetches the latest, validates success, extracts the USD per ounce price (USDXAU), and falls back to inverting XAU per USD if needed.
import os
import time
import json
import urllib.request
API_KEY = os.getenv("INDICES_API_KEY", "YOUR_API_KEY")
URL = f"https://indices-api.com/api/latest?access_key={API_KEY}"
def fetch_latest_xau():
with urllib.request.urlopen(URL, timeout=10) as resp:
payload = json.loads(resp.read().decode("utf-8"))
# Basic integrity checks
data = payload.get("data", {})
if not data.get("success"):
raise RuntimeError(f"API reported failure: {payload}")
rates = data.get("rates", {})
base = data.get("base")
ts = data.get("timestamp")
date = data.get("date")
# Prefer USD per XAU if present
usd_per_xau = rates.get("USDXAU")
if usd_per_xau is None:
# Fallback: invert XAU per USD
xau_per_usd = rates.get("XAU")
if xau_per_usd in (None, 0):
raise ValueError("Neither USDXAU nor invertible XAU rate found in response.")
usd_per_xau = 1.0 / xau_per_usd
return {
"timestamp": ts,
"date": date,
"base": base,
"usd_per_xau": float(usd_per_xau),
"xau_per_usd": float(rates.get("XAU")) if rates.get("XAU") is not None else None
}
if __name__ == "__main__":
quote = fetch_latest_xau()
print(f"[{quote['date']}] USD/XAU={quote['usd_per_xau']:.4f} (ts={quote['timestamp']})")
Tip: cache the latest response until a newer timestamp appears. Depending on your plan, updates arrive every 60 minutes or every 10 minutes. Over-polling wastes requests and doesn’t improve freshness.
Time-series and fluctuation for gold
Once your latest-price integration is stable, extend it with two read-heavy endpoints that are designed for trend lines and risk checks:
- Time-series: query daily historical rates between two dates to power a chart or moving-average scan.
- Fluctuation: request the aggregate change between two dates (start and end) to quantify a move without downloading all intermediate days.
For exact parameters, response shapes, and date rules, see the Documentation. The important production constraints to plan for:
- Base currency: responses are relative to USD. Use USDXAU when you need “dollars per ounce.”
- end_date cannot be today: set end_date to the most recent completed service day to avoid empty results.
- Non-trading days: weekend/holiday gaps can appear. Handle missing calendar days gracefully in your charts and indicators.
- Update frequency: latest updates at a fixed cadence based on your plan; if time-series spans recent dates, do not assume today’s bar is closed.
If your use case requires candle-level analysis, explore OHLC and intraday endpoints in the Documentation. They let you work with daily OHLC or intraday intervals for more granular signals while remaining consistent with the same symbols and base currency.
Production notes that save you time
- Quote direction: Decide once whether your UI and alerts use USDXAU (USD per ounce) or XAU per USD and stick to it. For human-facing views, USDXAU is clearer.
- Rounding and formatting: Keep full precision in storage but format to 2–3 decimals for USDXAU when rendering. Avoid double-inverting values in different layers.
- Caching: Use the timestamp field to detect freshness. Set a client cache TTL aligned with your plan’s update cadence (e.g., 10–60 minutes) and only refresh after a new timestamp appears.
- Gaps and weekends: Gold trading spans global venues and may show fewer gaps than equities, but your time-series requests will still skip non-service days. Do not synthesize bars for missing dates unless your analytics require it.
- “Today” is not closed: For both latest and daily endpoints, treat the current service day as incomplete until the next cycle. This prevents alert churn.
- Error handling: Check data.success and handle missing keys defensively. Fall back to inverting XAU when USDXAU is absent.
- Reconciliation: If you compute USD per ounce from XAU by inversion, compare to USDXAU when present to validate your pipeline periodically.
Avoid mixing XAU spot with the PHLX Gold/Silver Index
Developers sometimes conflate gold spot (XAU, a commodity price) with the PHLX Gold/Silver equity index (also colloquially “XAU”). They are distinct instruments with different behaviors and use cases. Before you pin dashboards or alerts to “XAU,” confirm the exact symbol you need on the Indices-API Supported Symbols page and keep commodity vs. equity index data on separate tracks. If you plan to overlay miner performance with spot gold, store them as separate series with explicit units.
Security, environments, and change control
- API keys: store in environment variables or a vault. Do not hard-code in client apps.
- Staging vs. production: gate integration changes behind feature flags. If you switch from XAU inversion to USDXAU direct pricing, migrate atomically to avoid double inversions.
- Monitoring: log data.timestamp and USDXAU values on fetch. Alert on stale timestamps that exceed your plan’s update cadence.
- Metadata: persist base and date with each record so you can reconcile if your account’s base currency ever changes or if you ingest multi-base datasets in the future.
Where to go next
- Consult the endpoint details, error formats, and pagination rules in the Documentation.
- Check symbol codes and instrument coverage on the Indices-API Supported Symbols page.
- If your stack relies on model-context augmentations or tool routing, explore MCP for integrating market data into agents and workflows.
FAQ
Which symbol should I use for gold spot?
Use XAU and/or USDXAU. XAU is ounces per USD, USDXAU is USD per ounce. Confirm availability on the Symbols page before you ship.
Why does the API return both XAU and USDXAU?
The service is USD-based. XAU expresses the amount of gold per USD, while USDXAU provides the conventional “price per ounce.” Use USDXAU for charts and user-visible prices, and XAU for inversions or cross calculations if needed.
My time-series end_date returns no data for today. Why?
end_date cannot be today. Query up to the most recent completed service day and treat the current day as incomplete.
How often do latest prices update?
Based on your plan; common cadences are every 60 minutes or every 10 minutes. Cache until a newer timestamp appears to avoid redundant calls.
What happens on weekends or holidays?
Some dates will have no new bars. Your time-series should handle missing calendar days; do not assume continuous daily records.
Get your key and start shipping
Spin up your first XAU fetch in minutes. Create an account for a 7‑day trial (PRO $49.99/month) and get an access_key here: Register. Then use the Documentation to extend your integration to time-series, fluctuation, and OHLC as your product roadmap grows.