whitebear
← exchange-rates-uy

v1.8.2 · MIT · la documentación está en inglés

exchange-rates-uy v1 Docs

npm install exchange-rates-uyv1.8.2

Uruguay's exchange rates, on your own backend. The official rate (Banco Central del Uruguay: buying and selling, every working day) and the market rate (ExchangeRate-API: every currency, every day; its past back to March 2024 from the archive this package ships), any pair between the currencies you choose, read on the schedule you choose, served by an API, a public page with a converter, and a panel to add currencies and pairs.

Demo: rates.whitebear.io, Whitebear's rates tool, running on this package.

npx exchange-rates-uy serve
# → http://localhost:8787 with the page, http://localhost:8787/api/pairs with the rates

No API keys and no accounts: both sources are free and open. It brings no database and no host of its own: it runs on the ones you already have.

Database Adapter
SQLite (a file: node:sqlite, better-sqlite3, bun:sqlite) exchange-rates-uy/sqlite
Postgres (Supabase, Neon, Vercel Postgres, RDS, Aurora, local, PGlite) exchange-rates-uy/postgres
Cloudflare D1 exchange-rates-uy/d1
Platform How
Any server (Node 22.13+), Docker exchange-rates-uy/node, npx exchange-rates-uy serve, the Dockerfile
Cloudflare Workers exchange-rates-uy/worker
AWS Lambda exchange-rates-uy/lambda
Vercel, Netlify, Deno, Bun, Supabase Edge Functions createExchangeRates(…).fetch is a plain Request → Response

Why two sources

They answer two questions. The official rate is what an invoice, a tax return or any figure that has to agree with somebody outside is read against: the BCU publishes it once a working day, buying and selling, and nothing on a bank holiday. The market rate is what the rest of the world uses while the official one holds all day: one number for every currency, every day.

Neither replaces the other, and they are never averaged: an average of an official rate and a market one is a figure that is true nowhere.

What it does

  • Reads both sources on a schedule: the BCU at 10, 14 and 18 in Montevideo on working days and the market at 10 and 18 by default, or whatever you set. Each slot is claimed in the database before it is read, so restarts, several instances or a late trigger never read twice, and a slot missed while the server was down is read on its next tick.
  • Keeps what the sources said, as they said it: the bank's reading of each currency per day (with the dollar arbitrage it publishes) and the market's table per day: whole (about 160 currencies) for the newest week, and before that only for the currencies of your pairs (pastCurrencies), since the package's archive has every other.
  • Answers any pair. Official: what the bank published directly where it did, else a division through the peso with both spreads compounded, which is what going through it costs. Market: one column over another. A pair is computed when asked, so one added today has its history at once (a market pair with a currency new to your pairs, once the ticks have kept its past: a few days).
  • Serves an API anybody may read from any origin, a public page with the pairs and a converter, and a panel to add currencies and pairs, retire, star and order them, read now, and load the bank's history back to 2018 or earlier.
  • Writes rates the way people read them: four digits that mean something (40.08, 0.0256, 1592), and money with its code, because $ alone says nothing.

Quick start

On any server, with Node

ADMIN_TOKEN=a-long-secret npx exchange-rates-uy serve --port 8787 --database ./rates.db

The page is /, the API /api, the panel /admin (with ADMIN_TOKEN). The environment sets the rest: RATES_CURRENCIES=USD,UYU,EUR, RATES_PAIRS=USD/UYU,EUR/UYU, RATES_OFFICIAL_HOURS=10,14,18, RATES_MARKET_HOURS=10,18, RATES_TIMEZONE, RATES_TITLE, RATES_LANG=es|en, CRON_SECRET.

In code, on SQLite or on Postgres (examples/node):

import { serve } from "exchange-rates-uy/node";
await serve({ port: 8787, database: "./rates.db", adminToken: process.env.ADMIN_TOKEN });

// or on Postgres
import pg from "pg";
import { pgSql } from "exchange-rates-uy/postgres";
await serve({ sql: pgSql(new pg.Pool({ connectionString: process.env.DATABASE_URL })) });

In Docker

docker build -t exchange-rates-uy .
docker run -p 8787:8787 -v rates:/data -e ADMIN_TOKEN=a-long-secret exchange-rates-uy

