> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ngnmarket.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a Currency Converter

> Use live NGN exchange rates to build a bidirectional NGN currency calculator.

This guide shows how to fetch live NGN exchange rates and build a bidirectional currency converter — the same feature NGN Market uses on its forex page. Users can type an amount in NGN and see the equivalent in USD, GBP, EUR, and more, or convert the other way around.

**Endpoint used:**

* `GET /forex/current` (Free plan) — all current NGN rates in one call

## How the rates work

The API returns rates as **how much foreign currency one Naira buys**. For example:

```json theme={null}
{ "source_currency": "NGN", "target_currency": "USD", "rate": 0.000623 }
```

This means **₦1 = \$0.000623**, so to convert:

* **NGN → USD:** `amount_ngn × rate`
* **USD → NGN:** `amount_usd ÷ rate`

## Step 1: Fetch all rates

One call returns every supported currency pair.

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.ngnmarket.com/v1/forex/current \
    -H "Authorization: Bearer ngm_live_YOUR_KEY"
  ```

  ```javascript JavaScript theme={null}
  const API_KEY = 'ngm_live_YOUR_KEY';

  async function fetchRates() {
    const res = await fetch('https://api.ngnmarket.com/v1/forex/current', {
      headers: { Authorization: `Bearer ${API_KEY}` },
    });
    const { data } = await res.json();

    // Build a currency code → rate map
    return Object.fromEntries(data.rates.map(r => [r.target_currency, r.rate]));
  }
  ```

  ```python Python theme={null}
  import requests

  API_KEY = 'ngm_live_YOUR_KEY'

  def fetch_rates():
      res = requests.get(
          'https://api.ngnmarket.com/v1/forex/current',
          headers={'Authorization': f'Bearer {API_KEY}'},
      )
      rates = res.json()['data']['rates']
      return {r['target_currency']: r['rate'] for r in rates}
  ```
</CodeGroup>

### Sample response (trimmed)

```json theme={null}
{
  "success": true,
  "data": {
    "base_currency": "NGN",
    "last_updated": "2026-04-21",
    "rates": [
      { "source_currency": "NGN", "target_currency": "USD", "rate": 0.000623 },
      { "source_currency": "NGN", "target_currency": "GBP", "rate": 0.000491 },
      { "source_currency": "NGN", "target_currency": "EUR", "rate": 0.000574 },
      { "source_currency": "NGN", "target_currency": "CAD", "rate": 0.000856 },
      { "source_currency": "NGN", "target_currency": "CNY", "rate": 0.004512 },
      { "source_currency": "NGN", "target_currency": "AED", "rate": 0.002288 }
    ]
  }
}
```

## Step 2: Conversion logic

<CodeGroup>
  ```javascript JavaScript theme={null}
  function convert({ amount, from, to, rates }) {
    if (from === 'NGN') {
      // NGN → foreign
      return amount * rates[to];
    } else if (to === 'NGN') {
      // foreign → NGN
      return amount / rates[from];
    } else {
      // foreign → foreign (route through NGN)
      const inNgn = amount / rates[from];
      return inNgn * rates[to];
    }
  }

  // Examples
  const rates = await fetchRates();
  console.log(convert({ amount: 100000, from: 'NGN', to: 'USD', rates })); // ₦100,000 → USD
  console.log(convert({ amount: 500,    from: 'USD', to: 'NGN', rates })); // $500 → NGN
  console.log(convert({ amount: 200,    from: 'USD', to: 'GBP', rates })); // $200 → GBP
  ```

  ```python Python theme={null}
  def convert(amount, from_currency, to_currency, rates):
      if from_currency == 'NGN':
          return amount * rates[to_currency]
      elif to_currency == 'NGN':
          return amount / rates[from_currency]
      else:
          # route through NGN
          in_ngn = amount / rates[from_currency]
          return in_ngn * rates[to_currency]

  rates = fetch_rates()
  print(convert(100_000, 'NGN', 'USD', rates))  # ₦100,000 → USD
  print(convert(500,     'USD', 'NGN', rates))  # $500 → NGN
  print(convert(200,     'USD', 'GBP', rates))  # $200 → GBP
  ```
</CodeGroup>

## React component (bidirectional)

Typing in either input updates the other in real time.

```tsx React theme={null}
import { useEffect, useState } from 'react';

