API to Get the Uniswap (UNI) Price: retrieving historical OHLC data

Metals-API 9 min read
API to Get the Uniswap (UNI) Price: retrieving historical OHLC data

You need a reliable way to fetch the Uniswap (UNI) price right now and also backfill historical OHLC (open, high, low, close) candles for charting, risk, or backtests. By the end of this guide, you will query the UNI price from Metals-API, interpret the response (including the USD/UNI inverse), and outline how to request historical OHLC suitable for time series analytics.

What you will build and why it matters

Many fintech dashboards, quant research notebooks, and product pricing engines need both a current price and a historical, candle-ready series. We will:

Illustration: API to Get the Uniswap (UNI) Price: retrieving historical OHLC data
  • Fetch the current UNI price in a single request.
  • Understand the inversion provided in the response (USDUNI) to convert between USD/UNI and UNI/USD.
  • Outline how to retrieve historical OHLC candles for uni, and how to align them to your charting intervals.
  • Cover operational details that trip up first integrations: base currency, timestamps/timezone, caching, and weekend/closure handling.

If you do not have an API key yet, create one in minutes: Register. You can explore all available symbols any time at Symbols and full reference at Documentation.

Core endpoints to retrieve UNI price and candles

We will focus on two endpoints that cover the majority of charting and analytics use cases:

  • Latest Rates endpoint: get the current UNI price with an included inverse (USDUNI).
  • OHLC endpoint: retrieve open, high, low, and close for specific dates (suitable for daily candles and, where supported, intraday OHLC).

For longer spans of daily closes (e.g., to calculate returns or build indicators), you can also use the Time-series endpoint and synthesize OHLC from it if your application only needs daily closing prices. For endpoint parameters, constraints, and availability per plan, refer to the Documentation.

Get the current Uniswap (UNI) price

The Latest Rates endpoint returns a JSON object keyed by rates. By default, the base is USD, so rates.UNI is “UNI per 1 USD” and the API also returns the inverse as rates.USDUNI (“USD per 1 UNI”). This inversion is particularly convenient when your UI needs USD/UNI while your models use UNI/USD or vice versa.

Copy-paste curl request

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

Below is an official sample response for the UNI latest quote. Use these exact fields and invert as needed in your application.

{"success":true,"timestamp":1793405280,"date":"2026-10-31","base":"USD","rates":{"UNI":0.14050469285674,"USD":1,"USDUNI":7.1172000000000715}}

How to read these fields

  • success: Boolean indicating whether the request returned properly.
  • timestamp: Unix epoch seconds; treat as UTC. Use it to align your cache invalidation and candle bucketing.
  • date: Calendar date for the payload (UTC).
  • base: The reference unit. Here it is USD.
  • rates.UNI: UNI per 1 USD (UNI/USD). With the sample, 1 USD buys approximately 0.14050469285674 UNI.
  • rates.USD: Always 1 when base is USD.
  • rates.USDUNI: USD per 1 UNI (USD/UNI). With the sample, 1 UNI costs ~7.1172 USD.

Important: When base=USD, you get both directions for UNI in one payload: - UNI (UNI per 1 USD) - USDUNI (USD per 1 UNI) Choose the one your pricing engine or charts expect and keep it consistent throughout your stack.

JavaScript example to display USD/UNI and UNI/USD

async function fetchUniPrice() {
  const url = "https://metals-api.com/api/latest?access_key=YOUR_API_KEY&symbols=UNI";
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json();

  // Validate shape
  if (!data.success || !data.rates || typeof data.rates.UNI !== "number" || typeof data.rates.USDUNI !== "number") {
    throw new Error("Unexpected response");
  }

  // Base is USD:
  // - UNI = UNI per 1 USD (UNI/USD)
  // - USDUNI = USD per 1 UNI (USD/UNI)
  const uniPerUsd = data.rates.UNI;
  const usdPerUni = data.rates.USDUNI;

  // Timestamp is epoch seconds in UTC
  const ts = new Date(data.timestamp * 1000).toISOString();

  return {
    asOf: ts,
    uniPerUsd,    // e.g., 0.1405 UNI per USD
    usdPerUni     // e.g., 7.1172 USD per UNI
  };
}

fetchUniPrice()
  .then(console.log)
  .catch(console.error);

For server-side Python, the same logic applies. Cache the response for at least the update interval of your plan to avoid redundant calls. Always check success and handle temporary network errors with backoff.

Retrieve historical OHLC for UNI

For charting and backtesting, you often need candles (open, high, low, close) by date. Metals-API provides an OHLC endpoint that returns candle data keyed by symbol. A common daily-candle pattern is:

  • Endpoint path: open-high-low-close/YYYY-MM-DD
  • Base: USD (default)
  • Symbols: UNI

In practice, you would iterate over a date range and request each day’s OHLC if your plan supports that resolution and historical span. If you only need closing prices over a range, the Time-series endpoint can be sufficient, and you can compute derived fields (e.g., daily return) from closes only. Consult the Documentation for the precise parameters and limits for OHLC and time series.

Designing a historical pipeline

Here is a robust approach that scales from quick dashboards to production analytics:

  1. Pick your candle interval (daily is the most common). Use the OHLC endpoint for precise O/H/L/C per day.
  2. Normalize all timestamps to UTC and store them as ISO 8601 (e.g., 2026-10-31T00:00:00Z) or as midnight UTC boundaries for dailies.
  3. Store both USD/UNI and UNI/USD if your consumers are split (e.g., a retail UI prefers USD per UNI, while a quant model might prefer the inverse). With Metals-API, you will usually have both in Latest and can construct inverses consistently for historical data.
  4. Fill data gaps deterministically: if a particular day is missing OHLC (network retry windows, plan constraints), consider backfilling with an adjacent day or flag the gap. For crypto like UNI, trading is 24/7, but upstream aggregations can still result in calendar-day boundaries.
  5. Cache aggressively: store each day’s OHLC in your database or object storage. Rebuild derived indicators (e.g., SMA, RSI) from your local store rather than re-requesting raw candles repeatedly.

