Integrating Salem Gold 22k (SALE-22k) - Per Gram Spot Price API into a Node.js backend

Metals-API 9 min read
Integrating Salem Gold 22k   (SALE-22k) - Per Gram Spot Price API into a Node.js backend

You need to price Salem Gold 22k (SALE-22k) per gram inside a Node.js backend—accurately, reproducibly, and with minimal latency. By the end of this guide, you’ll query Metals-API for spot gold, convert it to a per-gram 22k equivalent, cache it, and serve it to your app for real-time e-commerce pricing, RFQ/trading tools, or ERP integrations.

What we’re building: SALE-22k per gram derived from spot XAU

Metals-API quotes gold as XAU (troy ounces). SALE-22k is a retail-grade product (22 karat gold). We’ll compute SALE-22k per gram as a transformation of spot gold:

Illustration: Integrating Salem Gold 22k (SALE-22k) - Per Gram Spot Price API into a Node.js backend
  • Fetch spot XAU with the Latest endpoint.
  • Use USDXAU to get USD per troy ounce directly.
  • Convert troy ounce to grams (1 troy oz = 31.1034768 g).
  • Apply 22k purity factor: 22 / 24 = 0.9166667.
  • Result: SALE-22k USD per gram, ready for your backend.

If you also need backfill for charts or P&L archives, you can query historical or time-series endpoints the same way, then apply the gram/purity transforms on the fly. For endpoint details, see the Documentation. If you’re confirming symbol availability, check the live catalog on the Symbols page.

Endpoint choice and units you must get right

We focus on two endpoints:

  • Latest rates: to price SALE-22k per gram now.
  • Historical or Time-series: optional, to backfill charts or validate intraday changes.

Key unit conventions from Metals-API:

  • Base currency: USD by default.
  • Metals are quoted per troy ounce (not gram). See also troy ounce basics from the London Bullion Market Association (LBMA): LBMA.
  • Metric conversion: 1 troy ounce = 31.1034768 grams. NIST background on SI units: NIST – SI Units.

Reading Metals-API fields correctly:

  • rates.XAU is “troy ounces per 1 USD” (an inverted quote).
  • rates.USDXAU is “USD per troy ounce.” Use this directly for pricing.

Get SALE-22k per gram with the Latest endpoint

First, get an API key. Metals-API requires a key and does not offer a free trial. You can obtain yours here: Register. If you need programmatic key management or enterprise controls, explore MCP.

cURL: fetch latest XAU and USDXAU

Request the latest gold spot with both the inverted and conventional quotes so you can use USDXAU for pricing and keep XAU for checks or derived analytics.

curl -s "https://metals-api.com/api/latest?access_key=YOUR_API_KEY&symbols=XAU,USDXAU"

Official JSON response sample

Below is an official response sample to mirror structure and field names you will receive. We’ll use USDXAU from this payload to compute SALE-22k per gram in our Node.js code.

{"success":true,"timestamp":1793668080,"date":"2026-11-03","base":"USD","rates":{"XAU":0.00025301082886348,"USD":1,"USDXAU":3952.399999999928}}

What these fields mean for SALE-22k per gram

  • success: true indicates the request parsed and the service returned data.
  • timestamp: Unix epoch seconds. Use it to set cache TTLs and to time-align your downstream systems.
  • date: Calendar date associated with the snapshot.
  • base: "USD" means rates are relative to USD.
  • rates.XAU: 0.000253... troy ounces per 1 USD (inverted quote).
  • rates.USDXAU: 3952.3999... USD per troy ounce. This is the field you use to compute SALE-22k per gram.

Node.js code: compute SALE-22k per gram from USDXAU

This example uses native fetch (Node 18+). It calls the Latest endpoint, extracts USDXAU, converts to per gram, applies the 22k purity factor, and returns a rounded result suitable for quoting or cart pricing.

import http from "node:http";

// Configuration
const METALS_API_URL = "https://metals-api.com/api/latest";
const API_KEY = process.env.METALS_API_KEY || "YOUR_API_KEY";