On Cloudflare Workers

npm install exchange-rates-uy
npx wrangler d1 create exchange-rates
// src/index.ts
import { exchangeRatesWorker } from "exchange-rates-uy/worker";
export default exchangeRatesWorker();
# wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "exchange-rates"
database_id = "…"          # from `wrangler d1 create`

[triggers]
crons = ["*/15 * * * *"]   # only wakes it: the schedule decides what is read
npx wrangler secret put ADMIN_TOKEN
npx wrangler deploy

See examples/cloudflare, and Rate limits before it is public.

On Supabase

An Edge Function on your project's own Postgres, the tables beside yours (rates_official, rates_pair…), so your SQL can join them. pg_cron calls its /api/tick. See examples/supabase.

import postgres from "npm:postgres";
import { createExchangeRates } from "npm:exchange-rates-uy/server";
import { postgresJsSql } from "npm:exchange-rates-uy/postgres";

const rates = createExchangeRates({
  sql: postgresJsSql(postgres(Deno.env.get("SUPABASE_DB_URL")!, { prepare: false })),
  apiBase: "/rates/api",
  cronSecret: Deno.env.get("RATES_CRON_SECRET"),
});
Deno.serve((req) => rates.fetch(req));

On Vercel

A Function on Postgres (Neon from the Marketplace), with Vercel Cron calling /api/tick: Vercel sends Authorization: Bearer $CRON_SECRET, which is what cronSecret checks. See examples/vercel.

On AWS Lambda

A Function URL or an HTTP API for the requests, and an EventBridge rule every 15 minutes invoking the same function for the clock. See examples/aws-lambda.

import pg from "pg";
import { lambdaHandler } from "exchange-rates-uy/lambda";
import { pgSql } from "exchange-rates-uy/postgres";
export const handler = lambdaHandler({ sql: pgSql(new pg.Pool({ connectionString: process.env.DATABASE_URL })) });

Anywhere else

createExchangeRates({ sql }) from exchange-rates-uy/server gives fetch(request) and tick(now). Hand fetch to whatever serves requests (Bun's Bun.serve, Deno's Deno.serve, Hono, a Next.js route handler) and call tick from whatever keeps time (a timer, a cron, or a request to /api/tick with the cron secret). A database is three functions (src/server/sql.ts), so another one is a few lines.

Pairs and currencies

A currency is its ISO code and nothing else: its name in each language, its mark and its decimals come from the platform (Intl). If the BCU quotes it (34 currencies, from the dollar to the Peruvian sol), it joins the official reading the moment it is kept; the market has all of them anyway.

A pair is two kept currencies, BASE/QUOTE: one BASE buys this many QUOTE. USD/UYU is pesos per dollar, EUR/USD dollars per euro, USD/ARS Argentine pesos per dollar through the Uruguayan peso.

Three ways to choose them:

  • The seed, the first ones of a new database: seed: { currencies: ["USD", "UYU", "EUR"], pairs: ["USD/UYU", "EUR/UYU"] }, or RATES_CURRENCIES and RATES_PAIRS.
  • The panel: add, retire, star, order, reverse.
  • The admin API, which is what the panel calls.

The schedule

schedule: {
  timeZone: "America/Montevideo",                                        // the hours below are this zone's
  official: { hours: [10, 14, 18], weekdays: [1, 2, 3, 4, 5] },          // the BCU publishes on working days
  market:   { hours: [10, 18],     weekdays: [0, 1, 2, 3, 4, 5, 6] },    // its table is rebuilt once a day
}

Any hours and any days. Whatever runs it only has to call tick often enough (every 15 minutes is plenty): the Worker's Cron Trigger, the Node server's own timer, a scheduled Lambda, pg_cron, Vercel Cron.

The API

GET, open to any origin unless access says otherwise, cached five minutes. date=YYYY-MM-DD reads another day: the last reading on or before it. Days are Montevideo's.

