DEV Community

allratestoday
allratestoday

Posted on Originally published at allratestoday.com

Loading Dated Exchange Rates into Salesforce: Why Apex DML Fails and What Works

Salesforce multi-currency converts amounts with whatever rates you maintain under Setup > Manage Currencies. Salesforce doesn't fill them in for you. Most orgs end up with someone pasting rates in once a month, and the rates in Salesforce drift away from the ones finance books in the ERP.

When the rate has to be a specific institution's (the ECB reference rate, the Fed's H.10, the RBI reference rate, the HMRC monthly rate), you want a scheduled job that loads that table, dated with the day the bank published it. This post covers the parts that aren't obvious, all of which we hit while building and testing one in a Developer Edition org.

The full guide is at allratestoday.com/docs/integrations/salesforce/. The code is MIT-licensed at github.com/AllRates-Today/salesforce-central-bank-rates.

Two objects, one meaning

  • CurrencyType.ConversionRate holds the static rate per active currency. It is used everywhere when Advanced Currency Management (ACM) is off.
  • DatedConversionRate (IsoCode, ConversionRate, StartDate, read-only NextStartDate) exists only with ACM on. Opportunities, opportunity products and their reports convert at the dated rate in force on the close date.

Both store ConversionRate as units of the currency per 1 unit of the corporate currency, to 6 decimal places.

Problem 1: you can't write them with DML

The first attempt everyone makes is a plain insert new DatedConversionRate(...) in Apex, and the platform refuses it: DML is not allowed on these objects. They can be written through the REST API, though. We tested that in a Developer Edition org on 2026-11-25:

POST /services/data/v62.0/sobjects/DatedConversionRate
{ "IsoCode": "EUR", "ConversionRate": 0.914495, "StartDate": "2026-11-25" }

PATCH /services/data/v62.0/sobjects/DatedConversionRate/04w...
{ "ConversionRate": 0.914495 }

PATCH /services/data/v62.0/sobjects/CurrencyType/02k...
{ "ConversionRate": 0.914495 }
Enter fullscreen mode Exit fullscreen mode

Salesforce closes the previous range for you. After a 2026-11-25 row is created, the earlier row's NextStartDate becomes 2026-11-25. Query for an existing row with the same StartDate first and PATCH it, or a rerun fails on the duplicate.

So an in-org job has to call its own org's REST API from Apex. That means a Named Credential pointing at your My Domain.

Problem 2: the rate direction

The rates API returns a bank's whole table in one call. Each row is value units of quote per 1 unit of base, and rate_date is the date the bank put on the table:

{
  "bank": "ecb",
  "rate_date": "2026-11-25",
  "rates": [
    { "base": "EUR", "quote": "USD", "type": "reference", "value": 1.0935 },
    { "base": "EUR", "quote": "GBP", "type": "reference", "value": 0.8373 }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Every row involves the publisher's home currency (EUR for the ECB, INR for the RBI). Express each currency per 1 unit of that home currency, then divide by the corporate currency's figure:

ConversionRate(X) = (X per 1 home) / (corporate per 1 home)
Enter fullscreen mode Exit fullscreen mode

That makes any bank's table usable whatever your corporate currency is. A USD-corporate org reading the ECB table writes EUR = 1 / 1.0935 = 0.914495 and GBP = 0.8373 / 1.0935 = 0.765706. In Apex, use Decimal.divide(divisor, scale, RoundingMode), and convert JSON numbers yourself: JSON.deserializeUntyped hands you Integer for 180 and Decimal for 1.0935, so a blind (Decimal) cast fails.

Set StartDate to the bank's rate_date, not to the day the job ran.

Problem 3: the job's own credentials

The tested setup uses two Named Credentials:

  1. AllRatesToday for the rates API. It uses an External Credential with the Custom protocol, the key stored encrypted as a principal parameter ApiKey, and a custom header formula:
   Authorization = {!'Bearer ' & $Credential.AllRatesToday.ApiKey}
Enter fullscreen mode Exit fullscreen mode

Tick Allow Formulas in HTTP Header on the Named Credential.

  1. ART_Salesforce_API for the org's own REST API. It uses an External Client App with the client credentials flow (run as an admin who can manage currencies) and an External Credential with OAuth 2.0, Client Credentials with Client Secret, and the token URL https://<domain>.my.salesforce.com/services/oauth2/token.

These setup errors cost us time, so here they are:

  • Leave Scope empty on the client-credentials External Credential. With api in Scope, every callout fails with invalid_request: scope parameter not supported.
  • The consumer secret is only in Setup. The Connect API's apps/oauth/credentials/{appId}/{consumerId} returns the consumer key but never the secret. Copy it from External Client App Manager > Settings > OAuth Settings, after an emailed code.
  • The sf CLI redacts accessToken in sf org display --json ([REDACTED]...). If you paste that into a header to test something, you get INVALID_AUTH_HEADER and a misleading theory about why. Mint a token through your client-credentials app instead.
  • Apex is case-insensitive. public enum Mode {...} plus a field public Mode mode = Mode.DATED; fails to compile with Illegal forward reference: mode. Name the enum SyncMode.

Problem 4: callout limits and scheduling

Scheduled Apex can't make callouts, so the Schedulable only starts a Batch Apex job (Database.AllowsCallouts). Run the batch with scope 1, one table per execute: one GET to the rates API, then one REST write per currency. That stays well under the 100-callouts-per-transaction limit, and the same batch handles a historical load as one item per weekday.

ARTRateOptions o = new ARTRateOptions('ecb');          // or boe, fed, rbi, hmrc, ...
o.mode = ARTRateOptions.SyncMode.DATED;                // or STATIC_RATES without ACM
Database.executeBatch(new ARTRateSyncBatch(o), 1);     // latest table, now

// weekdays 17:00 (scheduling user's time zone), after the ECB's ~16:00 CET publication
System.schedule('ECB rates', '0 0 17 ? * MON-FRI', new ARTRateSyncSchedulable(o));
Enter fullscreen mode Exit fullscreen mode

Make write failures fail the job. Our first version caught per-currency errors and finished as "Completed, 0 errors". It now throws when a write fails, so the error shows in Setup > Apex Jobs.

What the test run showed

In a Developer Edition org (API 68.0, USD corporate, ACM on):

  • 7 Apex tests pass with 89% coverage. They use HttpCalloutMock and an override seam, so they also pass in single-currency orgs, where CurrencyType doesn't exist. That's why the queries are dynamic SOQL.
  • The ECB table loaded as dated rates (EUR 0.914495, GBP 0.765706, JPY 159.323274). A rerun updated those rows instead of duplicating them.
  • The RBI table loaded as static rates and matched the published table to 6 decimals.

Outside Salesforce instead

If you already run jobs in cron or CI, skip the Apex and the second Named Credential. The repo's scripts/python/sync_rates.py gets a token with the client credentials flow, reads the active currencies, and does the same writes over REST (--dry-run prints first).

Links

Rates are redistributed from each institution's own publication. They are reference rates for accounting, tax and compliance, not dealing quotes.

Top comments (0)