// Constants
const TROY_OUNCE_TO_GRAM = 31.1034768;
const PURITY_22K = 22 / 24; // 0.916666...

async function fetchSpot() {
  const url = `${METALS_API_URL}?access_key=${encodeURIComponent(API_KEY)}&symbols=XAU,USDXAU`;
  const res = await fetch(url, { timeout: 10000 });
  if (!res.ok) {
    throw new Error(`Metals-API HTTP ${res.status}`);
  }
  const json = await res.json();

  if (!json.success) {
    throw new Error(`Metals-API error: ${JSON.stringify(json)}`);
  }

  const { timestamp, date, base, rates } = json;
  const { USDXAU } = rates || {};
  if (typeof USDXAU !== "number") {
    throw new Error("USDXAU not present in response");
  }

  // Compute SALE-22k price per gram in USD
  const usdPerOunce = USDXAU;
  const usdPerGram24k = usdPerOunce / TROY_OUNCE_TO_GRAM;
  const usdPerGram22k = usdPerGram24k * PURITY_22K;

  return {
    timestamp,
    date,
    base,
    usdPerOunce24k: usdPerOunce,
    usdPerGram24k: usdPerGram24k,
    usdPerGram22k: usdPerGram22k,
  };
}

// Simple HTTP server to expose the computed SALE-22k per gram
const server = http.createServer(async (req, res) => {
  if (req.url === "/price/sale-22k" && req.method === "GET") {
    try {
      // Optional: add caching here (see notes below)
      const spot = await fetchSpot();
      const payload = {
        symbol: "SALE-22k",
        unit: "USD per gram",
        date: spot.date,
        timestamp: spot.timestamp,
        price_22k: Number(spot.usdPerGram22k.toFixed(4)),
        meta: {
          base: spot.base,
          usd_per_oz_24k: Number(spot.usdPerOunce24k.toFixed(2)),
          usd_per_gram_24k: Number(spot.usdPerGram24k.toFixed(4)),
          purity_factor: PURITY_22K,
        },
      };
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(payload));
    } catch (err) {
      res.writeHead(502, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: String(err.message || err) }));
    }
    return;
  }

  res.writeHead(404, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ error: "Not found" }));
});

server.listen(8080, () => {
  console.log("SALE-22k server running on http://localhost:8080/price/sale-22k");
});

Why we read USDXAU directly

Metals-API provides both “XAU” and “USDXAU” so you don’t have to invert manually. USDXAU eliminates floating-point inversion risk and communicates pricing intent explicitly (USD per troy ounce). You can still log XAU for consistency checks, arbitrage testing, or quant analytics.

Converting karats and grams correctly

Karats indicate gold content out of 24 parts. SALE-22k indicates 22 parts pure gold and 2 parts alloy, i.e., 91.6667% purity. Converting to per gram is a two-step transform: ounce-to-gram, then purity factor. The table below shows purity multipliers you may apply when pricing multiple products.

Label Purity (karat) Purity factor (multiplier) Use case
Fine/24k 24k 1.000000 Spot reference (XAU)
Salem Gold 22k 22k 0.9166667 Retail jewelry, SALE-22k
Jewelry 18k 18k 0.7500000 Common consumer jewelry

For SALE-22k per gram, multiply the 24k per-gram price by 0.9166667. If you charge making charges, taxes, or spreads, add them in your own business logic after computing the bullion content.