Endpoint What
/api/pairs The kept pairs, each with its official rate (buy, sell, day) and its market rate (rate, day).
/api/pairs/USD-UYU/history?from=&to=&source=official|market One pair, day by day (up to ten years per call).
/api/convert?amount=100&from=USD&to=UYU&source=official|market&side=buy|sell|mid An amount in another currency.
/api/official The bank's reading: each currency in pesos (perLocal) and what it published against the dollar (published).
/api/market The market's table: how many of each currency buy one dollar (perUsd), whose it is (source: live or past) and its credit. ?date= back to 2024-03-02.
/api/currencies?lang=es The kept currencies: name, mark, decimals, whether the BCU quotes them.
/api/status The newest day of each source and the last readings.
GET /api/pairs
{
  "date": "2026-11-25",
  "pairs": [
    { "pair": "USD/UYU", "base": "USD", "quote": "UYU", "favourite": true,
      "official": { "day": "2026-11-24", "buy": 40.697, "sell": 40.697 },
      "market": { "day": "2026-11-24", "rate": 40.532 } }
  ]
}

Two more, behind a secret:

  • POST /api/tick (or GET), with Authorization: Bearer <cronSecret or adminToken>: reads whatever is due.
  • GET/POST /api/admin, with Authorization: Bearer <adminToken> (or your authorize): the panel's. The actions are currency, pair, reverse, order, read and backfill (src/server/api.ts).

A public request only reads the database, whatever day it asks for: what is kept is written by the ticks and the admin API (and the tables by the first request, which creates and migrates them).

Rate limits

