Developer

Language: English
Appearance

Theme

Accent colour

Your theme and colour carry over to satelit.md and the app.

Sign in

Where should the theme change?

Choose where the new theme applies.

You can change it any time from the header.

Cookbook · Node.js 18+

BNM exchange rate widget

An HTML block with the National Bank of Moldova's official rates, the 30-day change and a small line for each currency. Static: no request from the reader's browser, no key in the page.

Runs on
Node.js 18+
One run
4 credits
A month
88 credits
Set up in
5 min
$ CODES=EUR,USD,RON DAYS=30 node rates_widget.mjsrates-widget.html: 3 currencies, 4 credits

How it works

  1. Get the day's rates from /v1/rates and keep the currencies in CODES.
  2. For each currency get DAYS days of history from /v1/rates/history.
  3. Draw the line as SVG in the page, with no chart library.
  4. Write rates-widget.html and rates.json, with BNM as the source under the numbers, as CC BY 4.0 asks.

What it costs: 1 credit for the rates, 1 for each history: 4 credits with three currencies. One run every working day: 88 credits a month. Fits in the Start plan.

How to run it

bash
export SATELIT_KEY=sat_live_...
CODES=EUR,USD,RON DAYS=30 node rates_widget.mjs

What it outputs

stdout
rates-widget.html: 3 currencies, 4 credits

The full script

rates_widget.mjs
#!/usr/bin/env node
// Exchange rate widget: BNM's official rates with a 30-day line, as one HTML block for any site.
//   SATELIT_KEY=sat_live_... node rates_widget.mjs
// Optional: CODES (EUR,USD,RON), DAYS (30), OUT (rates-widget.html), WIDGET_LANG (ro).
// Writes the block and rates.json. No dependencies, Node 18 or newer, no script runs in the reader's browser.
// Put it in cron after BNM publishes: 15 13 * * 1-5 node /path/rates_widget.mjs
import { writeFileSync } from "node:fs";

const BASE = process.env.SATELIT_BASE ?? "https://api.satelit.md/v1";
const KEY = process.env.SATELIT_KEY;
const LANG = process.env.WIDGET_LANG ?? "ro";
const CODES = (process.env.CODES ?? "EUR,USD,RON").split(",").map((c) => c.trim().toUpperCase());
const DAYS = Number(process.env.DAYS ?? 30);
const OUT = process.env.OUT ?? "rates-widget.html";
if (!KEY) throw new Error("Set SATELIT_KEY");

const WORDS = {
  ro: { title: "Cursul oficial BNM", days: "zile" },
  ru: { title: "Официальный курс НБМ", days: "дней" },
  en: { title: "Official BNM rates", days: "days" },
  uk: { title: "Офіційний курс НБМ", days: "днів" },
};
const w = WORDS[LANG];
let credits = 0;

async function api(path, params = {}) {
  const url = new URL(BASE + path);
  for (const [k, v] of Object.entries({ lang: LANG, ...params })) url.searchParams.set(k, v);
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(url, { headers: { Authorization: `Bearer ${KEY}` } });
    const retry = Number(res.headers.get("retry-after"));
    if ((res.status === 429 || res.status === 503) && retry && attempt < 2) {
      await new Promise((ok) => setTimeout(ok, retry * 1000));
      continue;
    }
    const body = await res.json();
    if (!res.ok) throw new Error(`${path}: ${body.error.code}: ${body.error.message}`);
    credits += body.meta.credits ?? 0;
    return body;
  }
}

const today = await api("/rates");
const rows = today.data.filter((r) => CODES.includes(r.code));
const history = await Promise.all(rows.map((r) => api("/rates/history", { code: r.code, days: DAYS })));

// a line of the last DAYS days, drawn as an inline SVG: no chart library, no request from the reader's page
function spark(points, width = 96, height = 28) {
  const v = points.map((p) => p.value);
  const min = Math.min(...v), max = Math.max(...v), span = max - min || 1;
  const xy = v.map((y, i) => `${((i / Math.max(v.length - 1, 1)) * width).toFixed(1)},${(height - 2 - ((y - min) / span) * (height - 4)).toFixed(1)}`);
  return `<svg viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" aria-hidden="true"><polyline fill="none" stroke="currentColor" stroke-width="1.5" points="${xy.join(" ")}"/></svg>`;
}
const sign = (n) => (n > 0 ? `+${n}` : `${n}`);
const items = rows.map((r, i) => `  <li><b>${r.code}</b> <span class="v">${r.value.toFixed(4)}</span> <span class="c ${r.change_30d_pct >= 0 ? "up" : "down"}">${sign(r.change_30d_pct)}% / ${DAYS} ${w.days}</span> ${spark(history[i].data.points)}</li>`);

// BNM's licence (CC BY 4.0) asks for the source next to the numbers: the attribution line comes from the answer
const html = `<section class="satelit-rates" lang="${LANG}">
  <h3>${w.title}, ${rows[0]?.date ?? ""}</h3>
  <ul>
${items.join("\n")}
  </ul>
  <p class="src">${today.meta.attribution}</p>
</section>
<style>
.satelit-rates{font:14px/1.4 system-ui,sans-serif}.satelit-rates ul{list-style:none;margin:0;padding:0}
.satelit-rates li{display:flex;gap:.6em;align-items:center;padding:.3em 0}.satelit-rates .v{font-variant-numeric:tabular-nums}
.satelit-rates .up{color:#b42318}.satelit-rates .down{color:#067647}.satelit-rates .src{font-size:12px;opacity:.7}
</style>
`;
writeFileSync(OUT, html);
writeFileSync("rates.json", JSON.stringify({ date: rows[0]?.date, rates: rows, attribution: today.meta.attribution }, null, 2));
console.log(`${OUT}: ${rows.length} currencies, ${credits} credits`);

Routes used

Data in this cookbook

Updated:

Questions about this cookbook

Why not call the API straight from the page?

The key would reach the browser of everyone who opens the page. The script runs on your server once a day and writes a static file: the key stays with you and the page loads with no extra requests.

When does BNM publish the rates?

BNM sets the official rates every working day. The cookbook's cron runs at 13:15, Monday to Friday; the answer's date field says which day the rates are for.

Can I use BNM's data on a commercial site?

BNM's data is under CC BY 4.0: you may use it with the source named. The widget puts the line from meta.attribution under the numbers. The same data is free at bnm.md.