DEV Community

Exchange Rate API
Exchange Rate API

Posted on

How Far Is Your Bank From the Mid-Market Rate? A 30-Line Node Script

The rate you see on Google is a mid-market rate. The rate your bank gives you is not. This script shows the gap for every covered bank in a country, using one API.

The data

AllRatesToday serves both sides:

  • a mid-market rate for 160+ currencies, refreshed every 60 seconds
  • buy and sell boards from 1,219 commercial banks in 124 countries, read every hour from the banks' own websites

The script

// node markup.mjs in USD
const KEY = process.env.ALLRATES_KEY;
const [country = "in", ccy = "USD"] = process.argv.slice(2);
const H = { Authorization: `Bearer ${KEY}` };
const get = (p) => fetch(`https://allratestoday.com${p}`, { headers: H }).then((r) => r.json());

const country_ = await get(`/api/v1/bank-rates/${country}`);
const local = country_.quote_ccy;                      // e.g. INR
const mid = await get(`/api/v1/rates?source=${ccy}&target=${local}`);
const midRate = mid[0].rate;                            // always an array

const rows = country_.banks
  .flatMap((b) => b.rates.filter((r) => r.ccy === ccy && r.sell).map((r) => ({ bank: b.name, ...r })))
  .map((r) => ({
    bank: r.bank,
    buy: r.buy,
    sell: r.sell,
    sell_vs_mid_pct: +(((r.sell - midRate) / midRate) * 100).toFixed(2),
  }))
  .sort((a, b) => a.sell_vs_mid_pct - b.sell_vs_mid_pct);

console.log(`${ccy}/${local} mid-market: ${midRate}`);
console.table(rows);
Enter fullscreen mode Exit fullscreen mode

What you get

A table of every covered bank in the country, sorted from the closest to the mid-market rate to the furthest. Each bank row also has the central bank's official rate for the same currency and vs_official_pct, so you can compare against the official rate as well as the market.

Ideas for using it

  • A "cheapest bank today" page for a country
  • An alert when your own bank's spread widens past a threshold
  • A treasury check on what your banking partners charge you

Links

Top comments (0)