Production tips that save time and errors

  • Timestamps and timezone: Metals-API returns a Unix timestamp (seconds) and a date string. Use the timestamp to drive cache refresh and market-day logic. Always convert to your app’s timezone in presentation code.
  • Caching: Backend cache should live at least until the next expected update window for your plan tier. Use the timestamp field to detect and avoid redundant refreshes. Memory caches (e.g., LRU) or a shared cache like Redis are typical.
  • Weekend/market closures: Precious metals pricing may not change on certain weekends or holidays. Your “latest” call can return the previous business day. Avoid triggering alerts just because the calendar rolled over; compare timestamps.
  • Fallback logic: If USDXAU is missing, you can compute it as 1 / (XAU in oz/USD), but only when XAU is present and nonzero. Prefer USDXAU when available.
  • Validation: Guard against division by zero and NaN results. Normalize to a fixed decimal precision when exposing prices externally.
  • Symbols: Confirm any symbol you rely on at the live list: Metals-API Supported Symbols.

Optional: backfill SALE-22k series for charts

If you need a SALE-22k price history for visualization or analytics, call the Historical or Time-series endpoints for XAU, then apply the same gram and purity transformations day-by-day in your pipeline. That keeps your SALE-22k series consistent with spot references and avoids storing duplicated raw data. For request shapes and date handling, see the endpoint docs: Metals-API Documentation.

System design notes for trading and commerce

  • Separation of concerns: Keep “market math” (ounce-to-gram, karat factors) in one module, and “commercial math” (fees, spreads, sales tax/VAT) in another. This makes audits and price-dispute resolution easier.
  • Idempotent updates: When the timestamp doesn’t advance, do not emit a new internal event; downstream consumers should key on that timestamp.
  • Rounding policy: Decide rounding per product type. For quoting, 2–4 decimals on per-gram USD is common. For settlement P&L, store full precision and round only at display/export boundaries.
  • Observability: Log the Metals-API timestamp, the computed per-gram 24k and 22k values, and any adjustments. This simplifies recon if a customer screenshot conflicts with your system.
  • Feature discovery: If you later need depth (bid/ask), OHLC, or intraday granularity, Metals-API exposes dedicated endpoints. Start at the Documentation to select the right one for your use case.

Troubleshooting common issues

  • Unexpected flatlines: If your SALE-22k price doesn’t move across days, check the raw timestamp. If it’s unchanged, you’re legitimately seeing the same snapshot (e.g., weekend).
  • Inverted math errors: Using XAU directly requires an inversion for USD per ounce. Prefer USDXAU to avoid 1/x precision drift.
  • Precision drift: Chain operations can amplify floating-point noise. Keep intermediate calculations in double precision, then round only at the API boundary.
  • Symbol mismatch: If you attempt to fetch a non-existent symbol, Metals-API won’t return it in rates. Always verify symbols at Symbols.

Why SALE-22k via API unlocks better product and risk workflows

Digitizing SALE-22k pricing lets you align your storefront, RFQ, and ERP in near real-time without manual spreadsheets. Your analytics team can model inventory exposure using quant-ready timestamps and standardized units, while product managers can experiment with maker fees and hedging spreads without changing the market source of truth. With a clean separation between spot data (XAU, USDXAU) and the SALE-22k transformation, you can reuse the same pipeline for other karat products using consistent math.

FAQ

How do I convert USD per ounce to USD per gram?
Divide USDXAU (USD per troy ounce) by 31.1034768 to get USD per gram at 24k purity, then multiply by 22/24 for SALE-22k.

Which field should I use for pricing—XAU or USDXAU?
Use USDXAU (USD per troy ounce) when pricing. XAU (oz per USD) is useful for validations and some quant models but requires inversion to get USD per ounce.

Why is the date unchanged on weekends?
Metals markets can be inactive on weekends/holidays. The Latest endpoint returns the last valid snapshot with its timestamp. Use the timestamp to decide whether to refresh caches or generate alerts.

What base currency does Metals-API use?
By default, USD. The sample above shows "base": "USD". Confirm base and any options you need in the Documentation.

Can I directly request SALE-22k as a symbol?
SALE-22k is a business label for your product. Derive its price from XAU using the gram and karat transforms described here. Check supported tickers anytime on the Symbols page.

Ready to serve SALE-22k per gram from your Node.js backend? Get your API key now and start integrating: Register. For key management and orchestration, see MCP, and keep the reference handy in the Documentation.