The package limits nobody: in front of a public deployment, put a rate-limit rule on /api/* per IP (Cloudflare's rate limiting rules or the Workers Rate Limiting binding, your load balancer's, your proxy's). A pair's history is answered from memory (each currency's days read once per instance, and again when a newer day is kept or ten minutes on; once its index is built, see Upgrading), but every other answer is read from your database, and a host that caps or bills the rows read per day (D1, for one) is spent by whoever asks most. Behind access the answers are private, so no shared cache takes that load.

The panel

At /admin, on with an adminToken (or an authorize function). Add a currency by searching its code, name or country; add a pair from two kept ones; retire, star, reverse and order pairs; set a currency's own mark (US$ beside the peso's $); read now; load the BCU's history from any day. It asks for the token once per tab, or opens straight away when authorize lets the request in (your own session cookie, an access proxy), so the panel can sit behind your own sign-in.

Options

createExchangeRates({                 // exchangeRatesWorker({…}), serve({…}) and lambdaHandler({…}) take the same
  sql,                                // the database (not for the Worker: it is env.DB)
  tablePrefix: "rates_",              // the tables' prefix
  apiBase: "/api",                    // where the API answers
  adminToken: "…",                    // the panel and the admin API (the Worker reads env.ADMIN_TOKEN)
  authorize: (req) => …,              // instead of the token: any check on the request
  cronSecret: "…",                    // the bearer a scheduler sends to /api/tick
  schedule: { … },                    // see above
  pastMarketPerTick: 2,               // past market days each tick keeps (0: none)
  pastCurrencies: ["EUR", …],         // whose market past is kept (every pair's by default; the dollar and the peso always)
  seed: { currencies: [...], pairs: [...] },
  page: { title, tagline, footer, lang: "es" },
  publicPage: true,                   // false: the API only
  maxAge: 300,                        // the public API's cache, in seconds
  observe: (e) => …,                  // each API request: route, status, ms, origin, referer, user agent
  access: { origins: [...], keys: [...] }, // who may read the API (open to everybody without it)
});

Who may read the API

Open to everybody by default. With access, only:

  • the web origins listed ("https://app.example.com"), whose pages call it from a browser (CORS answers them and nobody else);
  • the server's own page, always;
  • a server-side caller with one of the keys, as Authorization: Bearer <key> or X-Api-Key: <key> (a server has no origin to check).

What a browser says about where a call comes from stops other web pages from using your API; a script can write those headers itself, so the keys are what really close it. Behind access the answers are private for caches, so no shared cache hands one caller's answer to another.

observe is how you count usage, log or send metrics: it is told of each API request once it is answered ({ at, route, method, status, ms, origin, referer, userAgent }, the route without values: pairs/history, not pairs/USD-UYU/history) and the answer never waits for it. On a Worker it keeps running after the answer through ctx.waitUntil. It is told of refused requests too (any 4xx: a bad date, a wrong key, an unknown path), and anybody can send those: count in memory or in a metrics service rather than with a database row per request.

Connect an app

One package, three clients, all in this repository, with the same calls and names (official, market, pairs, currencies, history, convert) and two ways to answer them:

  • With a server: give the client its address. It asks your exchange-rates-uy server, which keeps the history, the pairs you chose and the market's past days.
  • Without one: give it nothing, or the pairs you want. It reads the BCU and the market itself, with the same arithmetic the server uses, and a market's past day from the package's archive (below). Nothing to deploy. What it cannot do alone: the market's days after the newest release's archive (a server keeps them), and the BCU from a web page (the bank lets no other site call it; on a phone, a server or a script it is fine).
Platform Install from this repository
JavaScript and TypeScript (Deno, Node, Workers, Supabase Edge Functions, browsers) npm: exchange-rates-uy/client
iOS, macOS (Swift, async/await) Swift Package Manager: https://github.com/guillecura/exchange-rates-uy
Android, JVM (Kotlin, coroutines) JitPack: com.github.guillecura:exchange-rates-uy:<tag>

JavaScript

import { createRatesClient } from "exchange-rates-uy/client";

const rates = createRatesClient({ baseUrl: "https://your-server/api", key: process.env.RATES_API_KEY }); // with a server
const alone = createRatesClient({ pairs: ["USD/UYU", "EUR/UYU"] });                                     // without one

const bank = await rates.official();                       // the BCU's pesos per unit, buying and selling
const market = await rates.market();                       // every currency per dollar
const usd = await rates.history("USD/UYU", { from: "2026-01-01" });
await rates.convert({ amount: 100, from: "USD", to: "UYU", source: "official" });

In Deno without npm: https://raw.githubusercontent.com/guillecura/exchange-rates-uy/<tag>/src/client.ts.

Swift (iOS 15, macOS 12; in Xcode, File › Add Package Dependencies… with this repository's URL)

import ExchangeRatesUY

let rates = RatesClient(baseURL: URL(string: "https://your-server/api")!, key: "…")   // with a server
let alone = RatesClient(pairs: ["USD/UYU", "EUR/UYU"])                                // without one

let bank = try await rates.official()                      // bank.perLocal["USD"]: Spread(buy:sell:)
let market = try await rates.market()                      // market.perLocal()["EUR"]: pesos per euro
let usd = try await rates.history("USD/UYU", from: "2026-01-01")

Kotlin (Android needs android.permission.INTERNET)

// settings.gradle.kts: repositories { maven("https://jitpack.io") }
// build.gradle.kts:    implementation("com.github.guillecura:exchange-rates-uy:v1.8.2")
import uy.exchangerates.RatesClient

val rates = RatesClient("https://your-server/api", key = "…")           // with a server
val alone = RatesClient.direct(listOf("USD/UYU", "EUR/UYU"))           // without one

val bank = rates.official()                                // suspends, on Dispatchers.IO
val usd = rates.history("USD/UYU", from = "2026-01-01")

A refused call fails with the status and the server's own words (RatesError, RatesError, RatesException). A key belongs on a server: in a phone app it can be read out of the binary, so there it only says which app is asking; give each app its own. Showing the market's figures? Keep its credit beside them: market.credit carries the one its source asks for.

The library

Without a server: the same sources and arithmetic, to use inside an app of your own.

import { latestBcu, bcuCode, marketTable, officialCross, marketCross } from "exchange-rates-uy";
import { money, rate, currencyName } from "exchange-rates-uy/money";

const bank = await latestBcu([{ iso: "USD", bcu: bcuCode("USD") }]);
officialCross(bank!.perLocal, bank!.published, "USD", "UYU");  // { buy, sell }

const market = await marketTable();
marketCross(market!.perUsd, "EUR", "JPY");                        // yen per euro

rate(40.0784, "es");             // "40,08"
money(1234.5, "UYU", "es-UY");   // "UYU 1.234,50"
currencyName("UYU", "es");       // "peso uruguayo"

How it keeps the rates

Seven tables, prefixed (rates_ by default), created and migrated by the server on its first request:

Table What
currency, pair What you chose: the kept currencies (and their own marks), the pairs (order, starred, active).
official The bank's reading: one row per day and currency, buying and selling in pesos, and its published dollar arbitrage.
market The market's table: one row per day and currency, units per dollar. Every currency for the newest week; before that, pastCurrencies' (below).
slot Which slot of each day was read, so none is read twice.
log Each reading and how it went (90 days).
meta How far the schema has migrated, how far back the ticks have kept the market's past and for which currencies, the past days they could not keep yet, how far old whole tables have been cut down, and whether the indexes by currency and day are built.

Retiring a currency or a pair only hides it: the readings stay, and bringing it back brings its history back (a retired pair's currencies stay in the default pastCurrencies).

A pair's history is answered from memory once the source's index by currency and day is built (below): each currency's days are read from the earliest day asked for on (that currency's rows and nothing else), any pair and range within them comes from there, and an earlier day asked for reads only the days missing. A range that ends long before the newest day (more than a month, and more than its own length) reads only its own days of a currency not in memory from its first day, and keeps nothing; the same currency asked that way again within ten minutes is read from that day on and kept, so repeats come from memory. An instance reads them again when the source keeps a newer day (it looks once a minute), ten minutes after it read them, or when a tick of its own kept or cut something, so however many history requests arrive, what the database is asked grows with the days asked for, not with the requests. Until the index is built, each history request reads its range by day, as it always did.

Upgrading

An upgrade migrates on its first request. From 1.7.1 there is nothing to migrate, so that request writes nothing.

market and official get an index by currency and day, so a pair's history reads its two currencies and not every currency of every day (on D1, a year of USD/UYU went from 58,560 rows read to 367). Building one writes an entry per row already kept, and D1's free plan allows 100,000 rows written a day, so it is not a migration: the ticks build each once its table has at most 25,000 rows (counted at most once per newest day; meta says when it is built), the market's once its old whole tables are cut down (below). An index already there is only written down. Until then a history reads its range by day, as before; a bank table kept for many currencies since 2018 may never be that small (every one the bank quotes, 34, is about 79,000 rows), and then reads by day for good, a few dozen rows a day asked.

The market's past is kept only for pastCurrencies (every pair's, the dollar and the peso). A database from before has every currency of every day it kept: the ticks cut those tables down, a day per tick, oldest first from 2 March 2024 (no archive has a day before it, so one stays whole), and only a day the archive of the version running has itself. A day it lacks stays whole: for good when it is a gap in the archive, and until an upgrade when it comes after the archive's last day, so it keeps answering its own rates. Until a day is cut, it answers as before; after, a currency it no longer keeps is answered from the archive, on that very day. A pair's market history with a currency outside pastCurrencies keeps only the days still whole. Adding such a pair later (or the currency to pastCurrencies) has the ticks keep its past again, starting from the newest day.

Measured on a local D1, from a 1.7.1 database (160,800 market rows, 11,630 of the bank's since 2018) at a 15-minute cron:

Day Rows written Of which
The first about 27,000 11,631 the bank's index, 14,784 the 96 days cut (154 rows deleted each)
Each while cutting (about ten) about 15,500 14,784 the days cut
The one it ends about 15,000 8,549 the market's index
After about 700 the readings

With an AI agent

The package ships a Claude Code skill: when to use which import, the wizards, and the rules that keep keys out of code. Copy it into the project and Claude reads it when the task calls for it:

mkdir -p .claude/skills && cp -r node_modules/exchange-rates-uy/skills/exchange-rates-uy .claude/skills/

Other agents can read the same file, or this README at node_modules/exchange-rates-uy/README.md.

Develop

npm install
npm test                              # the server on SQLite and on Postgres (PGlite), and the JS client
npm run typecheck
npm run build
swift test                            # the Swift client
cd clients/kotlin && ./gradlew test   # the Kotlin client (JDK 17)

A release is one number. npm version minor (or patch) bumps package.json, and its version script (scripts/version.ts) writes the new one everywhere else it is kept: src/version.ts, the Swift and Kotlin clients' Version files, build.gradle.kts, Package.swift and this README. The server and every client read the market's archive at their own version, so the npm publish and the tag v<version> must carry it; npm test fails when a copy disagrees with package.json.

npm takes the package only from the archive's workflow (trusted publishing), which releases in three ways:

  • Every month, on its own: it adds the new days and publishes a patch, and nothing when no day was added.
  • Run by hand (Actions → Archive → Run workflow), with bump patch or minor: it adds whatever days there are, bumps, commits, tags and publishes, even when no day was added.
  • A tag pushed: npm version minor && git push --follow-tags pushes the commit and its tag v<version>, and the workflow publishes that tag when package.json says the same version and npm does not have it yet.

The market's past

ExchangeRate-API's free table is only today's, so the package ships its own archive: data/market/YYYY-MM.json, every ISO 4217 currency against the dollar once a day since 2 March 2024, public-domain reference rates (CC0) within about one percent of ExchangeRate-API's. It grows every month (npm run archive, run by a workflow that publishes the package when a month was added), and it is free to use as it is:

const nov = await fetch("https://cdn.jsdelivr.net/npm/exchange-rates-uy@1/data/market/2026-11.json").then((r) => r.json());
nov.days["2026-11-20"].UYU;   // pesos per dollar that day

Every client and server reads a past day from there at the version it runs (exchange-rates-uy@<version> on jsDelivr, or the repository's tag v<version> when jsDelivr fails), a month a request, kept in memory; nothing else is asked for the past. A server never reads a newer copy, since what it keeps it keeps for good. A client without a server keeps nothing, so for a day its version's archive does not have (a month after it, or the rest of a month the release was cut in) it reads the newest release's copy of that month (@1, or the repository's main). A day's table is taken only whole and plausible (the peso in it, every figure a finite number above zero); one that is not counts as missing. ExchangeRate-API's daily tables, which a server keeps, are not in the archive: its terms let you keep them, not publish them.

A day before the server started reading the market, or one a reading missed, comes from the archive:

  • A day asked for (/api/market?date=, convert, pairs) is answered from the archive at once, and not kept: a reader's request writes nothing.
  • The ticks keep the past, newest first, pastMarketPerTick days each (2 by default; 0 turns it off), so a pair's market history (source=market) reaches back to March 2024 within a week, with each day's source (live when every figure it was worked out from is ExchangeRate-API's).
  • Only for pastCurrencies: each past day keeps the currencies of your pairs (retired ones too), the dollar and the peso, about five rows instead of 160, which is what keeps a free database's daily writes low (on D1, a past day kept costs about 15 rows written instead of 480: at the defaults and a 15-minute cron, about 3,000 a day for five days, then nothing). Today's table and the newest week's stay whole, for the converter; an older whole table is cut down to pastCurrencies, a day per tick, once the archive of the version running has that very day (until then it stays whole, so every currency still converts there with its own rate; a day after the archive's last waits for an upgrade). Any other currency on a past day (/api/market?date=, convert, pairs) is answered from the archive, never kept, so a day kept for a few currencies turns none away. A currency that joins them (a pair added) has the ticks start again from the newest day, adding its rows to the days already kept.
  • A day the ticks could not keep is listed (in meta) and asked for again: one whose archive could not be read, on the next ticks (pastMarketPerTick of them each); one the archive of the version running lacks, after an upgrade, which also looks again for every day since the ticks began that is not kept, a day a reading of the market missed among them. A day kept leaves the list.
  • A day the archive lacks answers the last one before it (within a week), with its own day. A day before 2024-03-02 has no market table: ask for the official rate there.

Credits

This package only reads the sources; it holds no licence for them. Whoever runs it, a server or an app in direct mode, reads Banco Central del Uruguay and ExchangeRate-API on their own behalf and answers for following their terms (ExchangeRate-API's include the credit below and not republishing its tables).

  • Official rates: Banco Central del Uruguay.
  • Market rates: Rates By Exchange Rate API. Their free tier asks for this credit beside their figures, and the public page shows it: keep it if you build your own.
  • The market's past days: this package's archive, public domain (CC0); a past day's credit points here.

Made by Guille Cura. It keeps the rates for Whitebear's products (rates.whitebear.io) and for Umino.

License

MIT

whitebear