const API_KEY    = 'ngm_live_YOUR_KEY';
const CURRENCIES = ['USD', 'GBP', 'EUR', 'CAD', 'CNY', 'AED'];

async function fetchRates() {
  const res = await fetch('https://api.ngnmarket.com/v1/forex/current', {
    headers: { Authorization: `Bearer ${API_KEY}` },
  });
  const { data } = await res.json();
  return Object.fromEntries(data.rates.map(r => [r.target_currency, r.rate]));
}

export function CurrencyConverter() {
  const [rates,      setRates]     = useState({});
  const [currency,   setCurrency]  = useState('USD');
  const [ngnAmount,  setNgnAmount] = useState('');
  const [fxAmount,   setFxAmount]  = useState('');

  useEffect(() => { fetchRates().then(setRates); }, []);

  const rate = rates[currency];

  function handleNgnChange(val) {
    setNgnAmount(val);
    setFxAmount(rate && val ? (parseFloat(val) * rate).toFixed(4) : '');
  }

  function handleFxChange(val) {
    setFxAmount(val);
    setNgnAmount(rate && val ? (parseFloat(val) / rate).toFixed(2) : '');
  }

  return (
    <div>
      <label>
        NGN (₦)
        <input
          type="number"
          value={ngnAmount}
          onChange={e => handleNgnChange(e.target.value)}
          placeholder="0.00"
        />
      </label>

      <select value={currency} onChange={e => { setCurrency(e.target.value); setFxAmount(''); }}>
        {CURRENCIES.map(c => <option key={c} value={c}>{c}</option>)}
      </select>

      <label>
        {currency}
        <input
          type="number"
          value={fxAmount}
          onChange={e => handleFxChange(e.target.value)}
          placeholder="0.00"
        />
      </label>

      {rate && (
        <p>1 NGN = {rate.toFixed(6)} {currency}</p>
      )}
    </div>
  );
}
```

## Vanilla JavaScript (with a rate table)

Display all rates alongside the converter:

```javascript JavaScript theme={null}
const API_KEY    = 'ngm_live_YOUR_KEY';
const CURRENCIES = ['USD', 'GBP', 'EUR', 'CAD', 'CNY', 'AED'];

async function init() {
  const res    = await fetch('https://api.ngnmarket.com/v1/forex/current', {
    headers: { Authorization: `Bearer ${API_KEY}` },
  });
  const { data } = await res.json();
  const rates  = Object.fromEntries(data.rates.map(r => [r.target_currency, r.rate]));

  // Render rates table
  const tbody = document.querySelector('#rates-table tbody');
  data.rates.forEach(({ target_currency, rate }) => {
    const row = tbody.insertRow();
    row.innerHTML = `
      <td>${target_currency}</td>
      <td>${(1 / rate).toLocaleString(undefined, { maximumFractionDigits: 2 })}</td>
      <td>${rate.toFixed(6)}</td>
    `;
  });

  // Wire up converter inputs
  const ngnInput = document.getElementById('ngn-input');
  const fxInput  = document.getElementById('fx-input');
  const fxSelect = document.getElementById('fx-select');

  ngnInput.addEventListener('input', () => {
    const rate = rates[fxSelect.value];
    fxInput.value = rate ? (parseFloat(ngnInput.value) * rate).toFixed(4) : '';
  });

  fxInput.addEventListener('input', () => {
    const rate = rates[fxSelect.value];
    ngnInput.value = rate ? (parseFloat(fxInput.value) / rate).toFixed(2) : '';
  });
}

init();
```

## Tips

**Cache rates for the session.** Forex rates update daily, so one fetch per page load is sufficient. No need to poll on an interval like equity prices.

**Always show `last_updated`.** The response includes a `last_updated` date. Display it near your rates so users know how fresh the data is.

**Cross-pair conversion routes through NGN.** All rates are NGN-based, so to convert USD → GBP you divide by the USD rate to get NGN, then multiply by the GBP rate. The `convert()` function above handles this automatically.

<CardGroup cols={2}>
  <Card title="Forex current reference" icon="book" href="/api-reference/forex/current">
    Full response spec for `GET /forex/current`
  </Card>

  <Card title="Forex history reference" icon="book" href="/api-reference/forex/history">
    Historical NGN rates with date range filtering
  </Card>
</CardGroup>