Notes on granularity and alignment

Daily OHLC is typically the fastest way to stand up a historical chart. If your application needs intraday resolution, check your plan’s support for intraday or finer OHLC availability. Align your candlestick open/close boundaries to UTC midnight so your computations are consistent across services and daylight saving changes.

Time-series for daily close backfills

When you only need daily closes (and not the full candle), the Time-series endpoint lets you request a date range with a daily rate for each date. This is ideal to backfill a simple historical price line, compute rolling returns, or initialize a chart that uses close-only markers.

For parameter details, date ranges, and supported symbols, see Documentation and confirm UNI availability in Symbols.

Practical integration guidance

Units and interpretation

  • Base currency: USD by default. With base=USD, rates.UNI means “UNI per 1 USD” (UNI/USD), and rates.USDUNI is “USD per 1 UNI” (USD/UNI).
  • Metals vs crypto: Metals-API commonly returns “per troy ounce” for metals. For UNI, you work in units of token per USD or USD per token. No weight units apply to crypto symbols.

Timestamps and timezone

  • timestamps are Unix epoch seconds; treat them as UTC.
  • For daily candles, bucket by UTC midnight boundaries to avoid cross-timezone shifts.

Caching and rate economy

  • Respect your plan’s update cadence. If updates are every X minutes, cache for at least X minutes before refreshing.
  • Batch historical requests. Persist daily OHLC locally so you don’t re-fetch the same day repeatedly.
  • Use ETag or timestamp checks in your data layer to bypass recomputation if nothing changed.

Weekend and market-closure handling

  • UNI trades 24/7, so you won’t see traditional “market closed” gaps like metals or equities. Even so, your daily buckets should still be UTC date-based for consistency.
  • If you’re blending UNI with metals or fiat currency rates in a multi-asset dashboard, be mindful that other assets can have non-trading days or thinner liquidity windows. Always align to a common calendar (UTC) and be explicit about carry-forward logic on days with no new ticks for those assets.

Validation and fallbacks

  • Always check success in responses and implement retry with exponential backoff on transient errors.
  • Set sanity bounds in your code. For example, if the previous day’s USD/UNI was ~7.1 and a sudden value is 710, trigger a manual review or a second-fetch confirmation.

Putting it together: from latest to candles

Below is a simple workflow you can adapt into a worker or cron:

  1. On startup, call the Time-series or a loop of OHLC endpoint calls to backfill the last N days of UNI candles. Store results keyed by date in UTC.
  2. On a fixed interval (aligned to your plan’s update cadence), call Latest to refresh the current price. Update any “in-progress” candle (e.g., today’s OHLC) as new highs/lows develop and close it at UTC midnight.
  3. When the day rolls, finalize the candle (open, high, low, close) for the prior UTC day and persist it. Start a new candle for the new UTC day with the first tick as both open and current high/low.

This approach yields consistent candles and keeps request volume predictable. For advanced streaming and event-driven updates, review the WebSocket capabilities in the Documentation.

Environment, deployment, and cost notes

  • Secrets: Keep your API key in an environment variable or your secret manager. Avoid hardcoding in clients shipped to end users.
  • Resilience: Deploy a small retry/backoff wrapper. Combine this with a short-lived in-memory cache to shield downstream services.
  • Cost planning: Choose a plan that matches your symbol coverage and frequency of updates. For reference, Copper Monthly is $19.99/mo. Confirm the capabilities you need (e.g., OHLC history, intraday, WebSocket) in the plan you select on MCP.

Troubleshooting common traps

  • Inversion confusion: Remember, with base=USD, rates.UNI is UNI per USD, and rates.USDUNI is USD per UNI. For UI labels, pick one and stick to it. For calculations, verify which direction your formulas assume.
  • Timezone mismatch: If your charting library assumes local midnight but your data is UTC midnight, candles will “shift.” Normalize to UTC everywhere and convert only for display if needed.
  • Partial days: Don’t finalize the current day’s candle until UTC midnight. During the day, track rolling high/low as new ticks arrive from Latest or WebSocket.
  • Schema drift: Guard your parser with checks for required fields (success, rates.UNI or rates.USDUNI, timestamp). Log anomalies for quick triage.

Reference and discovery

Keep these resources handy while you integrate:

FAQ

How do I get USD per UNI vs UNI per USD?
With base=USD, Metals-API returns both: rates.UNI (UNI per 1 USD) and rates.USDUNI (USD per 1 UNI). Use rates.USDUNI directly for “USD per UNI” displays and rates.UNI for models expecting UNI/USD.

What timezone should I use for candles?
Treat all timestamps as UTC. Bucket daily candles at UTC midnight for consistent OHLC, then convert to the user’s local time only in the presentation layer if desired.

How should I backfill historical data for a chart?
Use the OHLC endpoint to fetch daily candles by date. If you only require closing prices, the Time-series endpoint can backfill closes over a date range. Persist results locally and update incrementally to reduce calls.

How often should I refresh Latest?
Respect your plan’s update interval. Cache responses and schedule refreshes only when data can change. For streaming or lower-latency updates, consult the WebSocket option in the Documentation.

Is there a free trial?
Metals-API does not offer a free trial. Choose a plan that fits your data needs and update frequency. You can review and register here: Register.

Ready to ship? Create your API key, confirm UNI in the Symbols directory, and use the Latest plus OHLC endpoints to populate your UNI price widgets and historical charts. Start here: Register.