Chinese Renminbi Yuan (CNY) Convert API integration guide for server-side applications
You need to convert amounts between USD and Chinese Renminbi Yuan (CNY) on the server to power portfolio valuation, settlement files, risk dashboards, or nightly backfills. By the end of this guide you will: fetch the latest USD↔CNY rates, run server-side conversions with the Convert endpoint, and understand how to cache and schedule updates correctly for production.
What you will build: a reliable USD↔CNY conversion service
This guide focuses on two endpoints you’ll actually ship with:
- Latest: fetch up-to-date USD→CNY and derived USDCNY cross.
- Convert: convert any amount from CNY→USD or USD→CNY on your server.
We’ll also cover optional Time-series for backfills and sanity checks, plus the mechanics that trip teams up (base currency, timestamps, weekends, and caching). If you need additional endpoints beyond these, refer to the Documentation.
Symbols and quoting: how to read CNY in API responses
Indices-API returns exchange rates relative to a base currency. By default the base is USD, and you’ll see:
- rates.CNY: how many CNY for 1 USD (USD→CNY).
- rates.USDCNY: the reciprocal cross used in some client libraries; use what your codebase expects.
- rates.USD: the identity value (1), since base=USD.
Confirm symbols in the catalog before hardcoding them in your app. See the canonical list at Symbols.
Server call 1: fetch the latest CNY quotes (base=USD)
Use the Latest endpoint to drive real-time conversions and cache short-lived quotes. Depending on your plan, updates are available every 60 minutes, every 10 minutes, or faster. Production services typically pull at the plan’s update cadence and cache responses server-side to shield dependent services.
curl: latest CNY with USD base
curl -s "https://indices-api.com/api/latest?access_key=YOUR_API_KEY&symbols=USD,CNY,USDCNY"
Official JSON response
{"data":{"success":true,"timestamp":1792629720,"date":"2026-10-22","base":"USD","rates":{"CNY":6.677105,"USD":1,"USDCNY":0.1497655046610769}}}
What the fields mean and how you’ll use them
- success: boolean for your fast-path check. Short-circuit retries if false.
- timestamp: Unix seconds. Treat as UTC; pair with date for caching and logging.
- date: the market date for these rates (YYYY-MM-DD). This is not necessarily “today” if you call during off-hours or weekends.
- base: the quoting base. Here it’s USD.
- rates.CNY: 6.677105 means 1 USD = 6.677105 CNY.
- rates.USD: 1 (identity under USD base).
- rates.USDCNY: 0.1497655… is provided for convenience in some contexts. Use rates.CNY for straightforward USD→CNY conversions, or use Convert for exact amounts.
Python example: turn latest into a safe converter
The snippet below fetches the latest CNY rate and exposes two pure functions you can call across your app. It also caches the payload in memory with a soft TTL based on the response timestamp.
import os
import time
import requests
API_KEY = os.getenv("INDICES_API_KEY", "YOUR_API_KEY")
LATEST_URL = "https://indices-api.com/api/latest"
_cache = {"payload": None, "fetched_at": 0, "ttl": 300} # 5-minute soft cache
def get_latest_cny_rates():
now = time.time()
if _cache["payload"] and (now - _cache["fetched_at"] < _cache["ttl"]):
return _cache["payload"]
params = {
"access_key": API_KEY,
"symbols": "USD,CNY,USDCNY"
}
resp = requests.get(LATEST_URL, params=params, timeout=10)
resp.raise_for_status()
payload = resp.json()["data"]
# Validate required fields
assert payload.get("success") is True
assert payload.get("base") == "USD"
for key in ("CNY", "USD"):
assert key in payload["rates"]
_cache["payload"] = payload
_cache["fetched_at"] = now
return payload
def usd_to_cny(amount_usd):
data = get_latest_cny_rates()
rate = data["rates"]["CNY"] # 1 USD = rate CNY
return amount_usd * rate, data["timestamp"], data["date"]
def cny_to_usd(amount_cny):
data = get_latest_cny_rates()
rate = data["rates"]["CNY"]
return amount_cny / rate, data["timestamp"], data["date"]
if __name__ == "__main__":
usd_val, ts, d = cny_to_usd(1000.0)
print(f"1000 CNY ≈ {usd_val:.2f} USD (as of {d}, ts={ts})")
cny_val, ts, d = usd_to_cny(250.0)
print(f"250 USD ≈ {cny_val:.2f} CNY (as of {d}, ts={ts})")
Server call 2: convert amounts with the Convert endpoint
While Latest gives you a rate to multiply or divide by, Convert keeps the math and rounding on the server and gives you a single authoritative result tied to a specific rate and timestamp. This is useful when your application requires a canonical conversion (e.g., invoicing, PnL snapshots) and when you want to avoid mismatch from slight rate drifts between services.
curl: convert CNY→USD for a given amount
curl -s "https://indices-api.com/api/convert?access_key=YOUR_API_KEY&from=CNY&to=USD&amount=100000"
Notes:
- from and to accept currency symbols as in the Symbols list.
- amount is a decimal; use integer-like strings for large notionals to avoid floating-point issues in your SDK before the request is sent.
When to prefer Convert over Latest
- If you need an authoritative conversion value and a traceable timestamp for audit.
- If you operate multiple services in different timezones and want a single source of truth.
- If you need a normalized result field right away without client-side math.
Optional: time-series for USD↔CNY backfills and validations
To backfill historical CNY conversions (e.g., EOD reports) or to validate drift vs. yesterday’s close, use the Time-series endpoint. Be aware that end_date cannot be “today”; use the latest completed market date instead.
URL pattern (no sample payload here)
https://indices-api.com/api/timeseries?access_key=YOUR_API_KEY&start_date=YYYY-MM-DD&end_date=YYYY-MM-DD&symbols=USD,CNY
Tips for backfills:
- Request business-day windows. On weekends/holidays, expect the last available date to repeat.
- Do not set end_date to today; set it to yesterday or the last trading day observed in Latest.
- Cache by (start_date, end_date, symbols) and persist to your warehouse to avoid re-pulls.
Full endpoint semantics and query options are covered in the Documentation.
Production details that save you time
Base currency and quote expression
- Default base is USD. With base=USD, rates.CNY is the amount of CNY per 1 USD.
- If you convert CNY→USD on the client from Latest, divide by rates.CNY. If you call Convert, you don’t do any math—use result.
Timestamps, timezone, and recency
- timestamp is Unix seconds; treat it as UTC for logging and cache keys.
- date is the market date associated with the data. It may lag today during off-hours or non-trading days.
- Latest updates are tied to your plan cadence (e.g., every 60 or every 10 minutes). Do not assume sub-minute updates unless your plan specifies it.
Weekends and holidays
- Expect weekend responses to show the last available market date. Do not raise false “stale data” alarms on Saturdays/Sundays.
- Backfills spanning holidays will include gaps or carry-forward values depending on endpoint; handle missing dates explicitly in your pipeline.
Caching and retries
- Cache Latest responses until the next expected refresh boundary. If your plan updates every 10 minutes, set a TTL slightly under 600 seconds to avoid stampedes.
- Key your cache by (base, symbols, date, timestamp). Persist the raw JSON alongside derived fields inside observability stores for audits.
- Use exponential backoff on non-200s and short-circuit on success=false. Log both timestamp and date for post-incident triage.
Server-side inputs and validation
- Never trust user-provided symbols. Validate against Symbols at startup and reject unknown inputs.
- Normalize amount precision to your accounting policy (e.g., 2 decimals for display, higher precision internally).
- Always persist the source fields you used (base, symbol, rate, timestamp, date) with each conversion record.
Integration checklist for server apps
- Obtain an API key: start a 7‑day trial on the Pro $49.99/mo tier to test higher-frequency updates, then rotate to your production key. Use the Register page.
- Implement Latest fetch with caching and metrics (success, latency, age, next_refresh_eta).
- Implement Convert for canonical amounts in workflows that require auditable “result”.
- Add Time-series pulls to your nightly backfill job; cap end_date to the last completed trading day.
- Write idempotent ingestion: store raw JSON payloads and derived values with correlation IDs.
- Expose health checks that validate you can reach Latest and Convert endpoints and that data is not older than your SLO.
Security, deployment, and compliance notes
- Keep the access_key in server-side secrets, never in client-side code. Rotate keys periodically.
- Rate-limit your internal callers to avoid thundering herd effects at refresh boundaries.
- Pin TLS and verify certificates in environments where MITM is a risk.
Extending beyond conversion: alerts and reconciliation
Once you have stable USD↔CNY conversions, two fast wins:
- Alerting: Compare current rates.CNY vs. prior close from your Time-series pull; trigger if absolute or pct change exceeds thresholds relevant to your product.
- Reconciliation: For finance ops, store Convert results and timestamps next to booked FX rates to diagnose variances.
Related references
- For full endpoint details and parameters, see the Indices-API Documentation.
- Confirm all symbols used in this post (CNY, USD, USDCNY) in the official Symbols list.
- Monetary policy background: People’s Bank of China (PBOC) policy announcements and fixing mechanics (external reference: PBOC English portal).
- Cross-currency methodology context: Bank for International Settlements (BIS) statistics (external reference: BIS statistics).
- If you work with multi-cloud policy or data residency constraints, review MCP for deployment options.
Troubleshooting common pitfalls
- “Our end_date returns no data”: Do not set end_date to today. Use the last completed market day. Validate ranges before querying.
- “Values differ across services”: Ensure all services use the same source—either Convert results or the same Latest snapshot keyed by timestamp/date.
- “Weekend data looks stale”: That’s expected. Compare by “date” field, not wall-clock today, and adjust alerts to trading calendars.
- “We see slight rounding differences”: Centralize rounding policy. Prefer Convert for canonical PnL or invoicing amounts; store rate, timestamp, date used.
FAQ
Q: What symbols should I request for USD↔CNY?
A: Request USD, CNY, and USDCNY as needed. Verify canonical codes on the Symbols page before shipping.
Q: How often do latest rates update?
A: Update cadence depends on your plan (e.g., every 60 minutes or every 10 minutes). Pull at that cadence and cache slightly under the interval to avoid stampedes.
Q: Why does the “date” differ from my server’s local day?
A: date reflects the market date of the rates, not your local timezone. During weekends/holidays or outside trading hours, date can be the last completed market day.
Q: Can I set end_date to today for time-series pulls?
A: No. end_date must be the last completed market day. If you need “as of now,” use Latest (for current rates) or Convert (for canonical amounts).
Q: Should I compute conversions client-side or server-side?
A: Keep keys and conversions on the server. Use Latest for simple math when you can tolerate minor rounding differences; use Convert for definitive results tied to a timestamp.
Ready to wire this into your backend? Create your key and start a 7‑day trial on the Pro plan to test higher-frequency updates. Get access here: Register.