Fetching Stellar (XLM) prices with this API made easy
Fetching Stellar (XLM) prices with this API made easy: here’s a practical, developer-first walkthrough of how to programmatically price XLM-denominated products and portfolios using Metals-API’s real-time and historical metal and currency rates as your anchor leg. Because Metals-API specializes in precious and industrial metals plus fiat currencies, the winning architecture for XLM is to bridge through USD (or another fiat currency) you select as base, then combine that with your preferred XLM/USD feed to compute any cross-rate, blended hedge, or bill-of-materials valuation. This article shows you how to structure that workflow, implement each call with robust error handling and caching, and optimize for throughput across trading tools, fintech products, e-commerce repricing, ERP cost control, and research pipelines.
What you will build: a clean XLM pricing workflow using Metals-API
In practical terms, you will:
- Use Metals-API to fetch USD-based prices for gold, silver, platinum, palladium, copper, aluminum, nickel, and zinc, including OHLC and bid/ask where supported by your plan.
- Anchor all calculations to a consistent base currency (USD by default), ensuring units are explicit (per troy ounce) and timestamps are handled consistently.
- Combine those USD metal rates with your Stellar (XLM) quote from a crypto market feed to compute XLM-to-metal conversions (e.g., ounces-per-XLM), as well as fiat-to-XLM conversions for invoicing and portfolio P&L.
- Backfill XLM-referenced charts and research notebooks using Metals-API historical and time-series endpoints for the metals and currency side, then pair those with your XLM/USD historicals.
- Alert on fluctuations using the fluctuation endpoint for metals/currencies, and route threshold events into your risk or repricing logic that references your live XLM/USD source.
We will use the following Metals-API resources as our backbone. For full specifications and the latest updates, see the official Metals-API Documentation and the always-current Metals-API Supported Symbols. If you do not yet have credentials, start at the Metals-API Website to get a free API key in minutes.
Why bridge through USD for Stellar (XLM) pricing
Metals-API delivers metals prices and currency rates with USD as the default base. In many production environments, using USD (or another fiat base that you choose and your plan supports) is the most stable and resilient way to calculate cross-asset prices. Because crypto pairs can be fragmented across venues and deep liquidity for XLM may be concentrated in XLM/USD, using USD as the neutral anchor ensures consistent mark-to-market across your metals, fiat, and crypto legs. In practice:
- Fetch metal prices as USD per troy ounce from Metals-API.
- Fetch XLM/USD from your crypto market data source of choice.
- Compute ounces-per-XLM or XLM-per-ounce with straightforward division, respecting units and timestamps.
This separation of concerns simplifies monitoring, auditing, and reconciliation: you know exactly which system is authoritative for each leg. It also enables modular failover; if your XLM feed is momentarily stale, you can still price the metals leg for other workflows, and vice versa.
Symbols, units, and base currency mechanics
Metals-API returns metals prices “per troy ounce” by default and uses USD as the base currency unless otherwise specified and allowed by your plan. A few key considerations:
- Units: The default unit is troy ounces, not grams. 1 troy ounce ≈ 31.1034768 grams. If your UX or reporting expects grams, perform a post-processing conversion.
- Base: The base field in the response indicates the currency against which all rates are quoted (default “USD”). Align this with your valuation currency.
- Timestamps: The API returns unix timestamps and ISO dates. Normalize to UTC in your downstream systems and log the timestamp of both your metals fetch and your XLM fetch.
- Symbols: Metals commonly used include:
- XAU (Gold), XAG (Silver), XPT (Platinum), XPD (Palladium)
- XCU (Copper), XAL (Aluminum), XNI (Nickel), XZN (Zinc)
Quick reference: metals symbols and unit
| Symbol | Metal | Unit (default) | Notes |
|---|---|---|---|
| XAU | Gold | per troy ounce | Used in bullion pricing and jewelry, often paired with carat detail for purity |
| XAG | Silver | per troy ounce | Industrial and jewelry use cases; volatility can differ from gold |
| XPT | Platinum | per troy ounce | Catalysts, auto, and high-end jewelry |
| XPD | Palladium | per troy ounce | Emission control applications and catalysts |
| XCU | Copper | per troy ounce | Industrial bellwether; manufacturing and infrastructure |
| XAL | Aluminum | per troy ounce | Lightweight manufacturing, packaging, aerospace |
| XNI | Nickel | per troy ounce | Batteries, alloys, stainless steel |
| XZN | Zinc | per troy ounce | Galvanization and alloys |
For a full, up-to-date list, consult the Metals-API Supported Symbols.
From USD metals to Stellar (XLM): conversion blueprint
To express a metal price in XLM, bridge through USD:
- Get metal_per_USD from Metals-API (e.g., XAU per USD).
- Get USD_per_XLM or XLM_per_USD from your crypto source. Most crypto feeds provide XLM/USD (USD per XLM) or its inverse.
- If Metals-API returns XAU per USD and your crypto feed returns USD per XLM, then:
- XAU per XLM = (XAU per USD) × (USD per XLM)
- Or XLM per XAU = 1 ÷ (XAU per XLM)
Always record both timestamps. In live trading tools, consider adding a guardrail: if the time delta between your metals timestamp and your XLM timestamp exceeds a threshold (e.g., 60 seconds for intraday contexts), flag the price as stale.
Latest rates: the backbone of intraday pricing
When your plan includes the Latest Rates endpoint, you can retrieve real-time exchange rates updated at plan-specific intervals (e.g., every 60 minutes, 10 minutes, etc.). These rates are USD-based by default.
Complete curl request example for latest metals
The example below fetches current rates for a representative basket. Replace YOUR_KEY with your actual access_key.
curl -G "https://metals-api.com/api/latest" \
--data-urlencode "access_key=YOUR_KEY" \
--data-urlencode "symbols=XAU,XAG,XPT,XPD,XCU,XAL,XNI,XZN"
Representative JSON response
{
"success": true,
"timestamp": 1789518384,
"base": "USD",
"date": "2026-09-16",
"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"
}
Fields you will actually use
- success: Boolean flag for request status.
- timestamp/date: Use for staleness checks and audit logs; normalize to UTC.
- base: Your anchor currency (default “USD”).
- rates: Dictionary of metal symbols to numeric rates, expressed in the unit field and relative to base.
- unit: Clarifies the quantitative unit, typically “per troy ounce.”
Turning latest metals into XLM metal prices
Suppose your crypto feed returns XLM/USD = 0.1200 (USD per XLM) at timestamp T2, and Metals-API returns XAU per USD = 0.000482 at timestamp T1.
- XAU per XLM = 0.000482 × 0.1200 = 0.00005784 troy ounces per XLM
- XLM per XAU = 1 ÷ 0.00005784 ≈ 17,287.9 XLM per troy ounce
Record T1 and T2 and consider the pair stale if |T1 − T2| exceeds your internal SLA. If you’re repricing product SKUs in an e-commerce storefront that accepts XLM, round sensibly and cache short-lived results to reduce load and avoid price flicker.
Parsing the Latest Rates in JavaScript
Below is a minimal JavaScript example showing how to fetch and parse the metals leg, then combine with an external XLM/USD quote. Substitute your real access key and XLM source.
// Fetch metals leg from Metals-API, then combine with XLM/USD from your crypto feed.
async function priceGoldInXLM() {
const metalsUrl = new URL("https://metals-api.com/api/latest");
metalsUrl.searchParams.set("access_key", "YOUR_KEY");
metalsUrl.searchParams.set("symbols", "XAU");
const metalsResp = await fetch(metalsUrl.toString(), { timeout: 8000 });
if (!metalsResp.ok) throw new Error(`Metals-API HTTP ${metalsResp.status}`);
const metalsData = await metalsResp.json();
if (!metalsData.success || !metalsData.rates || typeof metalsData.rates.XAU !== "number") {
throw new Error("Invalid metals payload");
}
// Example: fetch XLM/USD (USD per XLM) from your crypto market data source.
// Replace with your own provider logic.
const xlmUsd = await getXlmUsdFromYourProvider(); // e.g., returns { price: 0.1200, timestamp: 1699999999 }
const xauPerUsd = metalsData.rates.XAU; // XAU per USD
const usdPerXlm = xlmUsd.price; // USD per XLM
// Gold per XLM:
const xauPerXlm = xauPerUsd * usdPerXlm; // troy ounces per XLM
// Optionally return both directions for convenience:
const xlmPerXau = 1 / xauPerXlm;
return {
xauPerXlm,
xlmPerXau,
metalsTimestamp: metalsData.timestamp,
xlmTimestamp: xlmUsd.timestamp,
unit: metalsData.unit // "per troy ounce"
};
}
Tip: If you observe intermittent delays in your crypto feed, apply a short TTL cache (e.g., 5–30 seconds) on the combined result to stabilize retail price displays and reduce load on both data providers.
Historical rates for research, backtesting, and auditability
Historical rates are available going back years (see documentation). Use historical metals and fiat currency series from Metals-API, and pair them with your archived XLM/USD feed to compute cross-rates and normalize P&L.
Historical daily rate example
{
"success": true,
"timestamp": 1789431984,
"base": "USD",
"date": "2026-09-15",
"rates": {
"XAU": 0.000485,
"XAG": 0.03825,
"XPT": 0.000915,
"XPD": 0.000748
},
"unit": "per troy ounce"
}
In a backfill job, iterate across your desired date range. Always capture:
- The Metals-API date and timestamp for each bar.
- Your XLM/USD historical quote’s timestamp and any exchange/venue metadata.
- Your transformation logic and unit conversions in a reproducible notebook or ETL.
Time-series for robust windowed analyses
Use time-series to pull continuous daily rates between two dates, ideal for rolling-window analytics, correlation studies, and building composite indices that you will later translate into XLM terms through your USD leg.
Time-series JSON example
{
"success": true,
"timeseries": true,
"start_date": "2026-09-09",
"end_date": "2026-09-16",
"base": "USD",
"rates": {
"2026-09-09": {
"XAU": 0.000485,
"XAG": 0.03825,
"XPT": 0.000915
},
"2026-09-11": {
"XAU": 0.000483,
"XAG": 0.0382,
"XPT": 0.000913
},
"2026-09-16": {
"XAU": 0.000482,
"XAG": 0.03815,
"XPT": 0.000912
}
},
"unit": "per troy ounce"
}
Key implementation details:
- Data gaps: Weekends and holidays may impact update cadence. Metals spot markets often have lower activity outside major trading hours. Your time-series queries will return available dates; handle missing dates gracefully.
- Alignment: Align time-series bars from Metals-API with your XLM/USD barset by date (daily close) or by a common end-of-day timestamp. Store both sides at consistent granularity.
- Resampling: If your XLM feed is higher frequency (e.g., minute bars), downsample to daily close to match the metals daily time-series before computing cross-rates.
Intraday nuance: bid/ask and OHLC for precise quoting
For more precise trading or quoting workflows, use Bid/Ask and OHLC if your plan supports them.
Bid and Ask for tight spreads and slippage modeling
{
"success": true,
"timestamp": 1789518384,
"base": "USD",
"date": "2026-09-16",
"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"
}
Use bid/ask for:
- Risk-aware quotes: If you sell to customers paying in XLM, use ask for costs and bid for inventory valuations, or vice versa depending on direction.
- Slippage models: Combine metals spreads with your XLM venue spread and fee tier to compute end-to-end slippage bounds.
OHLC for charting and signal generation
{
"success": true,
"timestamp": 1789518384,
"base": "USD",
"date": "2026-09-16",
"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"
}
Use OHLC when:
- Generating signals that respect shadow ranges (e.g., breakout detection on highs/lows).
- Building candlestick charts where you will later overlay your XLM/USD intraday bars to create synthetic XLM-denominated candles for metals.
Fluctuation endpoint: alerts and anomaly detection
The fluctuation endpoint summarizes how rates changed between two dates. This is ideal for risk thresholds in ERP or trading dashboards; whenever a metal’s daily change exceeds a threshold, trigger a notification that includes your latest XLM/USD quote for contextualized XLM impact.
Fluctuation example
{
"success": true,
"fluctuation": true,
"start_date": "2026-09-09",
"end_date": "2026-09-16",
"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"
}
Operational best practice:
- Set separate alert thresholds for absolute change and percentage change, then translate to XLM impact with your latest crypto leg.
- Throttle alerting to avoid noisy weekends or low-liquidity hours.
Convert endpoint: fiat-to-metal, metal-to-fiat, and bridging math
The Convert endpoint performs on-the-fly conversions between metals and currencies. In XLM workflows, use it to simplify internal math on the metals and fiat side, then apply your external XLM/USD leg for the final hop.
Convert example
{
"success": true,
"query": {
"from": "USD",
"to": "XAU",
"amount": 1000
},
"info": {
"timestamp": 1789518384,
"rate": 0.000482
},
"result": 0.482,
"unit": "troy ounces"
}
- Use this to quickly compute ounces of a given metal for operational invoices in USD before you translate to XLM with your crypto leg.
- The “unit” field clarifies output units, which remain critical for SKU and BOM reporting.
Lowest/highest price endpoint: guardrails for quotes
The lowest-highest/YYYY-MM-DD endpoint returns daily extremes. In XLM quoting, you can apply these as sanity bands so the XLM-denominated quote never deviates outside the day’s extremes scaled by your XLM/USD at evaluation time.
What to watch for
- Always pair the extremes with their date to avoid misinterpreting stale bounds.
- If your XLM/USD is very volatile, apply an additional buffer.
Historical LME data for industrial metals
If you price copper, aluminum, nickel, zinc and rely on London Metal Exchange historicals, use the historical-lme endpoint (dating back to 2008 per docs) to strengthen long-horizon analyses and then apply your XLM bridging logic.
Ensure your internal symbol mapping aligns with the LME symbols you consume. Check the Metals-API Supported Symbols for LME coverage details.
Intraday endpoint for single-symbol precision
When you only need intraday data for a single symbol (say, XAU) at a higher frequency supported by your plan, the intraday endpoint reduces payload size and improves latency. Pair this stream with your XLM/USD intraday source, and compute rolling XLM-denominated prices.
Carat endpoint for gold retail pricing
Gold jewelry retail often requires carat-level pricing. The carat endpoint gives you gold rates by carat for consumer-facing price tags that you can express in XLM at checkout by applying your XLM/USD uplift. This minimizes custom density/purity math in your frontend.
Authentication and authorization
All requests include your API key via the access_key parameter. Treat this credential as a secret. Security practices:
- Do not embed keys in client-side code for production; route requests through your server.
- Rotate keys periodically.
- Restrict access at the network and application layer where possible.
Get your key at the Metals-API Website and review usage examples in the Metals-API Documentation.
Response handling, validation, and sanitization
- Check success before using fields.
- Validate numeric fields (e.g., rates.XAU) against NaN/Infinity and reasonable bounds.
- Trust but verify the unit field for any downstream formatting.
- Normalize timestamps to UTC and store as integers to avoid float precision issues in some languages.
Error handling and recovery strategies
When integrating multiple data providers (Metals-API for metals/currencies and your crypto feed for XLM), graceful degradation is key:
- Retry with exponential backoff on transient network errors.
- Serve a cached price within a short TTL if one leg is temporarily unavailable; label it as “delayed.”
- Alert your SRE channel if either leg is stale beyond a set threshold (e.g., 2× your expected update cadence).
- Implement circuit breakers to avoid cascading failures.
Caching and performance optimization
- Cache Latest Rates responses for a few seconds to a minute, aligning with your plan’s update interval.
- Deduplicate requests across services by sharing a central pricing microservice and in-memory cache (e.g., Redis) that publishes events to consumers.
- For dashboards, batch symbols in a single request and fan out results internally.
- Prefer time-series calls for backfills rather than iterating one date per request.
Handling weekends, holidays, and market closures
Metals and fiat markets exhibit different liquidity patterns than crypto. Practical points:
- Expect fewer updates and wider spreads in off-hours. Do not misinterpret this as an API issue.
- During closures, Latest Rates may remain unchanged; mark UI with “market hours” info to manage expectations.
- If your crypto leg stays active 24/7, decide whether to hold metals quotes constant or widen your XLM quote bands as liquidity thins.
Data aggregation and analysis techniques
- Cross-rate synthesis: Build derived series like XAU/XLM using synchronized Metals-API USD legs and your XLM/USD series.
- Volatility estimations: Compute rolling standard deviation on metals in USD and then translate realized vol into XLM terms for hedging policies.
- Composite baskets: Create weighted baskets (e.g., industrial index of XCU, XAL, XNI, XZN) and publish in XLM.
Security considerations
- Secure secrets: Keep access_key in server-side vaults; never expose in public repos.
- Transport security: Enforce HTTPS end to end.
- Input sanitization: Sanitize query parameters like symbols to a whitelist set.
- Output hardening: Serialize numeric fields consistently; avoid locale-dependent formatting that can break parsers.
Architectural patterns for XLM-denominated pricing
- Pricing microservice: One internal service fetches Metals-API data and crypto quotes, performs cross-rate math, and publishes results to Kafka or a pub/sub bus.
- Idempotent jobs: Backfill and time-series jobs should be idempotent, using date partitions and checksums to avoid duplication.
- Feature flags: Toggle between different XLM feeds or fallback policies without redeploying code.
- Observability: Emit metrics for freshness (seconds since last metals update and since last XLM tick), failure rates, and cache hit ratios.
How the Convert and Latest endpoints simplify checkout and ERP flows
Operational scenarios:
- Retail checkout in XLM: Fetch Latest metals, compute product BOM cost in USD, convert to ounces with Convert, then multiply by USD per XLM to display a live XLM total.
- Procurement planning: Use time-series metals in USD to forecast cost baselines; when approving purchases funded in XLM, apply the current XLM/USD to translate budgets.
- Hedging reports: With Bid/Ask, simulate quoted execution prices for both legs and compute scenario P&L in XLM.
OHLC and Lowest/Highest for risk dashboards
Use OHLC to populate candlesticks for metals in USD, then render a synchronized pane that shows implied XLM candlesticks by multiplying each bar with XLM/USD. Apply daily lowest/highest as overlays to avoid quoting outside of known bounds during thin liquidity windows.
Tellurium (TE): a lens on digital transformation in metal markets
Tellurium, while a less-traded industrial metal, highlights broader themes shaping metals and fintech:
- Digital transformation: Standardized APIs like Metals-API allow industrial players to integrate price discovery into ERP and MES systems in near real-time, improving quoting speed and transparency.
- Technological innovation: Streaming intraday endpoints, OHLC, and bid/ask support more sophisticated tools such as automated repricing engines and algorithmic hedging overlays.
- Data analytics and insights: With clean historical series, analysts can study cross-elasticities between TE-adjacent metals (e.g., in semiconductor alloys) and broader market trends.
- Smart technology integration: IoT-enabled production lines can pull live cost inputs via APIs, adjust process parameters, and schedule batches when input costs (expressed in fiat or even in XLM for crypto-native treasuries) are favorable.
- Future trends: As crypto rails like Stellar mature, bridging fiat, metals, and digital assets becomes simpler—APIs that keep units, timestamps, and base currency rigorously defined make multi-asset operations auditable and scalable.
Practical guidance a beginner might miss
- Unit discipline: Always annotate values with units and retain unit metadata through every transformation, especially when switching between ounces and grams.
- Base awareness: If you change base from USD to another currency (where supported), update documentation and downstream multipliers. Mismatched base assumptions cause silent errors.
- Timezone control: Store timestamps in UTC and convert to display timezones at the UI edge.
- Weekend behavior: Expect fewer changes for metals on weekends; don’t trigger false outage alerts.
- Caching: Cache short-lived results to avoid jitter in UI quotes.
End-to-end example: pricing a silver product in XLM at checkout
- Fetch XAG per USD via Latest Rates.
- Fetch USD per XLM from your crypto feed.
- Compute XAG per XLM = (XAG per USD) × (USD per XLM).
- For a 100-gram product at 92.5% silver purity:
- Convert grams to troy ounces: 100 g ÷ 31.1034768 ≈ 3.2151 ozt total mass.
- Pure silver content ≈ 2.9739 ozt.
- Value in XLM = 2.9739 × (XLM per ozt) where XLM per ozt = 1 ÷ (XAG per XLM).
- Add fees, taxes, and a rounding policy. Cache final result for 15–30 seconds.
Data lineage and audit trails
- Log the metals response payload hash, timestamp, and unit.
- Log your crypto quote source, venue, and timestamp.
- Store the exact formula string for each price transformation to ensure reproducibility in audits.
Performance and scaling
- Batch symbols in one Latest Rates request for dashboards.
- Fan out updates internally via websockets or pub/sub to avoid polling storms.
- Use warm caches and coalescing to collapse concurrent identical requests into a single upstream call.
- Apply adaptive refresh: slower refresh overnight, faster during peak trading windows.
Compliance and governance
- P&L and NAV: Make end-of-day snapshots with both metals and XLM legs frozen at the same cut-off time.
- Policy codification: Document the source-of-truth and failover sequence for each leg (metals and XLM).
- Vendor risk: Monitor provider SLAs and set internal SLOs.
Getting started quickly
- Obtain an access key at the Metals-API Website.
- Review endpoint parameters in the Metals-API Documentation.
- Validate supported symbols against your needs using the Metals-API Supported Symbols page.
Additional resources
- Stellar Network for information about the Stellar (XLM) protocol and ecosystem.
- Bank for International Settlements publications for market microstructure insights relevant to cross-asset pricing.
- Troy ounce explained for unit conversion and reference.
Conclusion
Bridging Stellar (XLM) pricing with Metals-API is straightforward once you anchor your workflow in a consistent base currency and respect units and timestamps. Metals-API provides reliable metals and currency data—Latest Rates for intraday quotes, Historical and Time-Series for backfills, Bid/Ask for execution-aware modeling, OHLC for charting, and specialty endpoints like Convert, Carat, Lowest/Highest, Intraday, and Historical LME for industrial depth. Pair these with your XLM/USD feed to express any metal or fiat price in XLM for checkout, procurement, and portfolio management. Start by grabbing a free key from the Metals-API Website and explore examples in the Metals-API Documentation. With careful handling of units, caching, and staleness windows, you’ll deliver stable, audit-ready XLM-denominated pricing at scale.
FAQ
Does Metals-API provide crypto prices like XLM directly?
Metals-API focuses on precious and industrial metals and fiat currency rates. For XLM, use your preferred crypto source and bridge via USD (or another fiat base you select in Metals-API, depending on your plan).
What unit are metal prices returned in?
By default: per troy ounce. Always check the “unit” field in responses and convert to grams if needed.
Which base currency should I use?
USD is default. Choose a base that aligns with your accounting currency. Ensure all downstream math uses the same base, and re-document any base changes.
How do I handle weekend or holiday data?
Expect slower updates and potential unchanged quotes. Don’t mistake this for system errors. Mark charts accordingly and avoid over-alerting.
How should I cache results?
Short TTLs (e.g., 5–60 seconds) stabilize UIs and reduce load. Align TTL with your plan’s update frequency, and add jitter to prevent thundering herds.
What about bid/ask vs last trade?
Use bid/ask for executable-like quotes and slippage models on the metals leg. Your crypto provider may also offer bid/ask; apply symmetric policies to both legs when computing XLM-denominated values.
How do I get started?
Visit the Metals-API Website to obtain a free API key and dive into the Metals-API Documentation for endpoint details and parameters. Check the Metals-API Supported Symbols for coverage.