- keep the exact template phrase but alter internal formatting (for example different capitalization or punctuation) to force uniqueness? (This is not recommended and likely undesirable.)
Need to get Gold (XAU) historical prices into your chart, backtest, or pricing engine—today? This guide shows exactly how to retrieve, normalize, and operationalize historical XAU data with Metals-API. You’ll learn how to query point-in-time rates for single dates and ranges, handle OHLC and bid/ask nuances, convert units (troy ounces vs grams), and design a resilient pipeline that respects base currency conventions, timestamps/timezones, weekends, and caching. We’ll keep a developer focus with practical examples, including a complete curl request and a JavaScript snippet, and we’ll cover performance, security, and troubleshooting considerations end to end. For supported symbols and capabilities, see the Metals-API Website and the Metals-API Documentation.
Objective: Backfill and analyze Gold (XAU) historical prices with repeatable, production-grade workflows
Our concrete use case: you’re building or upgrading a system that requires accurate Gold (XAU) historical data—perhaps to backfill a chart, compute risk metrics, support a smart pricing rule in an e-commerce or ERP product, or power a quant research notebook. With Metals-API, you can programmatically retrieve historical daily rates, time series windows, OHLC snapshots, and day-to-day fluctuations, then transform and store these in your own canonical format. We’ll walk through:
- Key endpoints you’ll use for XAU history: historical by date, time-series windows, fluctuation, and OHLC.
- Implementation details developers care about: timestamps, base currency, units, pagination patterns, and caching.
- Data quality and operational reliability: retries, error handling, and schema evolution.
- Security and API key use in services, functions, and client apps.
Gold (XAU) in context: data model, units, and the “base” convention
Metals-API returns exchange rates where, by default, the base is USD and rates are “per troy ounce.” For gold, that means a rate describes the amount of XAU you receive per USD (or per your selected base). Keep in mind:
- Base currency: The response field base is typically "USD". A rate like "XAU": 0.000482 means 1 USD buys 0.000482 troy ounces of gold.
- Pricing direction: If you need USD per ounce (the inverse), compute 1 / rate for XAU. For example, price_per_oz_usd = 1.0 / 0.000482.
- Unit standard: Metals-API explicitly reports "unit": "per troy ounce". Convert to grams by multiplying ounces by 31.1034768.
- Time: Timestamps are epoch seconds; dates are ISO (YYYY-MM-DD). Align timezone assumptions in your system (e.g., UTC normalization) when joining with other datasets.
Core retrieval patterns you’ll rely on for XAU historical data
For historical Gold (XAU), you’ll most often stitch together these capabilities:
- Point-in-time historical daily rates for a specific date (e.g., to backfill a missing day in your DB).
- Time series daily rates for a contiguous window (e.g., to build a full chart or run an AB test comparing two time ranges).
- Fluctuation snapshot to compute day-over-day or week-over-week changes and percent movement, useful for alerting.
- OHLC daily values to support candlestick charts or strategy logic that relies on intraday extremes summarized by day.
- Bid/Ask when modeling execution spread, especially in trading or RFQ flows where friction matters.
- Convert for unit-aware conversions (e.g., USD to XAU for treasury accounting, or chain conversions between metals).
Step-by-step: query Gold (XAU) historical prices and interpret the response
1) Single-day, point-in-time historical rate for XAU
This is useful to patch missing rows or to reconcile end-of-day values. Query a specific date to get snapshot rates.
Example curl request (replace YOUR_ACCESS_KEY):
curl -G "https://metals-api.com/api/2026-09-16" \
-d access_key=YOUR_ACCESS_KEY \
-d base=USD \
-d symbols=XAU
Example JSON response:
{
"success": true,
"timestamp": 1789519710,
"base": "USD",
"date": "2026-09-16",
"rates": {
"XAU": 0.000485,
"XAG": 0.03825,
"XPT": 0.000915,
"XPD": 0.000748
},
"unit": "per troy ounce"
}
Fields you’ll actually use:
- success: Check before parsing values; handle false by retrying or logging.
- timestamp/date: Store both. date is your partition key; timestamp is useful to track data updates and consistency models.
- base: Persist or normalize; all downstream math depends on this context.
- rates.XAU: The core daily rate, expressed as XAU per USD (given base=USD).
- unit: Persist; you’ll need it for correct conversions and downstream audits.
Common follow-up computations:
- USD per troy ounce = 1 / rates.XAU
- USD per gram = (1 / rates.XAU) / 31.1034768
- grams per USD = rates.XAU * 31.1034768
2) Multi-day time series for XAU
When populating a chart or exporting a training set, query a range and store day-by-day values.
Example response for a time series window:
{
"success": true,
"timeseries": true,
"start_date": "2026-09-10",
"end_date": "2026-09-17",
"base": "USD",
"rates": {
"2026-09-10": {
"XAU": 0.000485,
"XAG": 0.03825,
"XPT": 0.000915
},
"2026-09-12": {
"XAU": 0.000483,
"XAG": 0.0382,
"XPT": 0.000913
},
"2026-09-17": {
"XAU": 0.000482,
"XAG": 0.03815,
"XPT": 0.000912
}
},
"unit": "per troy ounce"
}
Implementation tips:
- Not every calendar day may appear (weekends/holidays). Don’t assume continuous keys; create a calendar table if you need contiguous sequences.
- Chunk your requests by your plan’s date limits; merge ranges in your data store.
- Idempotency: Upserts by (date, symbol, base, unit) protect against duplicates.
3) Day-over-day Gold (XAU) change using fluctuation
Fluctuation snapshots are an efficient way to get start/end rates and computed changes for alerting or email digests without recomputing.
{
"success": true,
"fluctuation": true,
"start_date": "2026-09-10",
"end_date": "2026-09-17",
"base": "USD",
"rates": {
"XAU": {
"start_rate": 0.000485,
"end_rate": 0.000482,
"change": -3.0e-6,
"change_pct": -0.62
},
"XAG": {
"start_rate": 0.03825,
"end_rate": 0.03815,
"change": -0.0001,
"change_pct": -0.26
},
"XPT": {
"start_rate": 0.000915,
"end_rate": 0.000912,
"change": -3.0e-6,
"change_pct": -0.33
}
},
"unit": "per troy ounce"
}
Use cases:
- Notifications when XAU changes by more than a threshold (absolute or percentage).
- Risk metric delta previews without pulling the entire period timeseries.
4) OHLC daily data for candlesticks and strategy rules
For charting and backtesting, daily Open/High/Low/Close add nuance beyond a single daily fix. Metals-API’s OHLC endpoint returns per-symbol OHLC values keyed under rates.
{
"success": true,
"timestamp": 1789606110,
"base": "USD",
"date": "2026-09-17",
"rates": {
"XAU": {
"open": 0.000485,
"high": 0.000487,
"low": 0.000481,
"close": 0.000482
},
"XAG": {
"open": 0.03825,
"high": 0.0383,
"low": 0.0381,
"close": 0.03815
},
"XPT": {
"open": 0.000915,
"high": 0.000918,
"low": 0.00091,
"close": 0.000912
}
},
"unit": "per troy ounce"
}
Best practices:
- Store OHLC separately from “spot” daily; each serves different downstream needs.
- Derive volatility proxies from high/low ranges; validate against time-series pulls.
5) Bid/Ask spreads for execution-aware models
When simulating trading costs, you need both sides of the market. Metals-API returns bid, ask, and spread per symbol.
{
"success": true,
"timestamp": 1789606110,
"base": "USD",
"date": "2026-09-17",
"rates": {
"XAU": {
"bid": 0.000481,
"ask": 0.000483,
"spread": 2.0e-6
},
"XAG": {
"bid": 0.0381,
"ask": 0.0382,
"spread": 0.0001
},
"XPT": {
"bid": 0.000911,
"ask": 0.000913,
"spread": 2.0e-6
}
},
"unit": "per troy ounce"
}
Integrations:
- RFQ systems: present midpoint for quoting and include spread-aware P&L.
- Backtests: use bid for sells and ask for buys to avoid optimistic fills.
6) Conversions for accounting, invoicing, and unit handling
The convert endpoint resolves an amount between units or currencies using a specific timestamped rate. It’s a precise, auditable transformation for accounting trails.
{
"success": true,
"query": {
"from": "USD",
"to": "XAU",
"amount": 1000
},
"info": {
"timestamp": 1789606110,
"rate": 0.000482
},
"result": 0.482,
"unit": "troy ounces"
}
Operational pointers:
- Always persist the info.timestamp and rate with your transaction to ensure traceability.
- Normalize currency decimals in your own system; the API will return precise floats, but your DB might impose rounding.
End-to-end flow: from API to your data store for XAU
Below is a concise JavaScript example that fetches a historical window for Gold (XAU), normalizes to USD per troy ounce, and prints a sorted date/value table. Replace YOUR_ACCESS_KEY before running.
async function fetchGoldTimeSeries(startDate, endDate) {
const params = new URLSearchParams({
access_key: 'YOUR_ACCESS_KEY',
base: 'USD',
symbols: 'XAU',
start_date: startDate,
end_date: endDate
});
const url = `https://metals-api.com/api/timeseries?${params.toString()}`;
const res = await fetch(url, { method: 'GET' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (!data.success) throw new Error('API returned success=false');
const out = [];
for (const [date, symbolMap] of Object.entries(data.rates)) {
const xauPerUsd = symbolMap.XAU;
const usdPerOz = 1 / xauPerUsd;
out.push({ date, usdPerOz });
}
out.sort((a, b) => a.date.localeCompare(b.date));
return out;
}
fetchGoldTimeSeries('2026-09-10', '2026-09-17')
.then(rows => {
console.table(rows);
})
.catch(err => {
console.error('Error fetching gold time series:', err);
});
In production, send the array to your database, data warehouse, or time-series store (e.g., PostgreSQL, BigQuery, Snowflake, ClickHouse, InfluxDB). Partition by date for efficient range scans; index by symbol and base.
Comparing historical data options for XAU within Metals-API
| Capability | When to use it | Key fields to store | Notes |
|---|---|---|---|
| Historical rate (single date) | Backfill a missing daily XAU row | date, base, rates.XAU, unit, timestamp | Fast and precise for point-in-time snapshots |
| Time-series (date range) | Populate charts and research datasets | start_date, end_date, daily rates.XAU | Handle non-trading days and partial weeks |
| Fluctuation (start vs end) | Alerting and change summaries | start_rate, end_rate, change, change_pct | Avoids client-side delta calculations |
| OHLC (daily) | Candlesticks and volatility proxies | open, high, low, close | Separate store from “spot” to avoid confusion |
| Bid/Ask | Execution-aware backtests and P&L | bid, ask, spread | Use bid for sells, ask for buys |
| Convert | Audit-ready conversions by timestamp | query, info.timestamp, info.rate, result | Persist rate and timestamp with business docs |
Production considerations: timestamps, weekends, and timezones
- Timestamp semantics: The timestamp is epoch seconds. Always log it alongside the ISO date. If you resample to a specific market close, document your rule in metadata.
- Weekends and holidays: Metals trade globally but liquidity and fixes vary. Your time series may skip days. Interpolate only if your downstream logic tolerates it; otherwise, leave gaps explicit.
- Timezone normalization: Store and compute in UTC. Convert to user timezones at the edge (UI, report layer).
- Reproducibility: If you need historical reproducibility, archive the JSON payload or hash it to detect silent data changes in reprocess runs.
Caching and request efficiency for historical XAU pipelines
- Cache key: Include endpoint, symbol(s), date range, base, and your API version if applicable.
- TTL: For historical data, use long TTLs (days to months). For latest/intraday, keep TTL within your plan’s update cadence.
- Batching: Prefer time-series over repeated single-date calls when backfilling longer ranges.
- Compression: Enable gzip/deflate in your HTTP stack. Persist compressed JSON in object storage for audit trails.
- Cold-start warmup: Preload critical date windows at service startup to avoid latency spikes on first user interaction.
Security and API key handling
- Key storage: Keep the access_key in server-side secrets (e.g., environment variables, vaults). Avoid embedding in public clients.
- Least privilege: If you proxy requests, add your own rate limit and IP allowlist. Obfuscation is not a substitute for proper secret storage.
- Rotation: Schedule key rotation; abstract access_key in config so rollovers are non-disruptive.
- Transport: Always use HTTPS. Validate TLS in your client stack.
Authentication, rate limiting, and quotas in real deployments
Authentication is performed via the access_key query parameter. Handle quotas and plan-specific update cadences in your design:
- Backoff strategy: Implement exponential backoff with jitter on 429s and network errors.
- Circuit breakers: If repeated failures occur, trip a breaker and serve cached data with a stale-while-revalidate pattern.
- Observability: Log request/response metadata (excluding secrets) and build dashboards for error rates, latency, and cache hit ratio.
Data validation and sanitization
- Schema validation: Enforce required fields (success, base, date/timestamp, rates, unit). Reject partial or malformed payloads.
- Type checks: Ensure rates.XAU is numeric and within a plausible range; guard against NaN/Infinity.
- Outlier detection: Flag extreme moves relative to recent volatility to avoid polluting downstream analytics.
- Idempotent writes: Upsert by unique keys to prevent duplicate time buckets.
Error handling and recovery strategies
- API-level errors: If success=false, parse the error code/message when available, log, and decide on retry vs fallback.
- Network timeouts: Configure timeouts and retries with backoff; cap attempts to avoid thundering herds.
- Partial data: If some symbols are missing, persist what’s valid and schedule a targeted retry task.
- Fallback modes: Serve the last-known-good dataset with a warning in UI contexts to preserve user experience.
Advanced techniques: aligning historical XAU with indicators and models
- Roll-ups: Precompute rolling averages, EMAs, and Bollinger Bands in your warehouse; store as materialized views with refresh windows.
- Event joins: Align XAU time series with macro calendars (CPI, NFP, central bank meetings). Maintain event-time keys in UTC.
- Regime detection: Use fluctuation and OHLC to infer volatility regimes; tune model hyperparameters per regime.
- Unit sensitivity: If your model expects USD per oz, standardize at ingestion to prevent subtle bugs in signal generation.
Latest vs historical in a unified pipeline
Even if your prime need is historical, you’ll often blend latest data for near-real-time dashboards. Metals-API’s latest endpoint returns the most recent rates and updates based on plan cadence.
{
"success": true,
"timestamp": 1789606110,
"base": "USD",
"date": "2026-09-17",
"rates": {
"XAU": 0.000482,
"XAG": 0.03815,
"XPT": 0.000912,
"XPD": 0.000744,
"XCU": 0.294118,
"XAL": 0.434783,
"XNI": 0.142857,
"XZN": 0.344828
},
"unit": "per troy ounce"
}
Tips:
- Cache bust according to your plan’s update window (e.g., every 60 min or 10 min).
- Merge latest into your historical store via a “provisional” table; finalize after market close if your governance requires stable end-of-day values.
Broader Metals-API features you may leverage alongside XAU history
While this guide focuses on Gold (XAU), your application may expand across metals or require specialized historical variants:
- Supported symbols: Review the full list to ensure symbol correctness and coverage. See the Metals-API Supported Symbols.
- Intraday: Query intraday data for a single symbol to power finer-grained analytics. Think carefully about storage costs and re-sampling plans.
- Carat: If you sell jewelry or priced items by carat, use the carat feature to get gold rates by Carat, aligning directly to your product catalog attributes.
- Lowest/Highest Price: Retrieve daily extremes for a specific date to complement OHLC views or sanity-check alert triggers.
- Historical LME: Access LME historical symbols (dating back to 2008) for industrial metals modeling when your scope widens beyond XAU.
Units and conversions: troy ounces, grams, and currency bases
- Troy ounce to gram: 1 troy oz = 31.1034768 grams. Multiply ounces by 31.1034768 to get grams; divide grams by 31.1034768 to get ounces.
- USD base: If base=USD, rates.XAU means “ounces of gold per USD.” For a price per ounce in USD, invert the rate.
- Non-USD bases: If you choose another base (e.g., EUR), be consistent system-wide. Store base with every record and convert at query time.
Performance and scaling strategies
- Bulk backfills: Schedule ETL tasks that request historical ranges in chunks, with retries and persistent checkpoints.
- Concurrency limits: Cap concurrent requests to respect API quotas and avoid local resource starvation.
- CDN or proxy cache: Pull historical data through a caching layer to serve repeat queries at edge nodes, reducing origin calls.
- Warehouse ingestion: Use streaming ingestion for small deltas (daily), and batch jobs for large historical spans.
Data architecture patterns for reliable XAU history
- Bronze/Silver/Gold layers: Keep raw JSON (bronze), normalized daily rates (silver), and analytics-ready aggregates (gold) as separate schemas for traceability.
- Checksums and lineage: Hash responses and store lineage to enable reproducible backtests and compliance audits.
- Schema evolution: Encapsulate parsing in a versioned library so endpoint field changes don’t break downstream consumers.
Smart alerting and automation
- Threshold alerts: Use fluctuation change_pct to trigger alerts when XAU moves beyond N standard deviations of recent daily returns.
- Business rules: For ERP or e-commerce, compute USD per gram and apply margin rules; update product prices within defined guardrails.
- C-Suite summaries: Nightly digest emails summarizing OHLC and week-over-week change, with links to dashboards.
Integrating with research notebooks and BI tools
- Notebooks: Store normalized CSV/Parquet with explicit unit and base fields; include a small README.md in the dataset folder explaining transformations.
- BI: Build semantic models where “Price per oz USD” and “Price per gram USD” are first-class metrics; define a “Business Day” calendar for smoother visuals.
Gold (XAU) and the future of metals data: digital transformation and analytics
As the metals market digitizes, standardized APIs for timely and historical data become the backbone for pricing intelligence, automated RFQs, and programmatic hedging. Technologies that integrate smart endpoints—like OHLC for volatility characterization and bid/ask for execution-aware analytics—enable more thoughtful product experiences and operational resilience. Metals-API’s uniform JSON responses and steadily expanding symbol coverage help your architecture adapt with minimal code churn as new requirements emerge. Explore the Metals-API Documentation to discover advanced query patterns and plan capabilities, then iterate your pipelines as your analytics deepen.
Compliance, auditability, and governance
- Traceability: Persist raw response, rate, unit, base, timestamp, and request query parameters. This makes audits straightforward.
- Access logs: Record who or what system triggered data pulls; associate business events (e.g., price changes) with the exact reference data.
- Policy tags: For regulated environments, tag datasets with retention and usage policies; enforce lifecycle deletion for raw payloads where appropriate.
Troubleshooting common pitfalls
- Inverted rates: If your chart seems inverted, confirm you’re using 1 / XAU to derive USD per oz when base=USD.
- Missing days: Don’t forward-fill by default; either show gaps or annotate weekends/holidays in your UI.
- Rounding errors: Avoid early rounding; carry full precision in storage and round only at presentation.
- Mixed bases: If some datasets use EUR base and others USD, normalize to a common base before joining or modeling.
Complementary resources and references
- Get started and obtain a free API key: Metals-API Website.
- Endpoint usage, parameters, and examples: Metals-API Documentation.
- Symbol coverage for metals and currencies: Metals-API Supported Symbols.
- Background on troy ounces: Investopedia: Troy Ounce Explained.
- Market context for gold benchmarks and insights: LBMA Prices and Data.
Putting it all together: a minimal, robust blueprint
- Symbols and units: Validate “XAU” and unit “per troy ounce” at ingest; store base currency.
- Historical pulls: Use time-series for ranges; historical single date for patches; cache long-lived results.
- Analytics enrichments: Add fluctuation and OHLC into separate fact tables; compute USD/oz and USD/g as standardized metrics.
- Operations: Implement retries, backoff, circuit breakers, and observability. Archive raw JSON and track lineage.
- Security: Keep access_key server-side; rotate regularly; proxy public clients when needed.
- Scale: Batch large backfills; compress and partition data; pre-warm critical cache keys at app startup.
Example: tying endpoints together for a gold price report
- Step 1: Time-series for the last 90 days of XAU to build the chart and compute rolling indicators.
- Step 2: OHLC for yesterday to populate candlestick summary and volatility notes.
- Step 3: Fluctuation from last week’s close to today for headline percentage change.
- Step 4: Bid/Ask snapshot right now to convey execution conditions (spread) in the UI.
- Step 5: Convert endpoint to compute an audit-ready USD→XAU or XAU→USD number for a sample invoice or treasury adjustment.
Single curl to retrieve a historical gold rate (ready to paste)
curl -G "https://metals-api.com/api/2026-09-16" \
-d access_key=YOUR_ACCESS_KEY \
-d base=USD \
-d symbols=XAU
If the response’s success is true, parse the rates.XAU value, invert it for USD/oz if needed, and store it along with unit and base. See more parameter options in the official documentation.
Notes on additional endpoints without embedded JSON here
The following capabilities are available and often valuable alongside XAU history, especially as you scale your use cases. Where this article does not embed a JSON sample, consult the official docs for request/response schemas:
- Intraday: For finer granularity within a day, query intraday XAU rates. This is useful when backtesting strategies sensitive to sub-daily moves.
- Carat: For jewelry and retail pricing, request gold by carat to align API values with catalog SKUs and buyer expectations.
- Lowest/Highest Price: Request a given date’s extremes to validate alerts, sanity-check OHLC, or build alternative visualizations.
- Historical LME: If you expand into industrial metals with LME coverage back to 2008, this endpoint rounds out your macro view.
- Supported Symbols: Programmatically fetch the current list to validate inputs at runtime and adapt UIs automatically.
For up-to-date schemas and request parameters, review the Metals-API Documentation. If you haven’t already, visit the Metals-API Website to create an account and get your API key.
Conclusion
Retrieving and operationalizing historical Gold (XAU) data with Metals-API is straightforward and production-friendly. With a few well-chosen endpoints—historical snapshots, time-series windows, fluctuation, OHLC, bid/ask, and convert—you can build robust data pipelines that power charts, alerts, pricing engines, and quant research. Respect base currency conventions and units (“per troy ounce”), normalize USD per oz or per gram as needed, and store metadata like timestamps for auditability. Design for reliability with caching, retries, observability, and lineage, and you’ll have a future-proof foundation as your analytics deepen or your product scope widens into other metals and carat-based pricing. To explore parameters and start testing today, head to the Metals-API Documentation and grab a free key from the Metals-API Website. For symbol coverage, bookmark the Metals-API Supported Symbols page.
FAQ
What unit does Metals-API use for gold?
Responses include unit: "per troy ounce". Convert to USD per ounce by inverting rates.XAU when base=USD. Convert to grams by dividing USD per ounce by 31.1034768.
How do I handle missing days in the time series?
Don’t assume every calendar day exists. Metals markets have weekends/holidays. Leave gaps as-is or apply explicit interpolation rules with clear labeling.
Can I get OHLC for XAU to build candlestick charts?
Yes. Use the OHLC endpoint to retrieve open, high, low, close per date. Store separately from spot rates to avoid confusion.
How do I model transaction costs?
Use the Bid/Ask endpoint. In backtests, apply ask for buys and bid for sells. Persist spread to measure slippage and execution quality.
What’s the easiest way to compute USD per ounce from the API?
If base=USD, compute 1 / rates.XAU. For USD per gram, divide that result by 31.1034768.
Where can I find supported symbols?
See the full, current list here: Metals-API Supported Symbols.
How often does the latest endpoint update?
Update frequency depends on your plan (e.g., every 60 minutes, every 10 minutes). Cache accordingly and avoid polling more frequently than needed.
How should I store the data for audits?
Persist raw JSON, base, unit, timestamp, and original query parameters. Keep normalized tables for analytics and materialize common metrics (USD/oz, USD/g).
How do I start?
Read the Metals-API Documentation and create a key at the Metals-API Website. Then use historical and time-series calls to backfill your XAU dataset.