# OpenFX > This file is very large and may be truncated. For an index of this content, please refer to https://docs.openfx.com/llms.txt instead. > OpenFX API documentation. Real-time cross-border FX and stablecoin payment infrastructure. # Account model Source: https://docs.openfx.com/v3/account-model The resources behind a payout, how they relate, and the statuses they share. An `Account` is someone you send money to or on behalf of: who they are, and what they're set up to do. It holds no money. This page covers the resources a payout uses, how they fit together, and the statuses they share. ## The four resources | Resource | Who it belongs to | What it is | | - | - | - | | `FinancialAccount` | You | A balance in one currency that funds your payouts. OpenFX creates these for you. | | `Account` | The person or company you pay | Who they are, plus the capabilities (`AccountCapability`) they hold. You create it. | | `PayoutAddress` | The person or company you pay | A bank account the money lands in. It belongs to one `Account`, through `accountId`, and an account can have several. You create it. | | `Payout` | You | Money sent from one of your financial accounts to a payout address. | **A payout links your side to theirs.** It debits `financialAccountId` and credits `receiver.payoutAddressId`. You don't name the receiving account, because the address already belongs to it. Your credentials show which accounts are yours; no field links them to your organization. To find which balances can fund a payout in a given `receiveCurrency`, call [`listFinancialAccounts`](/v3/api-reference/payments/accounts/list-financial-accounts). Each entry has a `currency`, a `label` to tell same-currency balances apart, an `availableBalance`, and a `totalBalance`. The difference between the two balances is the amount on hold. ## Identity `identity` describes who the account is. Set `identityType` to INDIVIDUAL for a person, with an `individual` block, or ORGANIZATION for a company, with an `organization` block. You can't change the type later. An individual's block holds their name, date of birth, nationality, contact details, address, tax numbers, and identity documents. An organization's block holds its registration details (legal name, registration number, date of incorporation, legal structure, registered address) and `associations`: the people and companies that own or control it. Each association has a `role`, such as UBO_THROUGH_OWNERSHIP, DIRECTOR, or ULTIMATE_PARENT_COMPANY, and an `ownershipPercent` where they hold shares. Most identity fields are optional in the schema. The capabilities you request decide which ones you must send. If a required field is missing, the request fails with `422` IDENTITY_REQUIREMENT_UNMET. [Capabilities](/v3/capabilities#identity-requirements) lists the fields for each one. Two fields are just for you: `label`, a name to help you recognize the account, and `metadata`, for a reference back to a record in your own system. ## Capabilities A capability lets an account be paid in a currency, or be named as the sender of a payout. Request them by id in `capabilities` when you [create the account](/v3/api-reference/payments/accounts/create-account), along with the identity they need. You can only add capabilities at creation. An account created without any is just an identity. Each capability comes back as an `AccountCapability` with its `id`, its own `status`, and `details` describing what it covers. [Capabilities](/v3/capabilities) lists every capability and explains how they control payouts. ## Payout addresses A `PayoutAddress` is a bank account an account can be paid at. Its `bankAccount` holds the bank details, and `routingFamily` decides which ones: | `routingFamily` | Bank details | | - | - | | SEPA | An IBAN, as `accountNumber` | | SWIFT | `accountNumber`, `bic`, and the holder's address | | MX_LOCAL | A CLABE, as `accountNumber` | | CO_LOCAL | `bankCode`, `accountNumber`, and `bankAccountType` | | CO_BREB | A Bre-B key, as `brebKey` | | AE_LOCAL | A UAE IBAN, as `accountNumber` | | GB_LOCAL | A UK `sortCode` and `accountNumber` | The address also shows the currencies and rails it can be paid in (`supportedCurrencies`, `supportedRails`) and the checks run on it (`verifications[]`). An address belongs to one account, set by `accountId`, and you can't edit it. To correct anything, create a new address and archive the old one. Addresses aren't included in the account; list them with [`listPayoutAddresses`](/v3/api-reference/payments/addresses/list-payout-addresses), filtered by `accountId`. You can create an address before the account's capability is ACTIVE. The account only needs to hold a capability that can receive at that address, in any status. So you can set up the address and the capability at the same time. ## Roles on a payout An account plays one of two roles on a payout, and each needs a capability. * **The receiver** is the account being paid: the owner of `receiver.payoutAddressId`. It needs an ACTIVE capability that covers that address. * **The sender** is optional: another account, named as `sender` on the quote or inline payout. The payout is made in their name, but the money still comes from your financial account. The sender needs an ACTIVE capability granting SEND_PAYOUTS_TO_THIRD_PARTIES for the destination. ## The shared state machine Three statuses decide whether you can pay: * The account's own status (`AccountStatus`): OpenFX's view of the account as a whole. * Each capability's status (`CapabilityStatus`). * Each payout address's status (`PayoutAddressStatus`). All three use the same four values and the same transitions, so you only need to learn them once. They differ in what changes them and what ACTIVE lets you do. ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% stateDiagram-v2 direction TB [*] --> PENDING: created [*] --> ACTIVE: created PENDING --> ACTIVE: settled, nothing blocking PENDING --> REQUIRES_INFORMATION: needs information PENDING --> REJECTED: outcome went against it ACTIVE --> REQUIRES_INFORMATION: needs information ACTIVE --> REJECTED: later outcome turned REQUIRES_INFORMATION --> PENDING: information provided REQUIRES_INFORMATION --> REJECTED: outcome went against it ACTIVE --> [*] REJECTED --> [*] classDef ok stroke-width:1px classDef bad stroke-width:1px classDef pending stroke-width:1px classDef hold stroke-width:1px classDef returned stroke-width:1px classDef neutral stroke-width:1px class PENDING pending class ACTIVE ok class REQUIRES_INFORMATION hold class REJECTED bad ``` | Status | Meaning | | - | - | | PENDING | Created and not settled yet | | ACTIVE | Settled, with nothing blocking | | REQUIRES_INFORMATION | OpenFX has asked you for something. The status returns to PENDING once you provide it | | REJECTED | An outcome went against it. Final | Only PENDING can move to ACTIVE, and an ACTIVE status never goes back to PENDING. Anything that isn't REJECTED can move to REQUIRES_INFORMATION or REJECTED. OpenFX's request for information and your answer go through your usual support channel, not the API. Each section below says what to do after REJECTED. Capabilities and payout addresses always start PENDING. An account starts PENDING or ACTIVE. Two rules apply to all three: 1. **Create responses show the current status.** [`createAccount`](/v3/api-reference/payments/accounts/create-account) and [`createPayoutAddress`](/v3/api-reference/payments/addresses/create-payout-address) show each status at the moment of the response, including checks that finished during the call. Read the response instead of assuming a starting value. 2. **Every status change sends exactly one webhook**, however quickly it happened. Creation has its own webhook: [`common.account.created`](/v3/webhooks/payments/accounts-webhooks/account-created) shows the starting status of the account and each capability, and [`payments.payout_address.created`](/v3/webhooks/payments/addresses-webhooks/payout-address-created) shows an address's. ### The account's own status `AccountStatus` is OpenFX's decision on whether to do business with the account at all. **It doesn't summarize the capabilities.** An account can be ACTIVE while a capability is still PENDING, or REJECTED while its capabilities are ACTIVE. OpenFX's risk and compliance review sets it. Today that's a manual decision, made outside the API. Each change sends [`common.account.activated`](/v3/webhooks/payments/accounts-webhooks/account-activated), [`common.account.rejected`](/v3/webhooks/payments/accounts-webhooks/account-rejected), or [`common.account.requires_information`](/v3/webhooks/payments/accounts-webhooks/account-requires-information), with the `previousStatus`. A REJECTED account can't be named on any payout, as receiver or sender. Create a new account instead. Sending more identity details won't reverse a rejection. ### Capability status `createAccount` succeeds once the request is valid and the identity requirements are met. Each capability starts PENDING and its checks begin straight away. Checks that finish during the call show up in the response, so a capability can already be ACTIVE there. The rest settle later, by webhook. PENDING means the capability's checks haven't finished. The API doesn't show which checks run or in what order, only the result. A minute is typical but not guaranteed, so don't build a flow that assumes a time limit. Wait for the webhook instead. Each change sends its own webhook: [`common.account.capability_activated`](/v3/webhooks/payments/accounts-webhooks/account-capability-activated), [`common.account.capability_rejected`](/v3/webhooks/payments/accounts-webhooks/account-capability-rejected), or [`common.account.capability_requires_information`](/v3/webhooks/payments/accounts-webhooks/account-capability-requires-information). `data.capability` says which capability changed, and `data.capabilities[]` has the current status of every capability. A fast check still sends its webhook, so it can arrive before your system has handled the create response, or before `common.account.created`. Each webhook carries the resource as it was when the event fired, minus a few fields webhooks never include. See [Webhook authentication](/v3/webhooks/authentication). A REJECTED capability can't be used or revived. The account and its other capabilities aren't affected. The replacement is a different capability, never the same one, and capabilities can only be requested when an account is created. ### Payout address status An address usually starts PENDING and its checks begin straight away. Some are listed in `verifications[]`; others OpenFX runs without listing. `status` reflects all of them. There's no time guarantee here either, and OpenFX retries temporary problems itself. Each change sends one webhook: [`payments.payout_address.activated`](/v3/webhooks/payments/addresses-webhooks/payout-address-activated), [`payments.payout_address.rejected`](/v3/webhooks/payments/addresses-webhooks/payout-address-rejected), or [`payments.payout_address.requires_information`](/v3/webhooks/payments/addresses-webhooks/payout-address-requires-information). [`payments.payout_address.verification_resolved`](/v3/webhooks/payments/addresses-webhooks/payout-address-verification-resolved) also fires whenever a listed check resolves, even if the status doesn't change. **Checks continue for as long as the address exists**, so an ACTIVE address can later be rejected or need more information. A rejection after activation arrives as `payments.payout_address.rejected` with `previousStatus: "ACTIVE"`. If every entry in `verifications[]` looks fine, the failure came from an unlisted check. A REJECTED address can't receive payouts. Since you can't edit it, create a new one. ## How a payout reads the model A payout needs all three ACTIVE at once: the account, the capability the payout needs, and the payout address. REQUIRES_INFORMATION blocks a payout just like PENDING. [`createPayout`](/v3/api-reference/payments/payouts/create-payout) checks all three, and its 409 errors say which one failed. * **The account**: the status of the receiving account, and of the sender if there is one. * **The capability**: the receiver and any sender each need an ACTIVE capability that covers the payout. See [Capabilities](/v3/capabilities#the-coverage-gate). A missing capability fails the same way as one that isn't ACTIVE. * **The address**: the payout address's own status. Creating an address only needs a covering capability to exist, in any status. See [Payouts](/v3/payouts). ## Archiving OpenFX sets status; you decide archiving. Accounts and payout addresses have an `archivedAt` that's null until you call [`archiveAccount`](/v3/api-reference/payments/accounts/archive-account) or [`archivePayoutAddress`](/v3/api-reference/payments/addresses/archive-payout-address). Archiving is permanent. Both calls take no body and are safe to repeat: archiving again returns the record with its original `archivedAt`. Archived records are hidden from list calls by default, can still be fetched by id, and are kept in full for regulatory and audit purposes. Nothing is deleted. You can't pay an archived account or create addresses for it, and you can't pay an archived address. Payouts already under way carry on, as described in [Payouts](/v3/payouts#archiving-does-not-stop-a-payout-in-flight). Archiving and status are separate. A REJECTED address stays live until you archive it, and an archived ACTIVE account is still ACTIVE. Archiving sends [`common.account.archived`](/v3/webhooks/payments/accounts-webhooks/account-archived) or [`payments.payout_address.archived`](/v3/webhooks/payments/addresses-webhooks/payout-address-archived). ## What's next > [card] [Payouts](/v3/payouts) > > Set up a recipient and send a payout. > [card] [Capabilities](/v3/capabilities) > > Every capability and the identity it requires. > [card] [Payment Webhooks](/v3/webhooks/payments/accounts-webhooks/account-created) > > Every event these resources emit. # Payouts to the UAE Source: https://docs.openfx.com/v3/aed-payout-integration Pay a UAE bank account in AED: register the IBAN, then meet the purpose, funding, memo, and limit rules. Pay a UAE bank account in UAE dirhams (AED). For the general flow, see [Payout lifecycle](/v3/payouts). The quote, confirm, and webhook steps are the same as for EUR, and so is the fee model. [Supported payout currencies](/v3/payouts#supported-payout-currencies) compares every payout currency side by side. ## Before you start * Your organization must be enabled for AED. Until it is, listing the financial accounts that can fund a AED payout fails with `403` PAYOUT_CURRENCY_NOT_ENABLED, and a quote or payout fails with `409` PAYOUT_NOT_ENABLED. * The recipient's account needs the UAE-dirham receiving capability, ACTIVE before you pay. [Capabilities](/v3/capabilities#the-capability-catalog) lists the id, and [Be paid in UAE dirhams](/v3/capabilities#be-paid-in-uae-dirhams) lists the identity the recipient owes. * AED has no sending capability. Don't send a `sender` on a quote or payout, or it fails with `422` SENDER_NOT_SUPPORTED. * Every `POST` needs an `Idempotency-Key` header. See [Idempotency](/v3/idempotency#payments-endpoints). ## Register the bank account and create the payout A UAE bank account is identified by its IBAN and paid over AE_LOCAL. The recipient owes a name and an address with `line1` and `country`, in any country, and no identity document. See [Be paid in UAE dirhams](/v3/capabilities#be-paid-in-uae-dirhams). Register the account with `routingFamily` AE_LOCAL and the UAE IBAN as `accountNumber`. The IBAN carries the bank, so you send no BIC, bank code, or account type. No name check runs, so `verifications[]` stays empty. The `accountHolderName` can be at most 75 bytes. [Be paid in UAE dirhams](/v3/capabilities#be-paid-in-uae-dirhams) lists the characters it can use. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "payoutAddressType": "BANK_ACCOUNT", "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", "bankAccount": { "routingFamily": "AE_LOCAL", "accountNumber": "AE070331234567890123456" } }' ``` Three rules apply only to AED: * **Every payout needs a `purpose`.** Send one of GOODS_AND_SERVICES, PROFESSIONAL_SERVICES, INFORMATION_TECHNOLOGY, MERCHANT_SETTLEMENT, FINANCIAL_SERVICES, TREASURY_MANAGEMENT, PAYROLL, RENTAL, or TRAVEL. INVESTMENTS and OTHER are refused. A missing or refused value fails with `422` PURPOSE_INVALID. A quote carries no `purpose`, so send it when you create the payout, and the payout response carries it back. * **You fund it from a stablecoin or AED balance.** The financial account must hold USDC, USDT, EURC, or AED. Any other send currency fails with `422` QUOTE_SEND_CURRENCY_UNAVAILABLE. * **Per-payout limits apply.** A `receiveAmount` outside them is refused when the payout is priced, with `422` AMOUNT_OUT_OF_RANGE. `error.details` carries the exact bound. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payouts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "type": "INLINE", "financialAccountId": "finacc_AmKC5dMVXUbiAW8VzKBfqz", "receiver": { "payoutAddressId": "pytadd_PbDQ126YUAbkNrNX6XbGL" }, "receiveAmount": "5000.00", "receiveCurrency": "AED", "purpose": "GOODS_AND_SERVICES", "receiverMemo": "Invoice 4012" }' ``` The payout starts in REQUIRES_CONFIRMATION. [Confirm it](/v3/payouts#send-the-payout) as you would any payout. ## Memos On AE_LOCAL, a `receiverMemo` is at most 100 letters, digits, and spaces. A memo that is too long or holds any other character fails with `400` RECEIVER_MEMO_INVALID. OpenFX never truncates it. ## Track settlement On an AE_LOCAL payout, `settlementTraceId.status` reads UNSUPPORTED. [Trace a payout with the receiving bank](/v3/payouts#trace-a-payout-with-the-receiving-bank) lists the key for every rail. ## Common mistakes * **Naming a `sender`.** AED has no sending capability. Remove `sender` from the quote and the payout. * **Leaving out `purpose`, or sending INVESTMENTS or OTHER.** Each fails with `422` PURPOSE_INVALID. Pick the closest of the nine accepted values. * **Funding the payout from another currency.** Fund it from USDC, USDT, EURC, or AED. ## What's next > [card] [Payout lifecycle](/v3/payouts) > > The general payout flow. > [card] [Capabilities](/v3/capabilities#the-capability-catalog) > > The receiving capability and identity each currency needs. > [card] [Payouts in EUR](/v3/eur-payout-integration) > > Paying euro accounts over SEPA or SWIFT. > [card] [Payouts to Mexico](/v3/mxn-payout-integration) > > Paying Mexican bank accounts over SPEI. > [card] [Payouts to Colombia](/v3/cop-payout-integration) > > Paying Colombian bank accounts and Bre-B keys. > [card] [Payment Webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Every payout and address event. # Amounts Source: https://docs.openfx.com/v3/amounts Format rules, prefix vocabulary, parsing examples, and precision behavior for monetary values. Every monetary amount in v3 (request body, response field, query parameter) is a **JSON string** with a semantic prefix that tells you what the number refers to: `buyAmount`, `sellAmount`, `withdrawalAmount`, `depositAmount`, `withdrawableBalance`, and so on. No floats; no JSON numbers like `1000.50`. Sending a number instead of a string returns `400` VALIDATION_BODY_FAILED. Reading the response with a JSON parser that auto-converts to `float` re-introduces the bug v3 is designed to avoid. This illustrative object combines amount fields from several resource schemas. It is not a standalone request or response and omits the other fields required by those resources. ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "buyAmount": "1000", "sellAmount": "999.5", "withdrawableBalance": "5000", "totalBalance": "5150" } ``` > [!WARNING] > > **Strings, always.** A request body with `"withdrawalAmount": 1000` (JSON > number, not string) returns `400` VALIDATION_BODY_FAILED. Sending `"1000"` > works; sending `1000` doesn't. ## Why strings Floats lose precision. `0.1 + 0.2` is `0.30000000000000004` in JavaScript and in most languages whose numbers are IEEE-754 floats, which is how JSON numbers are typically parsed. For monetary amounts that's unacceptable: a \$0.000000000004 discrepancy compounds across millions of trades. Strings preserve every digit the API returns. FX responses can contain up to 16 fractional digits; parse them with a decimal representation such as `Decimal`, `BigDecimal`, or `bigint*scale`. ## Format | Constraint | Behavior | | - | - | | FX request amount pattern | `PositiveRequestAmount`: up to 16 fractional digits; request amounts must be greater than zero. | | Non-negative response pattern | `PositiveAmount`: `^[0-9]+(\.[0-9]{1,16})?$`, used for FX response and limit amounts. | | Signed response pattern | `SignedAmount`: `^-?[0-9]+(\.[0-9]{1,16})?$`, used where a negative response value is meaningful. | | FX response precision | Up to 16 fractional digits. FX amount schemas do not impose a per-currency fractional-digit cap. | | Withdrawal precision | Withdrawal requests retain the documented per-currency business checks: 2 decimals for fiat and 6 for crypto. | | Leading zero required | Yes (`"0.50"`, not `".50"`). | | Scientific notation | Not allowed (`1e3` is invalid). | | Decimal separator | Period (`.`) only. | | Thousands separators | Not allowed. No commas, spaces, underscores, or apostrophes between digits. These fail with `400` VALIDATION_BODY_FAILED. | | Trailing zeroes | FX responses do not preserve trailing zeroes; for example, an amount may be returned as `"10.5"`, not `"10.50"`. | | Negative amounts | FX requests reject a leading `-` with `400` VALIDATION_BODY_FAILED. Response fields may be negative only where they use `SignedAmount`. | An FX request body with a zero amount (`"0"` or `"0.00"`) or a negative amount (for example, `"-1.00"`) returns `400` VALIDATION_BODY_FAILED. The FX request schemas reject zero and negative amounts before business-rule checks. ## Prefix vocabulary Amount fields are **always** prefixed to describe what they refer to. There is no bare top-level `amount` field on any resource in v3. Every monetary field carries a qualifier and ends in `Amount` or `Balance`. A `Deposit` carries `depositAmount`, a `Withdrawal` carries `withdrawalAmount`, a `Quote` and `Trade` carry `buyAmount` / `sellAmount`, and a `Balance` carries `withdrawableBalance` / `totalBalance`. The one exception is a nested object that's already qualified by its parent key: the exposure summary's `usageBreakdown.settlableNow.amount` and `.settlableLater.amount`. | Prefix | Meaning | | - | - | | `buyAmount` | The amount being bought / received. On `POST /v3/fx/quotes`, supply this when you want to lock the **buy** side (you choose what to receive); the server computes `sellAmount`. | | `sellAmount` | The amount being sold / debited. On `POST /v3/fx/quotes`, supply this when you want to lock the **sell** side (you choose what to spend); the server computes `buyAmount`. Supply exactly one of `buyAmount` or `sellAmount` on a quote request. | | `withdrawalAmount` | The amount to withdraw, on a `POST /v3/fx/withdrawals` request body and on the `Withdrawal` response. Request amount must be greater than zero; the response uses `PositiveAmount`. | | `depositAmount` | The amount that landed, on a `Deposit` response. | | `withdrawableBalance` | Funds available for trading or withdrawing right now (on a `Balance` row, or on the response's `aggregate` block). Never negative: `0` when the corresponding `totalBalance` (or the org's net equity) is negative. | | `totalBalance` | Total funds held in a currency, including any amount earmarked against pending operations (on a `Balance` row). May be negative when the org owes a settlement (`SignedAmount`); when it is, `withdrawableBalance` is `0` rather than `≤ totalBalance`. | | `minTradeAmount` | Smallest tradable amount, denominated in that pair entry's `sellCurrency`. Each trade direction is listed as its own pair entry, so the limit tracks direction, not just the currency pair. | | `maxTradeAmount` | Largest tradable amount, denominated in that pair entry's `sellCurrency`. Each trade direction is listed as its own pair entry, so the limit tracks direction, not just the currency pair. | Every monetary field carries a qualifier and ends in `Amount` or `Balance`. There's no bare `amount` field to infer meaning from context. ## Parsing in clients ```javascript Node theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Parses buyAmount/sellAmount as Decimal, not float, to avoid the precision // loss floats introduce — the pattern from /v3/amounts#parsing-in-clients. const Decimal = require("decimal.js"); // signRequest is the real helper from /v3/authentication — adjust this path // if you've copied it somewhere else in your own project. const { signRequest } = require("../../authentication/node/sign-request"); // Divides two string amount fields as Decimal. Kept separate from the // network call so it's testable without a real request. Exactly one of // buyAmount/sellAmount is present on a trade — whichever side the quote // was anchored on — and executedAmount carries the other side. function computeRate(trade) { const buy = new Decimal(trade.buyAmount ?? trade.executedAmount); const sell = new Decimal(trade.sellAmount ?? trade.executedAmount); return buy.div(sell); } async function getTrade(id) { const url = `https://api.openfx.com/v3/fx/trades/${id}`; const { headers } = signRequest({ method: "GET", url }); const res = await fetch(url, { headers }); const { data } = await res.json(); return data; } async function tradeRate(id) { const trade = await getTrade(id); return computeRate(trade); } module.exports = { computeRate, getTrade, tradeRate }; if (require.main === module) { tradeRate("some-trade-id").catch((err) => { console.error("Error:", err.message); process.exitCode = 1; }); } ``` ```python Python theme={"theme":{"light":"poimandres","dark":"poimandres"}} """Parses buyAmount/sellAmount as Decimal, not float, to avoid the precision loss floats introduce — the pattern from /v3/amounts#parsing-in-clients.""" import os import sys from decimal import Decimal, getcontext # sign_request is the real helper from /v3/authentication — adjust this path # if you've copied it somewhere else in your own project. sys.path.insert( 0, os.path.join(os.path.dirname(__file__), "..", "..", "authentication", "python") ) from sign_request import sign_request # noqa: E402 import requests # noqa: E402 getcontext().prec = 28 def compute_rate(trade): """Divides two string amount fields as Decimal. Kept separate from the network call so it's testable without a real request. Exactly one of buyAmount/sellAmount is present on a trade — whichever side the quote was anchored on — and executedAmount carries the other side.""" buy = Decimal(trade.get("buyAmount", trade["executedAmount"])) sell = Decimal(trade.get("sellAmount", trade["executedAmount"])) return buy / sell def get_trade(trade_id): url = f"https://api.openfx.com/v3/fx/trades/{trade_id}" headers, _ = sign_request("GET", url) res = requests.get(url, headers=headers) return res.json()["data"] def trade_rate(trade_id): trade = get_trade(trade_id) return compute_rate(trade) if __name__ == "__main__": print(trade_rate("some-trade-id")) ``` ```java Java theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Parses buyAmount/sellAmount as BigDecimal, not double, to avoid the // precision loss floats introduce — the pattern from // /v3/amounts#parsing-in-clients. import java.math.BigDecimal; import java.math.MathContext; import java.net.HttpURLConnection; import java.net.URI; import java.util.Map; public class ParseAmounts { // Divides two string amount fields as BigDecimal. Kept separate from // the network call so it's testable without a real request. Exactly // one of buyAmount/sellAmount is present on a trade — whichever side // the quote was anchored on — and executedAmount carries the other // side. static BigDecimal computeRate(Map trade) { String buyAmount = trade.getOrDefault("buyAmount", trade.get("executedAmount")); String sellAmount = trade.getOrDefault("sellAmount", trade.get("executedAmount")); BigDecimal buy = new BigDecimal(buyAmount); BigDecimal sell = new BigDecimal(sellAmount); return buy.divide(sell, new MathContext(28)); } static Map getTrade(String id) throws Exception { String url = "https://api.openfx.com/v3/fx/trades/" + id; // SignRequest is the real helper from /v3/authentication, compiled // on the classpath alongside this file — see that page's example. Map headers = SignRequest.signRequest("GET", url, new byte[0]); HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection(); conn.setRequestMethod("GET"); for (Map.Entry h : headers.entrySet()) { conn.setRequestProperty(h.getKey(), h.getValue()); } conn.getResponseCode(); // A real implementation would parse the JSON response body's `data` // object into a Map here. return Map.of(); } public static void main(String[] args) throws Exception { Map trade = getTrade("some-trade-id"); System.out.println(computeRate(trade)); } } ``` ```cpp C++ theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Parses buyAmount/sellAmount as a fixed-point decimal, not double, to avoid // the precision loss floats introduce — the pattern from // /v3/amounts#parsing-in-clients. Requires OpenSSL and libcurl. #include #include #include #include #include // Matches the definition in ../../authentication/cpp/sign_request.cpp, // compiled together with this file — see that file for the real // implementation of signRequest. struct SignedRequest { std::string authHeader; std::string sigHeader; }; SignedRequest signRequest(const std::string& method, const std::string& urlPath, const std::string& query, const std::string& body); // A fixed-point decimal: value * 10^-scale. Avoids the precision loss a // double introduces when dividing decimal string amounts. struct Decimal { int64_t value; int scale; }; static Decimal parseDecimalString(const std::string& s) { size_t dot = s.find('.'); if (dot == std::string::npos) return {std::stoll(s), 0}; std::string digits = s.substr(0, dot) + s.substr(dot + 1); return {std::stoll(digits), static_cast(s.size() - dot - 1)}; } // std::to_string does not support __int128 — convert by hand. static std::string int128ToString(__int128 value) { if (value == 0) return "0"; std::string result; while (value > 0) { result.insert(result.begin(), '0' + static_cast(value % 10)); value /= 10; } return result; } // Returns trade[key] if present, else trade["executedAmount"]. Exactly one // of buyAmount/sellAmount is present on a trade — whichever side the quote // was anchored on — and executedAmount carries the other side. static const std::string& amountOrExecuted(const std::map& trade, const std::string& key) { auto it = trade.find(key); return it != trade.end() ? it->second : trade.at("executedAmount"); } // Divides two string amount fields as fixed-point decimals, scaled to 20 // fractional digits. Kept separate from the network call so it's testable // without a real request. std::string computeRate(const std::map& trade) { Decimal buy = parseDecimalString(amountOrExecuted(trade, "buyAmount")); Decimal sell = parseDecimalString(amountOrExecuted(trade, "sellAmount")); const int outScale = 20; __int128 numerator = static_cast<__int128>(buy.value); for (int i = 0; i < outScale + sell.scale - buy.scale; i++) numerator *= 10; __int128 quotient = numerator / sell.value; std::string digits = int128ToString(quotient); while (static_cast(digits.size()) <= outScale) digits = "0" + digits; return digits.substr(0, digits.size() - outScale) + "." + digits.substr(digits.size() - outScale); } static size_t discard(char*, size_t s, size_t n, void*) { return s * n; } std::map getTrade(const std::string& id) { std::string url = "https://api.openfx.com/v3/fx/trades/" + id; SignedRequest req = signRequest("GET", "/v3/fx/trades/" + id, "", ""); CURL* curl = curl_easy_init(); curl_slist* headers = nullptr; headers = curl_slist_append(headers, ("Authorization: " + req.authHeader).c_str()); headers = curl_slist_append(headers, ("X-Request-Signature: " + req.sigHeader).c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, discard); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); // A real implementation would parse the JSON response body's `data` // object here. return {}; } #ifndef PARSE_AMOUNTS_NO_MAIN int main() { try { auto trade = getTrade("some-trade-id"); std::cout << computeRate(trade) << std::endl; return 0; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } #endif ``` ```go Go theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Parses buyAmount/sellAmount as big.Rat, not float64, to avoid the // precision loss floats introduce — the pattern from // /v3/amounts#parsing-in-clients. package main import ( "fmt" "math/big" "net/http" // auth is the real signRequest helper from /v3/authentication — see // go.mod's replace directive if you've copied it somewhere else. auth "openfx-v3-authentication-example" ) // amountOrExecuted returns trade[key] if present, else trade["executedAmount"]. // Exactly one of buyAmount/sellAmount is present on a trade — whichever side // the quote was anchored on — and executedAmount carries the other side. func amountOrExecuted(trade map[string]string, key string) string { if value, ok := trade[key]; ok { return value } return trade["executedAmount"] } // Divides two string amount fields as big.Rat. Kept separate from the // network call so it's testable without a real request. func computeRate(trade map[string]string) (*big.Rat, error) { buyAmount := amountOrExecuted(trade, "buyAmount") sellAmount := amountOrExecuted(trade, "sellAmount") buy, ok := new(big.Rat).SetString(buyAmount) if !ok { return nil, fmt.Errorf("invalid buyAmount: %q", buyAmount) } sell, ok := new(big.Rat).SetString(sellAmount) if !ok { return nil, fmt.Errorf("invalid sellAmount: %q", sellAmount) } return new(big.Rat).Quo(buy, sell), nil } func getTrade(id string) (map[string]string, error) { url := "https://api.openfx.com/v3/fx/trades/" + id signed, err := auth.SignRequest("GET", url, nil) if err != nil { return nil, err } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, v := range signed.Headers { req.Header.Set(k, v) } res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() // A real implementation would parse the JSON response body's `data` // object here. return map[string]string{}, nil } func main() { trade, err := getTrade("some-trade-id") if err != nil { fmt.Println("Error:", err) return } rate, err := computeRate(trade) if err != nil { fmt.Println("Error:", err) return } fmt.Println(rate.FloatString(20)) } ``` ## Sending amounts Stringify the value before adding it to a JSON body. Most JSON serializers will turn a string into a JSON string with no special handling. ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} await fetch("https://api.openfx.com/v3/fx/withdrawals", { method: "POST", headers: {/* ... */}, body: JSON.stringify({ withdrawalAccountId: "...", withdrawalAmount: "1000.00", // string, not 1000.00 currency: "USD", }), }); ``` ## Withdrawal precision rules per currency type For withdrawal requests, the server enforces: * **Fiat:** max 2 decimal places. `"100.00"` ✓, `"100.123"` → `422` WITHDRAWAL_INVALID_AMOUNT_PRECISION with `details: { maxDecimals: 2 }` * **Crypto:** max 6 decimal places. `"100.000001"` ✓, `"100.0000001"` → same error with `maxDecimals: 6` These per-currency withdrawal checks are business rules; they do not limit FX request or response precision. ## Currency codes Amounts always travel with a currency code (`currency`, `buyCurrency`, `sellCurrency`). | Type | Format | Examples | | - | - | - | | Fiat | ISO 4217 (3 uppercase letters) | USD, EUR, GBP | | Crypto | Canonical ticker | USDC, USDT, EURC | Pattern: `^[A-Z0-9]{2,15}$` (some tokens contain digits, e.g. `1INCH`). ## Common mistakes * **Sending** `withdrawalAmount: 1000.50 `**(number) instead of** `"1000.50" `**(string).** The number-vs-string distinction is enforced server-side and returns `400` VALIDATION_BODY_FAILED. JSON serializers in some languages quietly emit numbers if you give them a `Decimal` or `BigDecimal`; explicitly `.toString()` before serializing. * **Parsing into a native float.** Round-tripping `"1.10"` through `JSON.parse` followed by `Number()` lands you back in IEEE-754 territory. Wrap in `Decimal` / `BigDecimal` immediately on read. * **Formatting with locale separators.** Use the period (`.`) decimal separator and no thousands separators. A locale-aware formatter that emits `"1,000.50"` or `"1.000,50"` fails with `400` VALIDATION_BODY_FAILED. Serialize amounts with an invariant/US formatter, not the user's locale. * **Stripping trailing zeros for display before persisting.** `"1.00"` and `"1"` parse to the same value but are not byte-equivalent strings. If you compare amounts as strings (e.g. for idempotent retries), normalize first. * **Sending too many decimals on a withdrawal.** Withdrawal requests allow 2 decimals for fiat and 6 for crypto; over-precision returns `422` WITHDRAWAL_INVALID_AMOUNT_PRECISION with `details.maxDecimals` and `details.currency`. Round (don't truncate) to the right scale before sending. FX amount schemas allow up to 16 fractional digits. * **Sending a bare** `amount `**field.** No request body accepts a bare `amount` field. A `Quote` carries `buyAmount` / `sellAmount` / `quoteAmount`; a `Trade` carries `buyAmount` / `sellAmount` / `executedAmount`; a `Withdrawal` request and response carry `withdrawalAmount`; a `Deposit` carries `depositAmount`. `quoteAmount` / `executedAmount` is the computed counter-leg amount, not a standalone exchange rate. A bare `amount` key in a request is rejected (unknown field on the request body). ## Balance lifecycle: available vs total Every `Balance` row carries two amounts. Treat them as a state machine, not a snapshot. * `withdrawableBalance`: spendable now. Never negative. * `totalBalance`: total held in the currency, including any amount earmarked against PENDING operations (submitted withdrawals, in-flight settlements). Ordinarily `withdrawableBalance` ≤ `totalBalance`, but it can go negative when the org owes a settlement in that currency; `withdrawableBalance` is then `0` rather than a negative-adjacent figure. The held (earmarked) portion is the difference `totalBalance − withdrawableBalance` (when `totalBalance` is non-negative). It is not broken out as a separate field in v3; a richer per-state breakdown may be added later. > [!NOTE] > > **Quotes do not reserve balance.** Only EXECUTED trades and submitted > withdrawals do. A quote that never fires is free. ### Net equity aggregate `GET /v3/fx/balances` also returns an `aggregate` block (nested under `data.aggregate`) alongside the per-currency `data.balances` array: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "currency": "USD", "withdrawableBalance": "85000.00" } ``` `aggregate.withdrawableBalance` is the org's net equity across **every** currency, converted to USD. It's the ceiling on what can actually be withdrawn overall, as distinct from any single currency's `withdrawableBalance`. It follows the same clamping rule: never negative, `0` when the org's overall net position is negative. ### Walkthrough: a trade through its lifecycle Starting balance: USD `5000.00` total, `5000.00` available. | Action | `withdrawableBalance` | `totalBalance` | Note | | - | - | - | - | | Initial | `5000.00` | `5000.00` | Idle | | `POST /v3/fx/quotes` (USD 1000 → EUR) | `5000.00` | `5000.00` | Quotes price; they don't hold balance | | `POST /v3/fx/trades` (executes the quote) | `4000.00` | `4000.00` | Atomic single-hop: USD debited and EUR credited together | | Quote expires unused | `5000.00` | `5000.00` | If you never EXECUTED | Trades are single-hop atomic. They debit one currency and credit another in the same operation. There is no intermediate held state for trades themselves, so `withdrawableBalance` and `totalBalance` move together. ### Walkthrough: a withdrawal through its lifecycle Starting balance: USD `4000.00` total, `4000.00` available. | Action | `withdrawableBalance` | `totalBalance` | Held (`total − available`) | Withdrawal status | | - | - | - | - | - | | Initial | `4000.00` | `4000.00` | `0.00` | — | | `POST /v3/fx/withdrawals` (USD 1500) | `2500.00` | `4000.00` | `1500.00` | PENDING | | Rail confirms settlement | `2500.00` | `2500.00` | `0.00` | COMPLETED: funds left OpenFX | | (Counterfactual) withdrawal doesn't go through | `4000.00` | `4000.00` | `0.00` | CANCELLED: hold released | Withdrawals earmark funds at POST and release them at completion or cancellation. While PENDING, funds are out of `withdrawableBalance` but still counted in `totalBalance`. ### Which view to read | Use case | Look at | | - | - | | "Can I trade USD 3000 right now?" | `withdrawableBalance` | | "How much USD do I own in total?" | `totalBalance` | | "What's tied up in in-flight ops?" | `totalBalance − withdrawableBalance` | | End-of-day reconciliation | `totalBalance` (or both) | ## What's next > [card] [Quickstart](/v3/quickstart#4-quote-a-trade) > > A worked quote-then-trade flow that uses these amount fields. > [card] [Errors](/v3/errors) > > WITHDRAWAL_INVALID_AMOUNT_PRECISION and other amount-related errors. > [card] [FX quotes](/v3/quotes) > > Where `buyAmount`, `sellAmount`, and `quoteAmount` come from. # Retrieve exposure summary Source: https://docs.openfx.com/v3/api-reference/exposure/get-exposure-summary api-reference/openapi-v3.json GET /v3/fx/exposures Returns the organization's exposure-limit usage, aggregated and broken down by currency. # Archive an account Source: https://docs.openfx.com/v3/api-reference/payments/accounts/archive-account api-reference/openapi-v3-payments.json POST /v3/common/accounts/{accountId}/archive Soft-archive an account. # Create an account Source: https://docs.openfx.com/v3/api-reference/payments/accounts/create-account api-reference/openapi-v3-payments.json POST /v3/common/accounts Create an account and optionally request capabilities for it in the same call. # Retrieve an account Source: https://docs.openfx.com/v3/api-reference/payments/accounts/get-account api-reference/openapi-v3-payments.json GET /v3/common/accounts/{accountId} Retrieve a single account. # List accounts Source: https://docs.openfx.com/v3/api-reference/payments/accounts/list-accounts api-reference/openapi-v3-payments.json GET /v3/common/accounts List with cursor pagination. # List financial accounts Source: https://docs.openfx.com/v3/api-reference/payments/accounts/list-financial-accounts api-reference/openapi-v3-payments.json GET /v3/common/financial-accounts List the financial accounts your organization can currently use to fund a payout settling in a given `receiveCurrency`. # Archive a payout address Source: https://docs.openfx.com/v3/api-reference/payments/addresses/archive-payout-address api-reference/openapi-v3-payments.json POST /v3/payments/payout-addresses/{payoutAddressId}/archive Soft-archive a payout address. # Create a payout address Source: https://docs.openfx.com/v3/api-reference/payments/addresses/create-payout-address api-reference/openapi-v3-payments.json POST /v3/payments/payout-addresses Register a destination `accountId` can be paid at. # Retrieve a payout address Source: https://docs.openfx.com/v3/api-reference/payments/addresses/get-payout-address api-reference/openapi-v3-payments.json GET /v3/payments/payout-addresses/{payoutAddressId} Retrieve a full `PayoutAddress`, including its `verifications[]` and the `status` derived from them. # List payout addresses Source: https://docs.openfx.com/v3/api-reference/payments/addresses/list-payout-addresses api-reference/openapi-v3-payments.json GET /v3/payments/payout-addresses Cursor list of payout addresses across the organization, optionally narrowed to one account via `?accountId=`. # Verify a payout address Source: https://docs.openfx.com/v3/api-reference/payments/addresses/verify-payout-address api-reference/openapi-v3-payments.json POST /v3/payments/payout-addresses/verify Verify a payout address before creating it. # Cancel a payout Source: https://docs.openfx.com/v3/api-reference/payments/payouts/cancel-payout api-reference/openapi-v3-payments.json POST /v3/payments/payouts/{payoutId}/cancel Cancel a payout while it's still in `REQUIRES_CONFIRMATION`; idempotent, re-cancelling returns 200. # Confirm a payout Source: https://docs.openfx.com/v3/api-reference/payments/payouts/confirm-payout api-reference/openapi-v3-payments.json POST /v3/payments/payouts/{payoutId}/confirm Acknowledge all `confirmations[]` atomically. # Create a payout Source: https://docs.openfx.com/v3/api-reference/payments/payouts/create-payout api-reference/openapi-v3-payments.json POST /v3/payments/payouts Create a payout, ordinarily in `REQUIRES_CONFIRMATION` (no funds moved until confirm). # Create a payout quote Source: https://docs.openfx.com/v3/api-reference/payments/payouts/create-payout-quote api-reference/openapi-v3-payments.json POST /v3/payments/payout-quotes Request a quote for a currency pair by specifying either the amount to send or the amount to receive. # Retrieve a payout Source: https://docs.openfx.com/v3/api-reference/payments/payouts/get-payout api-reference/openapi-v3-payments.json GET /v3/payments/payouts/{payoutId} Retrieve a payout. # List payouts Source: https://docs.openfx.com/v3/api-reference/payments/payouts/list-payouts api-reference/openapi-v3-payments.json GET /v3/payments/payouts Cursor list; each element a full Payout, not a summary row. # Create a withdrawal Source: https://docs.openfx.com/v3/api-reference/trade-settlement/create-withdrawal api-reference/openapi-v3.json POST /v3/fx/withdrawals Initiates a withdrawal to a verified withdrawal account. Pass a withdrawalAccountId from List withdrawal accounts. # Retrieve a deposit Source: https://docs.openfx.com/v3/api-reference/trade-settlement/get-deposit api-reference/openapi-v3.json GET /v3/fx/deposits/{id} Returns a single deposit by ID. # Retrieve a withdrawal Source: https://docs.openfx.com/v3/api-reference/trade-settlement/get-withdrawal api-reference/openapi-v3.json GET /v3/fx/withdrawals/{id} Returns a single withdrawal by ID. # List balances Source: https://docs.openfx.com/v3/api-reference/trade-settlement/list-balances api-reference/openapi-v3.json GET /v3/fx/balances Returns one entry per currency held, with available and total balances. # List deposits Source: https://docs.openfx.com/v3/api-reference/trade-settlement/list-deposits api-reference/openapi-v3.json GET /v3/fx/deposits Returns deposits to your account. Filter by `currency`. # List withdrawal accounts Source: https://docs.openfx.com/v3/api-reference/trade-settlement/list-withdrawal-accounts api-reference/openapi-v3.json GET /v3/fx/withdrawal-accounts Returns the withdrawal accounts on your account, in any status: fiat bank accounts and stablecoin wallets. Filter to verified accounts with `verified=true`. # List withdrawals Source: https://docs.openfx.com/v3/api-reference/trade-settlement/list-withdrawals api-reference/openapi-v3.json GET /v3/fx/withdrawals Returns withdrawals on your account. Fiat and stablecoin withdrawals appear in the same list. # Create a quote Source: https://docs.openfx.com/v3/api-reference/trade/create-quote api-reference/openapi-v3.json POST /v3/fx/quotes Locks a rate for a currency pair and amount, returning a quote id valid until expiresAt. # Execute a trade Source: https://docs.openfx.com/v3/api-reference/trade/execute-trade api-reference/openapi-v3.json POST /v3/fx/trades Executes a trade against a quote. Call this before the quotes expiresAt. # Generate a reverse quote Source: https://docs.openfx.com/v3/api-reference/trade/generate-reverse-quote api-reference/openapi-v3.json POST /v3/fx/trades/{id}/reverse-quote Creates a time-limited quote previewing the amounts and differential for reversing a trade. # Retrieve a quote Source: https://docs.openfx.com/v3/api-reference/trade/get-quote-by-id api-reference/openapi-v3.json GET /v3/fx/quotes/{id} Returns a single quote by ID, retrievable for 2 days after creation. Useful for audit, reconciliation, and verifying a quote has not been consumed. # Retrieve a trade Source: https://docs.openfx.com/v3/api-reference/trade/get-trade api-reference/openapi-v3.json GET /v3/fx/trades/{id} Returns a single trade by ID. # List currency pairs Source: https://docs.openfx.com/v3/api-reference/trade/list-currency-pairs api-reference/openapi-v3.json GET /v3/fx/pairs Returns every currency pair tradable on your account, with per-pair limits and supported directions. # List trades Source: https://docs.openfx.com/v3/api-reference/trade/list-trades api-reference/openapi-v3.json GET /v3/fx/trades Returns trades on your account. # Reverse a trade Source: https://docs.openfx.com/v3/api-reference/trade/reverse-trade api-reference/openapi-v3.json POST /v3/fx/trades/{id}/reverse Executes a reversal of a previously executed unsettled trade against a reverse quote. # Settle a trade Source: https://docs.openfx.com/v3/api-reference/trade/settle-trade api-reference/openapi-v3.json POST /v3/fx/trades/{id}/settle Settles a trade whose settlement is finalized out of band. # Authentication Source: https://docs.openfx.com/v3/authentication Mint ES256-signed JWT bearer tokens and ES256 request signatures to access the OpenFX API. OpenFX uses **ES256-signed JWT bearer tokens** plus a body-bound **`X-Request-Signature`** header for all v3 API access. The JWT carries identity and is **single-use** with a **60-second maximum TTL**; the request signature binds the call to that specific JWT, request method, path, query, and body. You mint both per request by signing with the `kid` and `privateKey` from the API key JSON you download from the [OpenFX dashboard](https://app.openfx.com). > [!WARNING] > > **Two breaks from older integrations: old code does not work unchanged.** > > 1. The JWT TTL ceiling drops to **60 seconds**: JWTs minted with `exp = iat + 120` now return `401` AUTH_TOKEN_INVALID_CONFIG. > 2. Every request now requires an **`X-Request-Signature`** ES256 signature header: calls without it are rejected with `401` AUTH_TOKEN_INVALID. > > Re-mint with the helpers below; the API key and key file format are unchanged. ## JWT shape A v3 JWT carries the claims and header values below. See [Mint a JWT and sign the request](#mint-a-jwt-and-sign-the-request) for how each language builds these. | Field | Where | Value | Notes | | - | - | - | - | | `aud` | claim | `["developer-api:v3"]` | Audience identifier; fixed string. | | `iss` | claim | `"openfx"` | Issuer; fixed string. | | `sub` | claim | `kid` from the API key JSON | Format: `org/{org-id}/apiKey/{api-key-id}`. | | `iat` | claim | seconds since epoch | Issued-at timestamp. | | `nbf` | claim | seconds since epoch | Not-before timestamp; usually equal to `iat`. | | `exp` | claim | `iat + 60` | **Max 60 seconds.** Larger values return AUTH_TOKEN_INVALID_CONFIG. | | `alg` | header | `"ES256"` | Only ES256 is accepted. | | `typ` | header | `"JWT"` | Fixed token-type header. | | `kid` | header | `kid` from the API key JSON | Key identifier; same value as `sub`. | | `nonce` | header | random UUID or 16 random bytes hex-encoded | Server-enforced unique for at least 80 seconds. Reuse → `401` AUTH_TOKEN_INVALID (with `details.reason: nonce_replay`). This same value goes into the request-signature canonical string (binds the signature to the JWT). | > [!WARNING] > > JWTs expire after 60 seconds. Mint a fresh one per request, not per session. Replaying a `nonce` is rejected with `401` AUTH_TOKEN_INVALID (`details.reason: nonce_replay`). Setting `exp - iat > 60 seconds` returns AUTH_TOKEN_INVALID_CONFIG. A missing `X-Request-Signature` header is likewise rejected with `401` AUTH_TOKEN_INVALID. ## API key scopes Selecting **Write** when you create an API key grants both read and write access, so you can also call GET endpoints with that key. Selecting **Read** grants read access only. `POST /v3/fx/quotes` requires read access even though it creates a quote; the other public POST operations require write access. A key without the required permission receives `403` AUTH_INSUFFICIENT_SCOPE. ## Request signing Every v3 request carries an **`X-Request-Signature`** header (an ES256 signature, IEEE P-1363 fixed 64-byte `r‖s` encoding, base64url-encoded) over the canonical string: ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} \n\n\n\n ``` | Component | How to build it | | - | - | | `METHOD` | Uppercase HTTP method (`GET`, `POST`). | | `CANONICAL_PATH` | Run the request path through the 7-step canonicalization below. | | `CANONICAL_QUERY` | Sort decoded parameters ascending by key, then value for repeated keys. Encode each pair with `encodeURIComponent` semantics (space → `%20`) and join with `&`. Empty when there are no parameters. | | `NONCE` | The **same** `nonce` value placed in the JWT header. Sharing this value between the JWT and the signature binds them together. A captured signature cannot be paired with a different JWT. | | `SHA256_HEX(body)` | Lowercase hex SHA-256 of the **raw request body bytes**. An empty body hashes to `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` (the hash of the empty string). | Sign the canonical string with the same API-key private key that signed the JWT. The server uses the JWT's `kid` to look up the matching public key and verifies both the JWT signature and the request signature against it. ### Path canonicalization (7 steps) Apply these steps in order before signing. The server applies the same canonicalization to the request path. 1. **Empty path becomes `/`.** 2. **Normalize percent-encoding** per RFC 3986 §6.2.2: decode unreserved octets (`%70` → `p`) and uppercase hex for reserved octets (`%2f` → `%2F`). 3. **Merge consecutive slashes** (`//a///b` → `/a/b`). 4. **Remove dot-segments** per RFC 3986 §5.2.4 (`/a/./b/../c` → `/a/c`). Encoded unreserved dots are normalized first, so `/a/%2E/b` becomes `/a/b`. 5. **Do NOT re-encode** any character that wasn't already encoded. 6. **Preserve case** (paths are case-sensitive). 7. **Preserve trailing slash** (`/a/` and `/a` are distinct). > [!WARNING] > > **Three failure modes you will hit if you skip canonicalization.** > > 1. `URL.pathname` (or its language equivalent) collapses dot-segments but does NOT merge `//`, so `https://api.openfx.com//v3/fx/pairs` signs `//v3/fx/pairs` while the server hashes `/v3/fx/pairs`. > 2. Re-serializing the JSON body between hashing and sending produces different bytes. The server's SHA-256 will not match. Serialize once and pass the same bytes to both the hasher and the HTTP client. > 3. Default ECDSA encoding in most languages is DER; the server expects IEEE P-1363 fixed 64-byte `r‖s`. Each sample below uses the language's idiomatic path to produce IEEE P-1363 output. Keep that setting; don't substitute the default. ### Why nonce reuse and body binding * **Same nonce in JWT and signature.** Reusing the JWT's `nonce` value as the signature nonce binds the two together. An attacker who exfiltrates a valid signature cannot pair it with a different JWT because the signature's canonical string includes the original JWT's `nonce`; verifying against a new JWT (with a new nonce) fails. * **Body binding.** Including `SHA256_HEX(body)` in the canonical string means a captured signature only authorizes the exact request it was signed for. Without this, a stolen bearer token could be paired with an attacker-chosen body until the JWT expired. * **Server-side nonce uniqueness.** The edge reserves each nonce atomically for 80 seconds after the request signature verifies. An invalid signature does not consume the nonce. Reusing a reserved nonce returns `401` AUTH_TOKEN_INVALID with `details.reason: nonce_replay`. ## Mint a JWT and sign the request Each sample mints a fresh 60s JWT and computes the matching `X-Request-Signature` in a single helper. Treat the helper as `signRequest({ method, url, body }) => { headers, body }`. Call it for every request, not once per session. ```javascript Node theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Mint a 60s ES256 JWT and compute the matching X-Request-Signature for OpenFX v3. const { sign: jwtSign } = require("jsonwebtoken"); const { createHash, createSign, randomUUID } = require("node:crypto"); // From the API key JSON downloaded in the dashboard. const KEY_NAME = "org/{org-id}/apiKey/{api-key-id}"; // `kid` const KEY_SECRET = "-----BEGIN PRIVATE KEY-----\nXXXX\n-----END PRIVATE KEY-----"; // `privateKey` // 7-step path canonicalization — see /v3/authentication#request-signing. const UNRESERVED_PATH_CHAR = /^[A-Za-z0-9._~-]$/; function canonicalizePath(rawPath) { if (!rawPath) return "/"; let path = rawPath.replace(/%[0-9A-Fa-f]{2}/g, (match) => { const char = String.fromCharCode(Number.parseInt(match.slice(1), 16)); return UNRESERVED_PATH_CHAR.test(char) ? char : match.toUpperCase(); }); // step 2: normalize percent-encoding path = path.replace(/\/{2,}/g, "/"); // step 3: merge // const hadTrailingSlash = path.length > 1 && path.endsWith("/"); const input = path.split("/"); const output = []; for (let i = 0; i < input.length; i++) { const seg = input[i]; if (seg === "" && i !== 0 && i !== input.length - 1) continue; if (seg === ".") continue; // step 4: drop "." if (seg === "..") { // step 4: pop ".." if (output.length > 1) output.pop(); continue; } output.push(seg); // steps 5,6: do not re-encode; preserve case } path = output.join("/"); if (path === "") path = "/"; // step 1 if (hadTrailingSlash && !path.endsWith("/")) path += "/"; // step 7 return path; } function canonicalizeQuery(params) { return [...params.entries()] .sort(([keyA, valueA], [keyB, valueB]) => keyA < keyB ? -1 : keyA > keyB ? 1 : valueA < valueB ? -1 : valueA > valueB ? 1 : 0, ) .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`) .join("&"); } // Mints a fresh JWT and computes the matching X-Request-Signature. Call this // for every request — both rotate together and must never be reused. function signRequest({ method, url, body }) { const now = Math.floor(Date.now() / 1000); const nonce = randomUUID(); // 1. Mint a 60s JWT. The header `nonce` is reused inside the signature canonical string. const jwt = jwtSign( { aud: ["developer-api:v3"], iss: "openfx", sub: KEY_NAME, iat: now, nbf: now, exp: now + 60, }, KEY_SECRET, { algorithm: "ES256", header: { alg: "ES256", typ: "JWT", kid: KEY_NAME, nonce }, }, ); // 2. Build the canonical string. const parsed = new URL(url); const canonicalPath = canonicalizePath(parsed.pathname); // Sort by byte/codepoint, NOT localeCompare — server uses raw comparison. const canonicalQuery = canonicalizeQuery(parsed.searchParams); const bodyBytes = body ?? ""; // serialize once: same bytes go to hasher and HTTP client const bodyHash = createHash("sha256").update(bodyBytes).digest("hex"); const canonical = [ method.toUpperCase(), canonicalPath, canonicalQuery, nonce, bodyHash, ].join("\n"); // 3. Sign with IEEE P-1363 (fixed 64-byte r‖s) — NOT DER. const signer = createSign("SHA256"); signer.update(canonical); signer.end(); const signature = signer .sign({ key: KEY_SECRET, dsaEncoding: "ieee-p1363" }) .toString("base64url"); return { headers: { Authorization: `Bearer ${jwt}`, "X-Request-Signature": signature, "Content-Type": "application/json", "X-App-Mode": "SANDBOX", // use "LIVE" with a Live key }, body: bodyBytes, }; } module.exports = { signRequest, canonicalizePath, canonicalizeQuery }; if (require.main === module) { const { headers } = signRequest({ method: "GET", url: "https://api.openfx.com/v3/fx/pairs", }); console.log(headers); } ``` ```python Python theme={"theme":{"light":"poimandres","dark":"poimandres"}} """Mint a 60s ES256 JWT and compute the matching X-Request-Signature for OpenFX v3.""" import base64 import hashlib import re import secrets import time from typing import Optional, Tuple from urllib.parse import urlsplit, parse_qsl, quote import jwt from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature # From the API key JSON downloaded in the dashboard. KEY_NAME = "org/{org-id}/apiKey/{api-key-id}" # `kid` KEY_SECRET_PEM = b"-----BEGIN PRIVATE KEY-----\nXXXX\n-----END PRIVATE KEY-----" # `privateKey` def canonicalize_path(raw_path: str) -> str: """7-step path canonicalization. See /v3/authentication#request-signing.""" if not raw_path: return "/" unreserved = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") raw_path = re.sub( r"%[0-9A-Fa-f]{2}", lambda match: ( chr(int(match.group()[1:], 16)) if chr(int(match.group()[1:], 16)) in unreserved else match.group().upper() ), raw_path, ) # step 2: decode unreserved octets and uppercase reserved escapes while "//" in raw_path: # step 3: merge consecutive slashes raw_path = raw_path.replace("//", "/") had_trailing = len(raw_path) > 1 and raw_path.endswith("/") segments = raw_path.split("/") out: list[str] = [] for i, seg in enumerate(segments): if seg == "" and i not in (0, len(segments) - 1): continue if seg == ".": # step 4 continue if seg == "..": # step 4 if len(out) > 1: out.pop() continue out.append(seg) # steps 5,6: do not re-encode; preserve case path = "/".join(out) or "/" if had_trailing and not path.endswith("/"): # step 7 path += "/" return path def canonicalize_query(params: list[tuple[str, str]]) -> str: """Sort decoded query entries by key then value before percent-encoding.""" params = sorted(params, key=lambda kv: (kv[0], kv[1])) safe_chars = "~!*'()" return "&".join(f"{quote(k, safe=safe_chars)}={quote(v, safe=safe_chars)}" for k, v in params) def _sign_es256_p1363(private_key, message: bytes) -> bytes: """ES256 sign producing IEEE P-1363 fixed 64-byte r‖s output. cryptography returns DER by default; decode and concat r,s as fixed-width big-endian. """ der_sig = private_key.sign(message, ec.ECDSA(hashes.SHA256())) r, s = decode_dss_signature(der_sig) return r.to_bytes(32, "big") + s.to_bytes(32, "big") def sign_request( method: str, url: str, body: Optional[bytes] = None ) -> Tuple[dict, bytes]: """Mints a fresh JWT and computes the matching X-Request-Signature. Call this for every request — both rotate together and must never be reused.""" body_bytes = body or b"" # serialize once: same bytes to hasher and HTTP client now = int(time.time()) nonce = secrets.token_hex(16) # 1. Mint a 60s JWT. Header `nonce` is reused inside the signature canonical string. payload = { "aud": ["developer-api:v3"], "iss": "openfx", "sub": KEY_NAME, "iat": now, "nbf": now, "exp": now + 60, } jwt_token = jwt.encode( payload, KEY_SECRET_PEM, algorithm="ES256", headers={"alg": "ES256", "typ": "JWT", "kid": KEY_NAME, "nonce": nonce}, ) # 2. Build canonical string. parsed = urlsplit(url) canonical_path = canonicalize_path(parsed.path) params = parse_qsl(parsed.query, keep_blank_values=True) canonical_query = canonicalize_query(params) body_hash = hashlib.sha256(body_bytes).hexdigest() canonical = "\n".join( [method.upper(), canonical_path, canonical_query, nonce, body_hash] ).encode("utf-8") # 3. ES256 sign producing IEEE P-1363 fixed 64-byte r‖s — NOT DER. private_key = serialization.load_pem_private_key(KEY_SECRET_PEM, password=None) sig_p1363 = _sign_es256_p1363(private_key, canonical) signature = base64.urlsafe_b64encode(sig_p1363).rstrip(b"=").decode("ascii") headers = { "Authorization": f"Bearer {jwt_token}", "X-Request-Signature": signature, "Content-Type": "application/json", "X-App-Mode": "SANDBOX", # use "LIVE" with a Live key } return headers, body_bytes if __name__ == "__main__": headers, _ = sign_request("GET", "https://api.openfx.com/v3/fx/pairs") print(headers) ``` ```java Java theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Mint a 60s ES256 JWT and compute the matching X-Request-Signature for OpenFX v3. // Uses only the built-in JDK security APIs — no external dependency. import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.KeyFactory; import java.security.Signature; import java.security.interfaces.ECPrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import java.time.Instant; import java.util.*; public class SignRequest { // From the API key JSON downloaded in the dashboard. static final String KEY_NAME = "org/{org-id}/apiKey/{api-key-id}"; // `kid` static final String KEY_SECRET_PEM = "-----BEGIN PRIVATE KEY-----\nXXXX\n-----END PRIVATE KEY-----"; // `privateKey` public static void main(String[] args) throws Exception { Map headers = signRequest( "GET", "https://api.openfx.com/v3/fx/pairs", new byte[0]); System.out.println(headers); } /** 7-step path canonicalization. See /v3/authentication#request-signing. */ static String canonicalizePath(String rawPath) { if (rawPath == null || rawPath.isEmpty()) return "/"; StringBuilder normalized = new StringBuilder(); for (int i = 0; i < rawPath.length(); i++) { if (rawPath.charAt(i) == '%' && i + 2 < rawPath.length()) { int high = Character.digit(rawPath.charAt(i + 1), 16); int low = Character.digit(rawPath.charAt(i + 2), 16); if (high >= 0 && low >= 0) { char decoded = (char) ((high << 4) | low); if (isUnreserved(decoded)) normalized.append(decoded); else normalized.append('%').append(Character.toUpperCase(rawPath.charAt(i + 1))) .append(Character.toUpperCase(rawPath.charAt(i + 2))); i += 2; continue; } } normalized.append(rawPath.charAt(i)); } rawPath = normalized.toString(); // step 2: normalize percent-encoding before dot-segment removal while (rawPath.contains("//")) rawPath = rawPath.replace("//", "/"); // step 3 boolean hadTrailing = rawPath.length() > 1 && rawPath.endsWith("/"); String[] segments = rawPath.split("/"); List out = new ArrayList<>(); for (int i = 0; i < segments.length; i++) { String seg = segments[i]; if (seg.isEmpty() && i != 0 && i != segments.length - 1) continue; if (seg.equals(".")) continue; // step 4 if (seg.equals("..")) { // step 4 if (out.size() > 1) out.remove(out.size() - 1); continue; } out.add(seg); // steps 5,6: do not re-encode; preserve case } String path = String.join("/", out); if (path.isEmpty()) path = "/"; if (hadTrailing && !path.endsWith("/")) path += "/"; // step 7 return path; } private static boolean isUnreserved(char c) { return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~'; } static String canonicalizeQuery(String rawQuery) throws Exception { if (rawQuery == null || rawQuery.isEmpty()) return ""; List> params = new ArrayList<>(); for (String pair : rawQuery.split("&", -1)) { if (pair.isEmpty()) continue; int equals = pair.indexOf('='); String key = equals < 0 ? pair : pair.substring(0, equals); String value = equals < 0 ? "" : pair.substring(equals + 1); params.add(new AbstractMap.SimpleImmutableEntry<>( URLDecoder.decode(key, StandardCharsets.UTF_8), URLDecoder.decode(value, StandardCharsets.UTF_8))); } params.sort(Map.Entry.comparingByKey().thenComparing(Map.Entry::getValue)); List encoded = new ArrayList<>(); for (Map.Entry param : params) { encoded.add(pctEncode(param.getKey()) + "=" + pctEncode(param.getValue())); } return String.join("&", encoded); } static ECPrivateKey loadPrivateKey(String pem) throws Exception { String cleaned = pem.replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replaceAll("\\s", ""); byte[] der = Base64.getDecoder().decode(cleaned); KeyFactory kf = KeyFactory.getInstance("EC"); return (ECPrivateKey) kf.generatePrivate(new PKCS8EncodedKeySpec(der)); } /** RFC 3986 percent-encoding. URLEncoder.encode is form-urlencoded * (space -> "+"); the spec requires "%20". */ static String pctEncode(String s) { final char[] hex = "0123456789ABCDEF".toCharArray(); StringBuilder encoded = new StringBuilder(); for (byte raw : s.getBytes(StandardCharsets.UTF_8)) { int c = raw & 0xff; if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') { encoded.append((char) c); } else { encoded.append('%').append(hex[c >>> 4]).append(hex[c & 0x0f]); } } return encoded.toString(); } static String base64UrlNoPad(byte[] bytes) { return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } /** ES256 sign producing IEEE P-1363 fixed 64-byte r‖s — NOT DER. */ static byte[] signEs256P1363(ECPrivateKey key, byte[] message) throws Exception { Signature sig = Signature.getInstance("SHA256withECDSA"); sig.initSign(key); sig.update(message); return derToP1363(sig.sign()); } static byte[] derToP1363(byte[] der) { int offset = 2; // SEQUENCE tag + length offset++; // INTEGER tag int rLen = der[offset++] & 0xff; byte[] r = Arrays.copyOfRange(der, offset, offset + rLen); offset += rLen; offset++; // INTEGER tag int sLen = der[offset++] & 0xff; byte[] s = Arrays.copyOfRange(der, offset, offset + sLen); byte[] out = new byte[64]; System.arraycopy(toFixed32(r), 0, out, 0, 32); System.arraycopy(toFixed32(s), 0, out, 32, 32); return out; } static byte[] toFixed32(byte[] value) { int start = 0; while (start < value.length - 32 && value[start] == 0) start++; byte[] trimmed = Arrays.copyOfRange(value, start, value.length); if (trimmed.length == 32) return trimmed; byte[] out = new byte[32]; System.arraycopy(trimmed, 0, out, 32 - trimmed.length, trimmed.length); return out; } static String signJwtEs256(String keyName, ECPrivateKey key, String nonce, long now) throws Exception { String headerJson = "{\"alg\":\"ES256\",\"typ\":\"JWT\",\"kid\":\"" + keyName + "\",\"nonce\":\"" + nonce + "\"}"; String payloadJson = "{\"aud\":[\"developer-api:v3\"],\"iss\":\"openfx\",\"sub\":\"" + keyName + "\",\"iat\":" + now + ",\"nbf\":" + now + ",\"exp\":" + (now + 60) + "}"; String encodedHeader = base64UrlNoPad(headerJson.getBytes(StandardCharsets.UTF_8)); String encodedPayload = base64UrlNoPad(payloadJson.getBytes(StandardCharsets.UTF_8)); String signingInput = encodedHeader + "." + encodedPayload; byte[] sig = signEs256P1363(key, signingInput.getBytes(StandardCharsets.UTF_8)); return signingInput + "." + base64UrlNoPad(sig); } /** Mints a fresh JWT and computes the matching X-Request-Signature. Call this * for every request — both rotate together and must never be reused. */ static Map signRequest(String method, String urlStr, byte[] body) throws Exception { long now = Instant.now().getEpochSecond(); byte[] nonceBytes = new byte[16]; new java.security.SecureRandom().nextBytes(nonceBytes); StringBuilder nonceHex = new StringBuilder(); for (byte b : nonceBytes) nonceHex.append(String.format("%02x", b)); String nonce = nonceHex.toString(); ECPrivateKey key = loadPrivateKey(KEY_SECRET_PEM); String jwtToken = signJwtEs256(KEY_NAME, key, nonce, now); URI uri = URI.create(urlStr); String canonicalPath = canonicalizePath(uri.getRawPath()); String canonicalQuery = canonicalizeQuery(uri.getRawQuery()); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); byte[] bodyHashBytes = sha256.digest(body); StringBuilder bodyHashHex = new StringBuilder(); for (byte b : bodyHashBytes) bodyHashHex.append(String.format("%02x", b)); String canonical = String.join("\n", method.toUpperCase(), canonicalPath, canonicalQuery, nonce, bodyHashHex.toString()); byte[] sigP1363 = signEs256P1363(key, canonical.getBytes(StandardCharsets.UTF_8)); String signature = base64UrlNoPad(sigP1363); Map headers = new LinkedHashMap<>(); headers.put("Authorization", "Bearer " + jwtToken); headers.put("X-Request-Signature", signature); headers.put("Content-Type", "application/json"); headers.put("X-App-Mode", "SANDBOX"); // use "LIVE" with a Live key return headers; } } ``` ```cpp C++ theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Mint a 60s ES256 JWT and compute the matching X-Request-Signature for OpenFX v3. // Requires OpenSSL. On macOS with Homebrew, add -I/opt/homebrew/include // -L/opt/homebrew/lib (Apple Silicon) or -I/usr/local/include -L/usr/local/lib // (Intel) — OpenSSL headers aren't on the default search path there. #include #include #include #include #include #include #include #include #include #include #include #include #include #include struct SignedRequest { std::string authHeader; std::string sigHeader; }; // From the API key JSON downloaded in the dashboard. static const char* KEY_NAME = "org/{org-id}/apiKey/{api-key-id}"; // `kid` static const char* KEY_SECRET_PEM = "-----BEGIN PRIVATE KEY-----\nXXXX\n-----END PRIVATE KEY-----"; // `privateKey` std::string b64url(const unsigned char* data, size_t len) { static const char* tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string out; int val = 0, valb = -6; for (size_t i = 0; i < len; i++) { val = (val << 8) + data[i]; valb += 8; while (valb >= 0) { out.push_back(tbl[(val >> valb) & 0x3F]); valb -= 6; } } if (valb > -6) out.push_back(tbl[((val << 8) >> (valb + 8)) & 0x3F]); for (auto& c : out) { if (c == '+') c = '-'; if (c == '/') c = '_'; } return out; } std::string b64url(const std::string& s) { return b64url(reinterpret_cast(s.data()), s.size()); } // RFC 3986 percent-encoding: unreserved chars pass through unescaped, // everything else becomes %XX (uppercase hex) — including space as %20, // never "+". std::string pctEncode(const std::string& s) { static const char* hex = "0123456789ABCDEF"; std::string out; for (unsigned char c : s) { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') { out.push_back((char)c); } else { out.push_back('%'); out.push_back(hex[(c >> 4) & 0xF]); out.push_back(hex[c & 0xF]); } } return out; } int hexValue(unsigned char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; return -1; } std::string pctDecode(const std::string& value) { std::string out; for (size_t i = 0; i < value.size(); i++) { if (value[i] == '+') { out.push_back(' '); } else if (value[i] == '%' && i + 2 < value.size()) { int high = hexValue(static_cast(value[i + 1])); int low = hexValue(static_cast(value[i + 2])); if (high >= 0 && low >= 0) { out.push_back(static_cast((high << 4) | low)); i += 2; } else { out.push_back(value[i]); } } else { out.push_back(value[i]); } } return out; } // Sort the query parameters ascending by key and percent-encode each // key=value pair. See /v3/authentication#request-signing. std::string buildCanonicalQuery(const std::string& query) { if (query.empty()) return ""; std::vector> pairs; size_t start = 0; while (start <= query.size()) { size_t amp = query.find('&', start); std::string pair = query.substr(start, amp == std::string::npos ? std::string::npos : amp - start); size_t eq = pair.find('='); if (eq == std::string::npos) { pairs.push_back({pctDecode(pair), ""}); } else { pairs.push_back({pctDecode(pair.substr(0, eq)), pctDecode(pair.substr(eq + 1))}); } if (amp == std::string::npos) break; start = amp + 1; } std::sort(pairs.begin(), pairs.end(), [] (const auto& a, const auto& b) { return a.first < b.first || (a.first == b.first && a.second < b.second); }); std::string out; for (size_t i = 0; i < pairs.size(); i++) { if (i > 0) out += "&"; out += pctEncode(pairs[i].first) + "=" + pctEncode(pairs[i].second); } return out; } std::string sha256hex(const std::string& data) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256(reinterpret_cast(data.data()), data.size(), hash); std::ostringstream oss; for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) oss << std::hex << std::setfill('0') << std::setw(2) << (int)hash[i]; return oss.str(); } // 7-step path canonicalization. See /v3/authentication#request-signing. std::string canonicalizePath(std::string rawPath) { if (rawPath.empty()) return "/"; std::string normalized; for (size_t i = 0; i < rawPath.size(); i++) { if (rawPath[i] == '%' && i + 2 < rawPath.size()) { int high = hexValue(static_cast(rawPath[i + 1])); int low = hexValue(static_cast(rawPath[i + 2])); if (high >= 0 && low >= 0) { unsigned char decoded = static_cast((high << 4) | low); bool unreserved = (decoded >= 'A' && decoded <= 'Z') || (decoded >= 'a' && decoded <= 'z') || (decoded >= '0' && decoded <= '9') || decoded == '-' || decoded == '.' || decoded == '_' || decoded == '~'; if (unreserved) { normalized.push_back(static_cast(decoded)); } else { static const char* hex = "0123456789ABCDEF"; normalized.push_back('%'); normalized.push_back(hex[(decoded >> 4) & 0xF]); normalized.push_back(hex[decoded & 0xF]); } i += 2; continue; } } normalized.push_back(rawPath[i]); } rawPath = normalized; // step 2: normalize percent-encoding before dot-segment removal size_t pos; while ((pos = rawPath.find("//")) != std::string::npos) rawPath.replace(pos, 2, "/"); // step 3 bool hadTrailing = rawPath.size() > 1 && rawPath.back() == '/'; std::vector raw; { std::string tmp; for (char c : rawPath) { if (c == '/') { raw.push_back(tmp); tmp.clear(); } else tmp += c; } raw.push_back(tmp); } std::vector out; for (size_t i = 0; i < raw.size(); i++) { const std::string& s = raw[i]; if (s.empty() && i != 0 && i != raw.size() - 1) continue; if (s == ".") continue; // step 4 if (s == "..") { if (out.size() > 1) out.pop_back(); continue; } // step 4 out.push_back(s); // steps 5,6: do not re-encode; preserve case } std::string path; for (size_t i = 0; i < out.size(); i++) { path += out[i]; if (i + 1 < out.size()) path += "/"; } if (path.empty()) path = "/"; if (hadTrailing && (path.empty() || path.back() != '/')) path += "/"; // step 7 return path; } // ES256 sign producing IEEE P-1363 fixed 64-byte r‖s — NOT DER. std::vector signEs256P1363(EVP_PKEY* pkey, const std::string& message) { EVP_MD_CTX* ctx = EVP_MD_CTX_new(); if (!ctx) { throw std::runtime_error("Could not allocate EVP_MD_CTX."); } EVP_DigestSignInit(ctx, nullptr, EVP_sha256(), nullptr, pkey); EVP_DigestSignUpdate(ctx, message.data(), message.size()); size_t sigLen = 0; EVP_DigestSignFinal(ctx, nullptr, &sigLen); std::vector der(sigLen); EVP_DigestSignFinal(ctx, der.data(), &sigLen); EVP_MD_CTX_free(ctx); const unsigned char* p = der.data(); ECDSA_SIG* sig = d2i_ECDSA_SIG(nullptr, &p, (long)sigLen); if (!sig) { throw std::runtime_error("Could not parse the DER-encoded ECDSA signature."); } const BIGNUM* r; const BIGNUM* s; ECDSA_SIG_get0(sig, &r, &s); std::vector out(64, 0); BN_bn2binpad(r, out.data(), 32); BN_bn2binpad(s, out.data() + 32, 32); ECDSA_SIG_free(sig); return out; } EVP_PKEY* loadPrivateKey(const std::string& pem) { BIO* bio = BIO_new_mem_buf(pem.data(), (int)pem.size()); if (!bio) { throw std::runtime_error("Could not allocate BIO for the private key PEM."); } EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr); BIO_free(bio); if (!pkey) { throw std::runtime_error( "Could not parse the private key PEM. Replace KEY_SECRET_PEM with the " "real `privateKey` value from your API key JSON."); } return pkey; } static std::string signJwtEs256(const std::string& keyName, EVP_PKEY* pkey, const std::string& nonce, long now) { std::ostringstream headerJson; headerJson << "{\"alg\":\"ES256\",\"typ\":\"JWT\",\"kid\":\"" << keyName << "\",\"nonce\":\"" << nonce << "\"}"; std::ostringstream payloadJson; payloadJson << "{\"aud\":[\"developer-api:v3\"],\"iss\":\"openfx\",\"sub\":\"" << keyName << "\",\"iat\":" << now << ",\"nbf\":" << now << ",\"exp\":" << (now + 60) << "}"; std::string encHeader = b64url(headerJson.str()); std::string encPayload = b64url(payloadJson.str()); std::string signingInput = encHeader + "." + encPayload; auto sig = signEs256P1363(pkey, signingInput); return signingInput + "." + b64url(sig.data(), sig.size()); } // Mints a fresh JWT and computes the matching X-Request-Signature. Call this // for every request — both rotate together and must never be reused. SignedRequest signRequest(const std::string& method, const std::string& urlPath, const std::string& query, const std::string& body) { EVP_PKEY* pkey = loadPrivateKey(KEY_SECRET_PEM); auto now = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()).count(); unsigned char nonceBytes[16]; RAND_bytes(nonceBytes, 16); std::ostringstream nonceHex; for (int i = 0; i < 16; i++) nonceHex << std::hex << std::setfill('0') << std::setw(2) << (int)nonceBytes[i]; std::string nonce = nonceHex.str(); std::string jwt = signJwtEs256(KEY_NAME, pkey, nonce, now); std::string canonicalPath = canonicalizePath(urlPath); std::string canonicalQuery = buildCanonicalQuery(query); std::string bodyHash = sha256hex(body); std::string canonical = method + "\n" + canonicalPath + "\n" + canonicalQuery + "\n" + nonce + "\n" + bodyHash; auto reqSig = signEs256P1363(pkey, canonical); std::string signature = b64url(reqSig.data(), reqSig.size()); EVP_PKEY_free(pkey); return { "Bearer " + jwt, signature }; } #ifndef SIGN_REQUEST_NO_MAIN int main() { try { SignedRequest req = signRequest("GET", "/v3/fx/pairs", "", ""); std::cout << "Authorization: " << req.authHeader << std::endl; std::cout << "X-Request-Signature: " << req.sigHeader << std::endl; std::cout << "X-App-Mode: " << "SANDBOX" << std::endl; // use "LIVE" with a Live key return 0; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } #endif ``` ```go Go theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Mint a 60s ES256 JWT and compute the matching X-Request-Signature for OpenFX v3. package auth import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/hex" "encoding/pem" "fmt" "net/url" "sort" "strconv" "strings" "time" "github.com/golang-jwt/jwt/v5" ) // From the API key JSON downloaded in the dashboard. const ( KeyName = "org/{org-id}/apiKey/{api-key-id}" // `kid` KeySecretPEM = "-----BEGIN PRIVATE KEY-----\nXXXX\n-----END PRIVATE KEY-----" // `privateKey` ) // SignedRequest carries the headers and body bytes to send. type SignedRequest struct { Headers map[string]string Body []byte } // CanonicalizePath performs the 7-step path canonicalization documented at // /v3/authentication#request-signing. func CanonicalizePath(raw string) string { if raw == "" { return "/" } var normalized strings.Builder for i := 0; i < len(raw); i++ { if raw[i] == '%' && i+2 < len(raw) { decoded, err := strconv.ParseUint(raw[i+1:i+3], 16, 8) if err == nil { b := byte(decoded) if b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z' || b >= '0' && b <= '9' || strings.ContainsRune("-._~", rune(b)) { normalized.WriteByte(b) } else { normalized.WriteString(strings.ToUpper(raw[i : i+3])) } i += 2 continue } } normalized.WriteByte(raw[i]) } raw = normalized.String() // step 2: normalize percent-encoding before dot-segment removal for strings.Contains(raw, "//") { // step 3 raw = strings.ReplaceAll(raw, "//", "/") } hadTrailing := len(raw) > 1 && strings.HasSuffix(raw, "/") segments := strings.Split(raw, "/") out := make([]string, 0, len(segments)) for i, seg := range segments { if seg == "" && i != 0 && i != len(segments)-1 { continue } if seg == "." { // step 4 continue } if seg == ".." { // step 4 if len(out) > 1 { out = out[:len(out)-1] } continue } out = append(out, seg) // steps 5,6: do not re-encode; preserve case } path := strings.Join(out, "/") if path == "" { path = "/" } if hadTrailing && !strings.HasSuffix(path, "/") { // step 7 path += "/" } return path } func parsePrivateKey(pemStr string) (*ecdsa.PrivateKey, error) { block, _ := pem.Decode([]byte(pemStr)) if block == nil { return nil, fmt.Errorf("no PEM block found — replace KeySecretPEM with your real privateKey") } k, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("parse private key: %w", err) } ecKey, ok := k.(*ecdsa.PrivateKey) if !ok { return nil, fmt.Errorf("not an ECDSA key") } return ecKey, nil } func pctEncode(s string) string { const hex = "0123456789ABCDEF" var encoded strings.Builder for i := 0; i < len(s); i++ { c := s[i] if c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.ContainsRune("-_.!~*'()", rune(c)) { encoded.WriteByte(c) } else { encoded.WriteByte('%') encoded.WriteByte(hex[c>>4]) encoded.WriteByte(hex[c&0x0F]) } } return encoded.String() } func buildCanonicalQuery(values url.Values) string { type queryPair struct{ key, value string } pairs := make([]queryPair, 0, len(values)) for key, vals := range values { for _, value := range vals { pairs = append(pairs, queryPair{key: key, value: value}) } } sort.Slice(pairs, func(i, j int) bool { if pairs[i].key == pairs[j].key { return pairs[i].value < pairs[j].value } return pairs[i].key < pairs[j].key }) parts := make([]string, 0, len(pairs)) for _, pair := range pairs { parts = append(parts, pctEncode(pair.key)+"="+pctEncode(pair.value)) } return strings.Join(parts, "&") } // SignRequest mints a fresh JWT and computes the matching X-Request-Signature. // Call this for every request — both rotate together and must never be reused. func SignRequest(method, rawURL string, body []byte) (*SignedRequest, error) { privateKey, err := parsePrivateKey(KeySecretPEM) if err != nil { return nil, fmt.Errorf("parse private key: %w", err) } nonceBytes := make([]byte, 16) if _, err := rand.Read(nonceBytes); err != nil { return nil, fmt.Errorf("nonce: %w", err) } nonce := hex.EncodeToString(nonceBytes) now := time.Now().Unix() // 1. Mint a 60s JWT. claims := jwt.MapClaims{ "aud": []string{"developer-api:v3"}, "iss": "openfx", "sub": KeyName, "iat": now, "nbf": now, "exp": now + 60, } token := jwt.NewWithClaims(jwt.SigningMethodES256, claims) token.Header["kid"] = KeyName token.Header["nonce"] = nonce jwtStr, err := token.SignedString(privateKey) if err != nil { return nil, fmt.Errorf("sign jwt: %w", err) } // 2. Build canonical string. parsed, err := url.Parse(rawURL) if err != nil { return nil, fmt.Errorf("parse url: %w", err) } canonicalPath := CanonicalizePath(parsed.EscapedPath()) canonicalQuery := buildCanonicalQuery(parsed.Query()) bodyHashBytes := sha256.Sum256(body) bodyHashHex := hex.EncodeToString(bodyHashBytes[:]) canonical := strings.Join([]string{ strings.ToUpper(method), canonicalPath, canonicalQuery, nonce, bodyHashHex, }, "\n") // 3. ES256 sign producing IEEE P-1363 fixed 64-byte r||s — NOT DER. sigP1363, err := signEs256P1363(privateKey, []byte(canonical)) if err != nil { return nil, err } signature := base64.RawURLEncoding.EncodeToString(sigP1363) return &SignedRequest{ Headers: map[string]string{ "Authorization": "Bearer " + jwtStr, "X-Request-Signature": signature, "Content-Type": "application/json", "X-App-Mode": "SANDBOX", // use "LIVE" with a Live key }, Body: body, }, nil } func signEs256P1363(privateKey *ecdsa.PrivateKey, message []byte) ([]byte, error) { digest := sha256.Sum256(message) r, s, err := ecdsa.Sign(rand.Reader, privateKey, digest[:]) if err != nil { return nil, fmt.Errorf("ecdsa sign: %w", err) } curveBytes := (privateKey.Curve.Params().BitSize + 7) / 8 // 32 for P-256 sig := make([]byte, 2*curveBytes) r.FillBytes(sig[:curveBytes]) s.FillBytes(sig[curveBytes:]) return sig, nil } ``` ```javascript Postman theme={"theme":{"light":"poimandres","dark":"poimandres"}} // OpenFX v3 authentication — Postman pre-request script. // Paste into a collection's Pre-request Script tab. Mints a 60s ES256 JWT // and computes the matching X-Request-Signature before every request. // Collection variables: KEY_NAME, KEY_SECRET (PEM, newlines escaped as \n). // Optional: APP_MODE (defaults to SANDBOX). const { sign: jwtSign } = pm.require("npm:jsonwebtoken@8.5.1"); const { ec: EC } = pm.require("npm:elliptic@6.6.1"); const brorand = pm.require("npm:brorand@1.1.0"); const keyName = pm.collectionVariables.get("KEY_NAME"); const keySecret = pm.collectionVariables .get("KEY_SECRET") .replace(/\\n/g, "\n"); const appMode = pm.collectionVariables.get("APP_MODE") || "SANDBOX"; const now = Math.floor(Date.now() / 1000); const nonce = Buffer.from(brorand(16)).toString("hex"); // 32 hex chars // 1. Mint a 60s JWT (v3's max — not the 120s used on v1/v2) with the PEM key. // The header `nonce` is reused inside the signature's canonical string below. const jwt = jwtSign( { aud: ["developer-api:v3"], iss: "openfx", sub: keyName, iat: now, nbf: now, exp: now + 60, }, keySecret, { algorithm: "ES256", header: { alg: "ES256", typ: "JWT", kid: keyName, nonce }, }, ); // 2. Build the canonical string: METHOD\nPATH\nQUERY\nNONCE\nSHA256_HEX(body). // Resolve the complete URL first so path segments in BASE_URL are included. // Canonicalization must match the path and query the server receives. const method = pm.request.method.toUpperCase(); const requestUrl = new URL(pm.variables.replaceIn(pm.request.url.toString())); const canonicalPath = canonicalizePath(requestUrl.pathname); const canonicalQuery = pm.request.url.query .all() .filter((p) => !p.disabled) .map((p) => [ pm.variables.replaceIn(p.key), pm.variables.replaceIn(p.value ?? ""), ]) .sort(([keyA, valueA], [keyB, valueB]) => keyA < keyB ? -1 : keyA > keyB ? 1 : valueA < valueB ? -1 : valueA > valueB ? 1 : 0, ) .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) .join("&"); const bodyRaw = pm.variables.replaceIn( (pm.request.body && pm.request.body.raw) || "", ); const bodyHash = CryptoJS.SHA256(bodyRaw).toString(); const canonical = [ method, canonicalPath, canonicalQuery, nonce, bodyHash, ].join("\n"); function canonicalizePath(rawPath) { if (!rawPath) return "/"; let path = rawPath.replace(/%[0-9A-Fa-f]{2}/g, (match) => { const char = String.fromCharCode(Number.parseInt(match.slice(1), 16)); return /^[A-Za-z0-9._~-]$/.test(char) ? char : match.toUpperCase(); }); path = path.replace(/\/{2,}/g, "/"); const hadTrailingSlash = path.length > 1 && path.endsWith("/"); const input = path.split("/"); const output = []; for (let i = 0; i < input.length; i++) { const segment = input[i]; if (segment === "" && i !== 0 && i !== input.length - 1) continue; if (segment === ".") continue; if (segment === "..") { if (output.length > 1) output.pop(); continue; } output.push(segment); } path = output.join("/"); if (path === "") path = "/"; if (hadTrailingSlash && !path.endsWith("/")) path += "/"; return path; } // 3. Extract the raw private-key scalar from the PKCS8 PEM. A P-256 PKCS8 // key is: SEQUENCE { version, AlgorithmIdentifier, OCTET STRING { SEQUENCE { // version, OCTET STRING <32-byte scalar>, ... } } } — this reads only the // two SEQUENCE/OCTET STRING pairs needed to reach that scalar and never // looks at the (optional, ignored either way) trailing curve/public-key // fields, so it doesn't matter whether your key file includes them. function derReadTLV(buf, offset) { const tag = buf[offset]; const lenByte = buf[offset + 1]; let lenOfLen = 0; let length; if (lenByte & 0x80) { lenOfLen = lenByte & 0x7f; length = 0; for (let i = 0; i < lenOfLen; i++) length = (length << 8) | buf[offset + 2 + i]; } else { length = lenByte; } const valueStart = offset + 2 + lenOfLen; const valueEnd = valueStart + length; return { tag, valueStart, valueEnd, nextOffset: valueEnd }; } function extractEcPrivateScalar(pem) { const base64 = pem .split("\n") .map((line) => line.trim()) .filter((line) => line && !line.startsWith("-----")) .join(""); const der = Buffer.from(base64, "base64"); let tlv = derReadTLV(der, 0); // outer SEQUENCE (PrivateKeyInfo) let offset = tlv.valueStart; tlv = derReadTLV(der, offset); // version INTEGER offset = tlv.nextOffset; tlv = derReadTLV(der, offset); // AlgorithmIdentifier SEQUENCE — skip over offset = tlv.nextOffset; tlv = derReadTLV(der, offset); // privateKey OCTET STRING, wraps ECPrivateKey DER const ecDer = der.subarray(tlv.valueStart, tlv.valueEnd); let inner = derReadTLV(ecDer, 0); // ECPrivateKey SEQUENCE let innerOffset = inner.valueStart; inner = derReadTLV(ecDer, innerOffset); // version INTEGER innerOffset = inner.nextOffset; inner = derReadTLV(ecDer, innerOffset); // privateKey OCTET STRING — the raw scalar const scalar = ecDer.subarray(inner.valueStart, inner.valueEnd); // DER integers can be shorter than 32 bytes (leading zero bytes are // dropped) or, rarely, 33 with a leading 0x00 padding byte; normalize to // exactly 32 bytes either way. return Buffer.concat([Buffer.alloc(32), scalar]).subarray(-32); } // 4. Sign SHA-256(canonical) with the extracted scalar. const ec = new EC("p256"); const keyPair = ec.keyFromPrivate(extractEcPrivateScalar(keySecret)); const digestHex = CryptoJS.SHA256(canonical).toString(); const sig = keyPair.sign(digestHex, { canonical: true }); // Postman's Buffer polyfill may not recognize the "base64url" encoding // name, so base64url is handled by hand (base64 + character substitution) // rather than relying on it directly. const signature = Buffer.concat([ sig.r.toArrayLike(Buffer, "be", 32), sig.s.toArrayLike(Buffer, "be", 32), ]) .toString("base64") .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); // 5. Attach headers. upsert (not add) so re-running the script doesn't // stack duplicate headers. pm.request.headers.upsert({ key: "Authorization", value: `Bearer ${jwt}` }); pm.request.headers.upsert({ key: "X-Request-Signature", value: signature, }); pm.request.headers.upsert({ key: "X-App-Mode", value: appMode }); ``` > [!NOTE] > > Retrieve the key ID and private key from the `kid`/`privateKey` > parameters in the API key JSON. For **Postman**, paste the script into your > collection's **Pre-request Script**, then define `BASE_URL`, `APP_MODE`, > `KEY_NAME`, and `KEY_SECRET` in a private environment. Needs a Postman version with `pm.require("npm:...")` support. ## Use the Postman collection Open the [OpenFX v3 collection](https://www.postman.com/ofx-devs/workspace/openfx/collection/58952302-184b70a6-dc21-41a7-9a15-6e03fcd88303) in Postman and fork it into your workspace. Create or select a private environment containing `BASE_URL`, `APP_MODE`, `KEY_NAME`, and `KEY_SECRET`. Set `BASE_URL` to the API origin including `/v3`, and set `APP_MODE` to SANDBOX or LIVE. The collection includes authentication, request signing, and idempotency handling. Start with your Sandbox environment and list the available currency pairs. Live requests act on real balances and funds. Keep all key values in your private Postman environment. ## Scopes Two scopes apply, and they split on direction: | Scope | Grants | | - | - | | `read` | Every `GET`, plus `POST /v3/fx/quotes`, which prices a trade without changing anything. | | `write` | Every other `POST`: trades, reversals, settlement, withdrawals, and all payments writes. | A key without the scope a call needs returns `403` AUTH_INSUFFICIENT_SCOPE. The [Cheat sheet](/v3/cheat-sheet#endpoints) lists the scope for each operation. ## Common mistakes When token minting, signing, or use goes wrong, you'll see one of these `AUTH_*` codes. Full catalog in [Errors → Auth](/v3/errors#error-code-catalog). | Code | When it fires | Fix | | - | - | - | | AUTH_TOKEN_MISSING | `Authorization` header absent | Add the header. | | AUTH_TOKEN_INVALID | JWT/claim validation fails, the `X-Request-Signature` is missing or invalid (`details.reason: request_signature_missing` or `request_signature_invalid`), or the JWT `nonce` was replayed (`details.reason: nonce_replay`). | Re-mint with ES256 and the correct key. For signature failures: re-check IEEE P-1363 encoding, freeze the body bytes once, run the path through `canonicalizePath`, and confirm you reused the JWT's `nonce` inside the canonical string. For a replayed nonce: generate a fresh `nonce` for every request. | | AUTH_TOKEN_EXPIRED | `exp` is in the past | Re-mint. Check NTP clock sync on the host. | | AUTH_TOKEN_INVALID_CONFIG | `exp - iat > 60s` or other unexpected claim config | Re-mint with `exp = iat + 60` (or shorter). | | AUTH_API_KEY_MISSING | The bearer token does not reference an API key | Mint the JWT with your API key `kid` as `sub` and `kid`. | | AUTH_API_KEY_INVALID | API key revoked or not found | Generate a new key in the dashboard. | | AUTH_FORBIDDEN_IP | Source IP not in the key's allowlist | Update the IP allowlist for the key. | | AUTH_INSUFFICIENT_SCOPE | Key missing the required scope (e.g. `write`) | Generate a key with the needed scope. | ## What's next > [card] [Quickstart](/v3/quickstart) > > Mint a token and make your first trade end-to-end. > [card] [Environments](/v3/environments) > > Switch between Sandbox and Live modes with the same key flow. > [card] [Errors](/v3/errors) > > `AUTH_TOKEN_*` codes and how to recover. > [card] [Rate limiting](/v3/rate-limiting) > > The per-org, per-environment limit, plus the headers to watch. # Balances Source: https://docs.openfx.com/v3/balances How to read the balances response: the org-wide aggregate, the per-currency rows, and what moves each amount. [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances) returns your organization's funds in two parts: an `aggregate` for the whole organization, and one row per currency in `balances`. Each part answers a different question, and each carries amounts that mean different things. Read this page before you gate a trade or withdrawal on a balance. > [!NOTE] > > `totalBalance` and `withdrawableBalance` are not the same number, and neither > one is "what you can trade". Check `withdrawableBalance` for the currency you > are selling, and use `aggregate` as the ceiling across all currencies. ## The response A successful response wraps the balances in `data`. There is no pagination: the response is the complete set, one row per currency you hold. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl https://api.openfx.com/v3/fx/balances \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" ``` ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "aggregate": { "currency": "USD", "withdrawableBalance": "85000.00" }, "balances": [ { "currency": "USD", "withdrawableBalance": "50000.00", "totalBalance": "60000.00" }, { "currency": "USDC", "withdrawableBalance": "25000.00", "totalBalance": "25000.00" }, { "currency": "EUR", "withdrawableBalance": "0", "totalBalance": "-1200.50" } ] } ``` Amounts are decimal strings. Parse them as decimals, never as floats. See [Amounts](/v3/amounts). ## Aggregate `aggregate` is your organization's net equity across every currency, converted to USD. It is the ceiling on what you can withdraw in total. | Field | Type | Meaning | | - | - | - | | `currency` | string | The currency `withdrawableBalance` is denominated in. Always USD today | | `withdrawableBalance` | decimal string | Net equity in USD. Never negative: it is `0` when your net position is negative | Read `aggregate` rather than deriving it. It is converted across currencies by OpenFX, so adding the per-currency rows yourself will not reproduce it. ## Per-currency balances Each entry in `balances` describes one currency you hold. | Field | Type | Meaning | | - | - | - | | `currency` | string | The currency both amounts are denominated in | | `withdrawableBalance` | decimal string | Available now to withdraw or trade. Never negative | | `totalBalance` | decimal string | Full ledger balance, including amounts reserved for pending withdrawals and trades. Can be negative | ### Withdrawable and total The two amounts relate in one of three ways. | Situation | `withdrawableBalance` | `totalBalance` | Why | | - | - | - | - | | Nothing pending | Equal to `totalBalance` | Zero or positive | All of the balance is available | | Amounts reserved | Less than `totalBalance` | Positive | The difference is held for pending withdrawals or trades | | You owe a settlement | `0` | Negative | The currency is in deficit | In the example above, USD shows `50000.00` withdrawable of `60000.00` total, so `10000.00` is reserved. EUR shows a negative total with `0` withdrawable, meaning the organization owes a settlement in EUR. A negative `totalBalance` in one currency does not make the whole response negative. `aggregate` nets your currencies, so check it separately. ## What changes a balance | Event | Effect | | - | - | | A [deposit](/v3/deposits) reaches COMPLETED | Credits the deposited currency | | A [trade](/v3/trades) reaches EXECUTED | Debits the sell currency and credits the buy currency | | A trade is [reversed](/v3/trades#reverse-a-trade) | Applies `reversalDetails.differentialAmount` in `reversalDetails.currency`, in the `direction` given | | A [withdrawal](/v3/withdrawals) is pending | Holds the amount in `totalBalance` and out of `withdrawableBalance` | ## Check a balance before you act Balances are real-time, so the response is a snapshot. Two checks use it. * **Before a trade.** Compare the sell amount against `withdrawableBalance` for the sell currency. OpenFX checks the sell-side balance at execution, and a shortfall returns `409` TRADE_INSUFFICIENT_BALANCE with `requiredAmount` and `availableAmount` in `error.details`. * **Before a withdrawal.** Compare the amount against `withdrawableBalance` for that currency. A shortfall returns `409` WITHDRAWAL_INSUFFICIENT_BALANCE. A balance can change between your read and your write, so treat the check as a guard and handle the error on the write. To reconcile, re-read balances when a [deposit](/v3/webhooks/deposits/deposit-completed) or [trade](/v3/webhooks/trades/trade-settled) webhook arrives rather than polling on a timer. ## Common mistakes * **Gating on `totalBalance`.** It includes reserved amounts. Use `withdrawableBalance` to decide what you can spend. * **Summing the rows to get the aggregate.** The rows are in different currencies. Read `aggregate`. * **Treating a negative `totalBalance` as an error.** It means you owe a settlement in that currency. `withdrawableBalance` is `0` for it. * **Expecting a row for every currency.** The response lists only currencies you hold. * **Parsing amounts as floats.** Use a decimal type. ## What's next > [card] [Trades](/v3/trades) > > When a trade moves funds, and what you can do while it waits. > [card] [Settlement models](/v3/settlement-models) > > Deposits, balances, and withdrawals in one flow. > [card] [Exposure](/v3/exposure) > > Exposure-limit usage, separate from your balances. > [card] [Amounts](/v3/amounts) > > Decimal strings and precision rules. # Blueprints Source: https://docs.openfx.com/v3/blueprints Choose what you're converting and get each integration step in order, with the API calls behind it and request and response bodies taken from the v3 specification. [Blueprints](about:blank) # Build with AI Source: https://docs.openfx.com/v3/build-with-ai Use Claude, ChatGPT, Cursor, or your own coding agent to build an OpenFX v3 integration in Sandbox, or to ask about your account. Build with AI Bring Claude, ChatGPT, Cursor, or your own agent into your OpenFX work. Build your integration in Sandbox, or ask about your trades. [Copy the starter prompt](#start-with-one-prompt) [Claude](https://claude.ai/new?q=Read%20the%20OpenFX%20API%20docs%20at%20https%3A%2F%2Fdocs.openfx.com%2Fllms.txt%20and%20help%20me%20integrate%20with%20the%20OpenFX%20v3%20API.%20Start%20by%20asking%20what%20I%20want%20to%20build%20%28FX%20trades%2C%20payouts%2C%20deposits%2C%20withdrawals%2C%20or%20webhooks%29%20and%20which%20language%20I%20use.%20Start%20with%20Sandbox%20%28X-App-Mode%3A%20SANDBOX%29%20and%20keep%20the%20key%20and%20X-App-Mode%20in%20configuration%20so%20going%20live%20is%20a%20configuration%20change.%20Never%20ask%20me%20to%20paste%20a%20Live%20key%20or%20private%20key%2C%20and%20cite%20the%20docs%20page%20for%20every%20endpoint%20you%20use.) [ChatGPT](https://chatgpt.com/?q=Read%20the%20OpenFX%20API%20docs%20at%20https%3A%2F%2Fdocs.openfx.com%2Fllms.txt%20and%20help%20me%20integrate%20with%20the%20OpenFX%20v3%20API.%20Start%20by%20asking%20what%20I%20want%20to%20build%20%28FX%20trades%2C%20payouts%2C%20deposits%2C%20withdrawals%2C%20or%20webhooks%29%20and%20which%20language%20I%20use.%20Start%20with%20Sandbox%20%28X-App-Mode%3A%20SANDBOX%29%20and%20keep%20the%20key%20and%20X-App-Mode%20in%20configuration%20so%20going%20live%20is%20a%20configuration%20change.%20Never%20ask%20me%20to%20paste%20a%20Live%20key%20or%20private%20key%2C%20and%20cite%20the%20docs%20page%20for%20every%20endpoint%20you%20use.) [Cursor](https://cursor.com/link/prompt?text=Read%20the%20OpenFX%20API%20docs%20at%20https%3A%2F%2Fdocs.openfx.com%2Fllms.txt%20and%20help%20me%20integrate%20with%20the%20OpenFX%20v3%20API.%20Start%20by%20asking%20what%20I%20want%20to%20build%20%28FX%20trades%2C%20payouts%2C%20deposits%2C%20withdrawals%2C%20or%20webhooks%29%20and%20which%20language%20I%20use.%20Start%20with%20Sandbox%20%28X-App-Mode%3A%20SANDBOX%29%20and%20keep%20the%20key%20and%20X-App-Mode%20in%20configuration%20so%20going%20live%20is%20a%20configuration%20change.%20Never%20ask%20me%20to%20paste%20a%20Live%20key%20or%20private%20key%2C%20and%20cite%20the%20docs%20page%20for%20every%20endpoint%20you%20use.) Just want to ask about your account? [Connect an AI app](#ask-your-agent-about-your-account) → ![Two hands drawn in dollar signs reaching toward each other](https://public-assets.openfx.com/docs/images/build-with-ai/banner-art.png) ## Start with one prompt Paste this into any AI assistant. It reads the docs index first, asks what you're building, and keeps you in Sandbox. ```text wrap theme={"theme":{"light":"poimandres","dark":"poimandres"}} Read the OpenFX API docs at https://docs.openfx.com/llms.txt and help me integrate with the OpenFX v3 API. Start by asking what I want to build (FX trades, payouts, deposits, withdrawals, or webhooks) and which language I use. Start with Sandbox (X-App-Mode: SANDBOX) and keep the key and X-App-Mode in configuration so going live is a configuration change. Never ask me to paste a Live key or private key, and cite the docs page for every endpoint you use. ``` ## Add the right files to your repo Head off common integration mistakes, like reusing a JWT or sending amounts as floats. your-project/ AGENTS.md Start here CLAUDE.md SKILL.md hosted by OpenFX llms.txt llms-full.txt openapi.json your-project/AGENTS.md Download Copy `AGENTS.md` covers Sandbox, authentication, amounts, idempotency, errors, and webhooks. Codex, Cursor, and GitHub Copilot read it directly. Claude Code reads it through `CLAUDE.md` and the skill. ```text AGENTS.md theme={"theme":{"light":"poimandres","dark":"poimandres"}} # OpenFX v3 integration rules This repository calls the OpenFX v3 API. Follow these rules in every change that touches OpenFX. ## Sources of truth - Read https://docs.openfx.com/llms.txt first, then the pages for the task. - The OpenAPI specifications define the wire contract. If a guide page and the specification disagree, follow the specification and report the disagreement. - Cite the docs page for every endpoint you use. Do not guess an endpoint, field, error code, or event name. If the docs do not cover it, say so. ## Environment and secrets - Build and test against Sandbox first. Sandbox and Live use the same endpoints and code, so keep the API key, webhook signing secret, and `X-App-Mode` value in configuration. Switch to Live by changing those values, and only when a human asks you to. - Read the API key from a file path or an environment variable. Never ask for, print, log, or commit a private key, JWT, or webhook signing secret. - Send `X-App-Mode` on every request, set to the environment of the key in use (`SANDBOX` or `LIVE`). Never rely on the header being optional. - Keep Sandbox and Live keys and webhook secrets in separate configuration entries. Sandbox ids are not Live ids. - See https://docs.openfx.com/v3/environments. ## Authentication - Every request carries a fresh ES256 JWT bearer token (60 seconds maximum lifetime, a unique `nonce` in the header) and an `X-Request-Signature` header. - The request signature uses IEEE P-1363 encoding, not DER, and covers the exact body bytes you send. Serialize the body once. - Build the signing helper from https://docs.openfx.com/v3/authentication. Do not reuse a JWT or a nonce. ## Requests and responses - Routes: FX under `/v3/fx/...`, Payments under `/v3/payments/...` and `/v3/common/...`. The base URL is `https://api.openfx.com`. - Amounts are JSON strings. Parse them as decimals, never floats. See https://docs.openfx.com/v3/amounts. - Responses wrap the result in a `data` object. Most list endpoints use cursor pagination with `limit`, `startingAfter`, and `endingBefore`, and return a `pagination` object. `GET /v3/fx/pairs`, `GET /v3/fx/balances`, and `GET /v3/common/financial-accounts` return the complete `data` array with no cursor parameters or `pagination`. See https://docs.openfx.com/v3/pagination. - Send an `Idempotency-Key` on every write. Create one key per logical operation, store it before you send the request, and reuse the same key to retry. See https://docs.openfx.com/v3/idempotency. ## Errors and rate limits - Branch on `error.code` and the retry strategy in the error response, not on the HTTP status alone. See https://docs.openfx.com/v3/errors. - Cap retries and back off. On `429`, wait for `Retry-After`. See https://docs.openfx.com/v3/rate-limiting. ## Webhooks - Verify the signature on the raw request body before you parse it, compare in constant time, and deduplicate by event `id`. - Handlers must tolerate duplicate and out-of-order events. Refetch the resource by id when in doubt. - See https://docs.openfx.com/v3/webhooks/setup and https://docs.openfx.com/v3/webhooks/authentication. ## Working agreement - Ask which language and HTTP client the repository uses if it is not obvious. - Keep a reusable signing helper, a thin API client, and tests that run against Sandbox. Do not hard-code credentials or resource ids. - Report which pages you read and anything you could not verify. ``` your-project/CLAUDE.md Download Copy Claude Code reads `CLAUDE.md`, not `AGENTS.md`. If your repository doesn't already have a `CLAUDE.md`, create one that contains this single line so Claude Code loads the same rules. ```text CLAUDE.md theme={"theme":{"light":"poimandres","dark":"poimandres"}} @AGENTS.md ``` your-project/.claude/skills/openfx-integration/SKILL.md Download Copy A skill packages a repeatable workflow that Claude Code loads when a request matches its description. It sends the agent to `AGENTS.md` and the matching task prompt, so the rules stay in one place. ```text SKILL.md theme={"theme":{"light":"poimandres","dark":"poimandres"}} --- name: openfx-integration description: Build, debug, or review an OpenFX v3 API integration. Use when the task involves OpenFX FX quotes and trades, payouts, deposits, withdrawals, request signing, or webhooks. --- # OpenFX v3 integration 1. Read `AGENTS.md` in the repository root and follow it. If it does not exist, stop and ask the user to add it from https://docs.openfx.com/v3/coding-agents. 2. Read https://docs.openfx.com/llms.txt, then read the docs pages for the task. 3. Find the matching prompt in the prompt library at https://docs.openfx.com/v3/coding-agents and follow its steps. 4. Work against Sandbox first, and keep the key and `X-App-Mode` in configuration so going live is a configuration change. State which pages you read and what you could not verify. ``` [https://docs.openfx.com/llms.txt](https://docs.openfx.com/llms.txt) [Open](https://docs.openfx.com/llms.txt) An index of every documentation page. Coding agents read the index first, then the pages for your task. ```text llms.txt theme={"theme":{"light":"poimandres","dark":"poimandres"}} # OpenFX > OpenFX API documentation. Real-time cross-border FX and stablecoin payment infrastructure. - [Introduction](https://docs.openfx.com/v3/introduction.md): OpenFX gives financial institutions programmatic access to FX and stablecoin liquidity, plus payouts to bank accounts, with a consistent `{ data }` response envelope, stable error codes, and cursor pagination. - [Quickstart](https://docs.openfx.com/v3/quickstart.md): Get from zero to your first executed trade in under 5 minutes. - [Cheat sheet](https://docs.openfx.com/v3/cheat-sheet.md): Every endpoint at a glance. Method, path, auth, idempotency, pagination, response shape. - [Glossary](https://docs.openfx.com/v3/glossary.md): Definitions for the vocabulary: resources, headers, status enums, and concepts used across the spec. - [Build with AI](https://docs.openfx.com/v3/build-with-ai.md): Use Claude, ChatGPT, Cursor, or your own coding agent to build an OpenFX v3 integration in Sandbox, or to ask about your account. - [Coding agents](https://docs.openfx.com/v3/coding-agents.md): Give your coding agent the OpenFX v3 rules, docs, and task prompts so it builds a correct integration in any language. - [MCP connectors](https://docs.openfx.com/v3/mcp-connectors.md): Connect Claude, ChatGPT, Claude Code, or Codex to your OpenFX account to query trades, deposits, and withdrawals in plain language. - [Trades](https://docs.openfx.com/v3/trades.md): The trade state machine from execution to settlement or reversal: statuses, settlement windows, the settle and reverse actions, and the webhooks that report each change. - [Currencies](https://docs.openfx.com/v3/currencies.md): Fiat and stablecoin currencies for FX trading, first-party withdrawals, and payout funding, with rails, networks, and early-access labels. - [Quotes](https://docs.openfx.com/v3/quotes.md): Atomic FX trades: discover supported pairs, quote a rate, execute the trade against the quote. - [Settlement models](https://docs.openfx.com/v3/settlement-models.md): Netted and Per-Trade settlement models, plus the balances, deposits, and withdrawals flows they share. - [Balances](https://docs.openfx.com/v3/balances.md): How to read the balances response: the org-wide aggregate, the per-currency rows, and what moves each amount. - [Exposure](https://docs.openfx.com/v3/exposure.md): The organization's exposure-limit usage: how much is committed to unsettled trades, and the breakdown by currency and settlement stage. - [Verified accounts](https://docs.openfx.com/v3/verified-accounts.md): Pre-configure your bank accounts and stablecoin wallets so withdrawals only need an `withdrawalAccountId` and a `withdrawalAmount`. - [Deposits](https://docs.openfx.com/v3/deposits.md): Deposit status values, detection mechanics per rail, and the reconciliation pattern for incoming funds. - [Withdrawals](https://docs.openfx.com/v3/withdrawals.md): Settlement windows per rail, and how to track the time between submission and settlement: webhooks first, adaptive polling as a fallback. ``` [https://docs.openfx.com/llms-full.txt](https://docs.openfx.com/llms-full.txt) [Open](https://docs.openfx.com/llms-full.txt) The full documentation in one file, for chat assistants that can't open links. The file is large, so avoid it in coding agents. ```text llms-full.txt theme={"theme":{"light":"poimandres","dark":"poimandres"}} # Account model Source: https://docs.openfx.com/v3/account-model The resources behind a payout, how they relate, and the statuses they share. An `Account` is someone you send money to or on behalf of: who they are, and what they're set up to do. It holds no money. This page covers the resources a payout uses, how they fit together, and the statuses they share. ## The four resources | Resource | Who it belongs to | What it is | | - | - | - | | `FinancialAccount` | You | A balance in one currency that funds your payouts. OpenFX creates these for you. | | `Account` | The person or company you pay | Who they are, plus the capabilities (`AccountCapability`) they hold. You create it. | | `PayoutAddress` | The person or company you pay | A bank account the money lands in. It belongs to one `Account`, through `accountId`, and an account can have several. You create it. | | `Payout` | You | Money sent from one of your financial accounts to a payout address. | **A payout links your side to theirs.** It debits `financialAccountId` and credits `receiver.payoutAddressId`. You don't name the receiving account, because the address already ``` [https://api.openfx.com/v3/openapi.json](https://api.openfx.com/v3/openapi.json) [Open](https://api.openfx.com/v3/openapi.json) The OpenAPI specification is the wire contract. Where a guide page and the specification disagree, the specification wins. ```text openapi.json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "openapi": "3.1.0", "info": { "title": "OpenFX API v3", "description": "FX trading, accounts, and payments on the OpenFX v3 API.", "version": "3.0.0", "termsOfService": "https://www.openfx.com/terms-and-conditions", "contact": { "name": "OpenFX Support", "email": "support@mail.openfx.com", "url": "https://www.openfx.com" }, "license": { "name": "Proprietary — © OpenFX. All rights reserved.", "url": "https://www.openfx.com/terms-and-conditions" } }, "servers": [ { "url": "https://api.openfx.com" ``` ## Prompts for common tasks With `AGENTS.md` in your repo, each prompt only has to describe the task. Select a task to copy its prompt. [All prompts](/v3/coding-agents#prompt-library) ## Ask your agent about your account Connect Claude, ChatGPT, Claude Code, or Codex to your OpenFX account. Ask about your trades, deposits, and withdrawals, and build reports from the answers, without an API key. Try asking: “Show me all my trades from last month, grouped by currency pair, with total notional per pair.” What the connector reads Trade history Deposit history Withdrawal history Withdrawal accounts Currency pairs > [!NOTE] > > An OpenFX admin switches on each AI app under **Organization > MCP Platforms**. See [MCP connectors](/v3/mcp-connectors) for more details. [https://mcp.openfx.com/mcp](https://mcp.openfx.com/mcp) [https://mcp-sandbox.openfx.com/mcp](https://mcp-sandbox.openfx.com/mcp) Live Sandbox Copy Copy Claude Add a custom connector with this URL, then sign in to OpenFX [Claude setup steps](/v3/mcp-connectors#claude) ChatGPT Add OpenFX as a custom app with this URL, then sign in [ChatGPT setup steps](/v3/mcp-connectors#chatgpt) Claude Code Run `claude mcp add` with this URL, then sign in from `/mcp` [Claude Code setup steps](/v3/mcp-connectors#claude-code) Codex Run `codex mcp add` with this URL, then `codex mcp login` [Codex setup steps](/v3/mcp-connectors#codex) # Capabilities Source: https://docs.openfx.com/v3/capabilities Every capability you can request, the identity details each one needs, and how capabilities control who can be paid. A capability lets an account do one thing in a payout: be paid in a currency, or be named as the sender. This page lists every capability, the identity details each one needs, and how they control payouts. For how a capability's status changes, see [Account model](/v3/account-model#the-shared-state-machine). ## What a capability is Each capability has an id: `cap_` followed by a Base58 string. Treat it as opaque; don't try to read meaning into it. An id stands for one fixed set of terms: what it covers, the identity it needs, and its legal basis. When any of those change, OpenFX issues a new id. To see what a capability covers, read its `details` (`CapabilityDetails`). It's read-only and always matches the id: * `grants`: what the capability lets the account do, as one or more `CapabilityGrant` values. A capability with several grants is still one capability, with one set of requirements and one status. * `currencies` (optional): the currencies it covers. Two rules apply. **A missing field means no limit**: no `currencies` means any currency. **Every combination applies**: two grants and two currencies mean both grants for both currencies. Where that wouldn't hold, OpenFX issues separate capabilities per currency instead. New fields can appear in `details`, so ignore ones you don't recognize. Compare capabilities, check payouts, and match webhooks by id, never by `details`. ## The capability catalog These are the ids to use. They're fixed and global: the same id works in SANDBOX and LIVE, and it's both what you send in `capabilities` and what accounts report back. The names in the first column are labels for this page only; the API uses just the id. | Capability | Id | Grant | Currency | Offered to | | - | - | - | - | - | | **RECEIVE_EUR** | `cap_Ce3AJmAmDGcJgTmTqgFVZ` | RECEIVE_PAYOUTS | EUR | Individuals and organizations | | **RECEIVE_MXN** | `cap_Ce3AJmB1WMUZkcMJ8DMzZ` | RECEIVE_PAYOUTS | MXN | Individuals and organizations | | **RECEIVE_COP** | `cap_Ce3AJmB1WMUZkahj9zxMf` | RECEIVE_PAYOUTS | COP | Individuals and organizations | | **RECEIVE_AED** | `cap_CfqBRLsEDD6zTH1oy7kvd` | RECEIVE_PAYOUTS | AED | Individuals and organizations | | **RECEIVE_GBP** | `cap_CgLwtEvHBaWUixEMH8RK7` | RECEIVE_PAYOUTS | GBP | Individuals and organizations | [Identity requirements](#identity-requirements) below lists what each one needs. ## Request capabilities at create Send capability ids in `capabilities` when you [create the account](/v3/api-reference/payments/accounts/create-account). You can only add capabilities at creation, so request every one the account will need, along with the identity details they require. Each starts PENDING. If you send `[]` or leave it out, the account has no capabilities. Each capability comes back as an `AccountCapability` with its `details`, which you can use in your own product, for example to offer adding a EUR payout address once the account can receive EUR. An account can hold each capability only once, ever. Requesting the same one twice fails with `422` CAPABILITY_DUPLICATE. If a capability is rejected, you can't request it again; you need a different one. [Account model](/v3/account-model#the-shared-state-machine) explains each status. Requesting a capability that the catalog doesn't know, that isn't offered to the account's `identityType`, or that has been retired, fails with `422` CAPABILITY_NOT_REQUESTABLE, and `error.details.notRequestable` names each one with its reason: UNKNOWN, NOT_OFFERED, or DEPRECATED. If a request has more than one of these problems, it fails with the first that applies of CAPABILITY_NOT_REQUESTABLE, CAPABILITY_DUPLICATE, and IDENTITY_REQUIREMENT_UNMET, and `details` reports every problem it found. ## Identity requirements Each capability is available to individuals, organizations, or both, and needs certain identity details before it can become ACTIVE. The sections below list them. Each table lists one required field per row, as a path into the account's identity. An individual's fields start with `identity.individual` and an organization's with `identity.organization`. If a capability is open to both, each gets its own table. If you request several capabilities, you need the fields for all of them. Most identity fields are optional in the schema, so an account with no capabilities needs very little. These tables show what each capability adds. If anything is missing when you request it, the request fails with `422` IDENTITY_REQUIREMENT_UNMET, and `error.details.issues` lists every missing field. The capability isn't created. The **When required** column gives any condition. "Always" means in every case. Conditions that depend on the account are explained below the table. ### Receiving capabilities Receiving capabilities grant RECEIVE_PAYOUTS: the account can be paid. See [The coverage gate](#the-coverage-gate). #### Be paid in euro over SEPA **`cap_Ce3AJmAmDGcJgTmTqgFVZ` (RECEIVE_EUR).** Covers RECEIVE_PAYOUTS for EUR. Offered to individuals and organizations. An individual needs: | Field | When required | | - | - | | `identity.individual.firstName` | Always | | `identity.individual.lastName` | Always | | `identity.individual.residentialAddress.country` | Always | An organization needs: | Field | When required | | - | - | | `identity.organization.legalName` | Always | | `identity.organization.registeredAddress.country` | Always | #### Be paid in Mexican pesos **`cap_Ce3AJmB1WMUZkcMJ8DMzZ` (RECEIVE_MXN).** Covers RECEIVE_PAYOUTS for MXN. Offered to individuals and organizations. An individual needs: | Field | When required | | - | - | | `identity.individual.firstName` | Always | | `identity.individual.lastName` | Always | | `identity.individual.taxInformation[]` | An entry whose `issuingCountry` is MX, carrying the RFC. Not needed where `documents[]` carries the CURP | | `identity.individual.documents[]` | A NATIONAL_ID document issued in MX, carrying the CURP as `number`. Not needed where `taxInformation[]` carries the RFC | An individual is identified by an RFC or a CURP. If you send both, OpenFX uses the RFC. A passport isn't accepted instead. An organization needs: | Field | When required | | - | - | | `identity.organization.legalName` | Always | | `identity.organization.taxInformation[]` | An entry whose `issuingCountry` is MX, carrying the RFC | #### Be paid in Colombian pesos **`cap_Ce3AJmB1WMUZkahj9zxMf` (RECEIVE_COP).** Covers RECEIVE_PAYOUTS for COP, to a Colombian bank account or a Bre-B key. Offered to individuals and organizations. An individual needs: | Field | When required | | - | - | | `identity.individual.firstName` | Always | | `identity.individual.lastName` | Always | | `identity.individual.nationality` | Always | | `identity.individual.documents[]` | A NATIONAL_ID or PASSPORT document from any issuing country, or a RESIDENCE_PERMIT issued in CO, carrying `number` and `issuingCountry` | A Colombian citizen is identified by their cédula, sent as a NATIONAL_ID issued in CO. A foreign national uses a cédula de extranjería, sent as a RESIDENCE_PERMIT issued in CO, or a passport or national ID from another country. A driving license isn't accepted. An organization needs: | Field | When required | | - | - | | `identity.organization.legalName` | Always | | `identity.organization.taxInformation[]` | An entry whose `issuingCountry` is CO, carrying the NIT | #### Be paid in UAE dirhams **`cap_CfqBRLsEDD6zTH1oy7kvd` (RECEIVE_AED).** Covers RECEIVE_PAYOUTS for AED, to a bank account held in the United Arab Emirates. Offered to individuals and organizations. An individual needs: | Field | When required | | - | - | | `identity.individual.firstName` | Always | | `identity.individual.lastName` | Always | | `identity.individual.residentialAddress.line1` | Always. At most 50 characters | | `identity.individual.residentialAddress.country` | Always | No identity document is needed. If you send a PASSPORT, or a NATIONAL_ID issued in AE (the Emirates ID), its `number` must be at most 50 characters, not counting spaces and separators. The address can be in any country. An organization needs: | Field | When required | | - | - | | `identity.organization.legalName` | Always | | `identity.organization.registeredAddress.line1` | Always. At most 50 characters | | `identity.organization.registeredAddress.country` | Always | The name paid is checked on the payout address, not here. A UAE bank account takes a name of at most 75 bytes using letters A to Z, digits, spaces and / – ? : - ( ) . , ' + &, with no digits for an individual. If the account's own name doesn't fit, send `accountHolderName` when you [register the payout address](/v3/payouts). #### Be paid in pounds sterling **`cap_CgLwtEvHBaWUixEMH8RK7` (RECEIVE_GBP).** Covers RECEIVE_PAYOUTS for GBP, to a UK bank account. Offered to individuals and organizations. An individual needs: | Field | When required | | - | - | | `identity.individual.lastName` | Always | | `identity.individual.firstName` | Optional. A single-name identity is valid, and the name is folded into `lastName` | | `identity.individual.residentialAddress.country` | Always | An organization needs: | Field | When required | | - | - | | `identity.organization.legalName` | Always | | `identity.organization.registeredAddress.country` | Always | ## The coverage gate A payout checks **what a capability covers, not its id**. When you create a payout, OpenFX works out the coverage it needs from the `receiveCurrency`. The receiver, and the sender if there is one, must each hold an ACTIVE capability that covers it. * RECEIVE_PAYOUTS lets the account be paid at the bank accounts its capability covers. * SEND_PAYOUTS_TO_THIRD_PARTIES lets the account be named as a payout's `sender`. It only grants permission: the money still comes from the payout's `financialAccountId`, never from the sender. A payout address doesn't name a capability, but its account must already hold one that can receive at it, in any status. See [Payouts](/v3/payouts). OpenFX decides how the payout is delivered. ## How the vocabulary evolves Capabilities are only ever added. A published capability is never renamed or changed. To widen what a capability covers, OpenFX issues a new capability and grants it to accounts that already meet its requirements. You get [`common.account.capability_activated`](/v3/webhooks/payments/accounts-webhooks/account-capability-activated) without doing anything. A change to requirements or legal basis always means a new capability. To retire one, OpenFX issues a replacement and moves holders of the old one to REJECTED; the old one can then no longer be requested. This means capabilities are versioned without version numbers, and one capability may be replaced by several ids over time. Because payouts check coverage across all your ACTIVE capabilities, you won't notice this when paying, and your audit trail stays clear. ## What's next > [card] [Account model](/v3/account-model) > > The resources behind a payout, and the statuses they share. > [card] [Payouts](/v3/payouts) > > Set up a recipient and send a payout. # Cheat sheet Source: https://docs.openfx.com/v3/cheat-sheet Every endpoint at a glance. Method, path, auth, idempotency, pagination, response shape. A single-page reference for everything callable in v3. For the narrative version of any row, follow the link. ## Endpoints | Method | Path | Description | Auth scope | Idempotency-Key | Paginated | Returns | | - | - | - | - | - | - | - | | GET | [`/v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs) | List tradable currency pairs | `read` | — | Bounded | `{data: {pairs: Pair[]}}` | | POST | [`/v3/fx/quotes`](/v3/api-reference/trade/create-quote) | Lock a rate (`quoteForSeconds`: 3, 15, 30, 45, or 60) | `read` | Required | — | `{data: Quote}` | | GET | [`/v3/fx/quotes/{id}`](/v3/api-reference/trade/get-quote-by-id) | Retrieve one quote (pre-trade verification) | `read` | — | — | `{data: Quote}` | | POST | [`/v3/fx/trades`](/v3/api-reference/trade/execute-trade) | Execute a quote | `write` | Required | — | `{data: Trade}` | | POST | [`/v3/fx/trades/{id}/reverse-quote`](/v3/api-reference/trade/generate-reverse-quote) | Preview the amounts for reversing a trade | `write` | Required | — | `{data: ReverseQuote}` | | POST | [`/v3/fx/trades/{id}/reverse`](/v3/api-reference/trade/reverse-trade) | Reverse a trade against a reverse quote | `write` | Required | — | `{data: TradeReversal}` | | POST | [`/v3/fx/trades/{id}/settle`](/v3/api-reference/trade/settle-trade) | Settle a trade | `write` | Required | — | `{data: TradeSettlement}` | | GET | [`/v3/fx/trades/{id}`](/v3/api-reference/trade/get-trade) | Retrieve one trade | `read` | — | — | `{data: Trade}` | | GET | [`/v3/fx/trades`](/v3/api-reference/trade/list-trades) | List trades, newest-first | `read` | — | ✓ cursor | `{data: Trade[], pagination}` | | GET | [`/v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances) | Per-currency balance | `read` | — | Bounded | `{data: Balance[]}` | | GET | [`/v3/fx/exposures`](/v3/api-reference/exposure/get-exposure-summary) | Exposure summary | `read` | — | — | `{data: ExposureSummary}` | | GET | [`/v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits) | List deposits, newest-first | `read` | — | ✓ cursor | `{data: Deposit[], pagination}` | | GET | [`/v3/fx/deposits/{id}`](/v3/api-reference/trade-settlement/get-deposit) | Retrieve one deposit | `read` | — | — | `{data: Deposit}` | | POST | [`/v3/fx/withdrawals`](/v3/api-reference/trade-settlement/create-withdrawal) | Submit a withdrawal (fiat or stablecoin) | `write` | Required | — | `{data: Withdrawal}` | | GET | [`/v3/fx/withdrawals/{id}`](/v3/api-reference/trade-settlement/get-withdrawal) | Retrieve one withdrawal | `read` | — | — | `{data: Withdrawal}` | | GET | [`/v3/fx/withdrawals`](/v3/api-reference/trade-settlement/list-withdrawals) | List withdrawals, newest-first | `read` | — | ✓ cursor | `{data: Withdrawal[], pagination}` | | GET | [`/v3/fx/withdrawal-accounts`](/v3/api-reference/trade-settlement/list-withdrawal-accounts) | List verified withdrawal accounts | `read` | — | ✓ cursor | `{data: WithdrawalAccount[], pagination}` | | POST | [`/v3/common/accounts`](/v3/api-reference/payments/accounts/create-account) | Create an account for a recipient or a sender, with the capabilities it needs | `write` | Required | — | `{data: Account}` | | GET | [`/v3/common/accounts`](/v3/api-reference/payments/accounts/list-accounts) | List accounts, newest-first | `read` | — | ✓ cursor | `{data: Account[], pagination}` | | GET | [`/v3/common/accounts/{accountId}`](/v3/api-reference/payments/accounts/get-account) | Retrieve one account | `read` | — | — | `{data: Account}` | | POST | [`/v3/common/accounts/{accountId}/archive`](/v3/api-reference/payments/accounts/archive-account) | Archive an account | `write` | Required | — | `{data: Account}` | | GET | [`/v3/common/financial-accounts`](/v3/api-reference/payments/accounts/list-financial-accounts) | List which of your balances can fund a given payout | `read` | — | Bounded | `{data: FinancialAccount[]}` | | POST | [`/v3/payments/payout-addresses`](/v3/api-reference/payments/addresses/create-payout-address) | Register where the money lands | `write` | Required | — | `{data: PayoutAddress}` | | GET | [`/v3/payments/payout-addresses`](/v3/api-reference/payments/addresses/list-payout-addresses) | List payout addresses, newest-first | `read` | — | ✓ cursor | `{data: PayoutAddress[], pagination}` | | GET | [`/v3/payments/payout-addresses/{payoutAddressId}`](/v3/api-reference/payments/addresses/get-payout-address) | Retrieve one payout address | `read` | — | — | `{data: PayoutAddress}` | | POST | [`/v3/payments/payout-addresses/{payoutAddressId}/archive`](/v3/api-reference/payments/addresses/archive-payout-address) | Archive a payout address | `write` | Required | — | `{data: PayoutAddress}` | | POST | [`/v3/payments/payout-quotes`](/v3/api-reference/payments/payouts/create-payout-quote) | Price a payout without moving funds | `write` | Required | — | `{data: PayoutQuote}` | | POST | [`/v3/payments/payouts`](/v3/api-reference/payments/payouts/create-payout) | Create a payout, inline-priced or from a quote | `write` | Required | — | `{data: Payout}` | | GET | [`/v3/payments/payouts`](/v3/api-reference/payments/payouts/list-payouts) | List payouts, newest-first | `read` | — | ✓ cursor | `{data: Payout[], pagination}` | | POST | [`/v3/payments/payouts/{payoutId}/confirm`](/v3/api-reference/payments/payouts/confirm-payout) | Accept the priced payout | `write` | Required | — | `{data: Payout}` | | POST | [`/v3/payments/payouts/{payoutId}/cancel`](/v3/api-reference/payments/payouts/cancel-payout) | Decline a payout before acceptance | `write` | Required | — | `{data: Payout}` | | GET | [`/v3/payments/payouts/{payoutId}`](/v3/api-reference/payments/payouts/get-payout) | Look up a single payout | `read` | — | — | `{data: Payout}` | The `read` scope covers reads and `POST /v3/fx/quotes`, which prices a trade without changing anything. The `write` scope covers every other change, payments endpoints included. Selecting **Write** when you create a key grants both read and write access; selecting **Read** grants read access only. See [Authentication](/v3/authentication#api-key-scopes) for the permission rules. A key without the scope a call needs returns `403` AUTH_INSUFFICIENT_SCOPE. ## Request headers | Header | When | Value | | - | - | - | | `Authorization` | Always | `Bearer `: ES256, 60s TTL, single-use (server-enforced nonce uniqueness) | | `X-Request-Signature` | Always | ES256 (IEEE P-1363 base64url) over `METHOD\nCANONICAL_PATH\nCANONICAL_QUERY\nNONCE\nSHA256_HEX(body)`. See [Authentication → Request signing](/v3/authentication#request-signing). | | `X-App-Mode` | Required for Live; optional for Sandbox | LIVE or SANDBOX, matching the key's environment. Defaults to SANDBOX when omitted, so send LIVE explicitly with a Live key. Any other value returns `400` INVALID_APP_MODE. See [Environments](/v3/environments). | | `Idempotency-Key` | Writes (POST) | Client-generated. Pattern `^[a-zA-Z0-9_-]{1,255}$` (UUID recommended) | | `Content-Type` | Writes (POST) | `application/json` | ## Response headers Always set, every response (success and error): | Header | Meaning | | - | - | | `X-Trace-Id` | Per-request ID. Echo back in support tickets. | | `X-Request-Timestamp` | Server time the request reached the API (RFC 3339, ms) | | `RateLimit-Limit` | Max requests in current window | | `RateLimit-Reset` | Seconds until window resets (a duration, not an epoch time) | Sometimes set: | Header | When | | - | - | | `Idempotency-Replayed` | `true`/`false` on every POST: whether the response was replayed from the idempotency cache | | `Retry-After` | Seconds to wait. On `429` RATE_LIMIT_EXCEEDED and `409` IDEMPOTENCY_IN_FLIGHT only | | `Sunset` + `Link: rel="successor-version"` | On 410 (v1 endpoints after Dec 31 2026) | ## Resource IDs All resource IDs are **readable, typed-prefix** strings: a lowercase 3-to-6-letter resource-type prefix plus a Base58 encoding of the underlying UUID. Bare UUIDs never appear in a v3 response body. Server-generated, permanent, safe to store and index. * Example: `tde_5W7guYdHT24JFnRQrZN9y8` * Regex: `^[a-z]{3,6}_[1-9A-HJ-NP-Za-km-z]{1,22}$`, a loose pre-filter. The authoritative check is a successful decode to 16 bytes, and payments operations also pin each ID's prefix and a 21-to-22-character body. See [Resource IDs](/v3/resource-ids) for the prefix table, foreign-key surface, and stability contract. ## Status enums | Resource | Values | | - | - | | `Quote.status` | ACTIVE · EXPIRED · CONSUMED | | `Trade.status` | PENDING · LOCKED · READY_TO_SETTLE · EXECUTED · REVERSED | | `Deposit.status` | PENDING · COMPLETED · REJECTED · ERROR | | `Withdrawal.status` | PENDING · COMPLETED · CANCELLED | | `Payout.status` | REQUIRES_CONFIRMATION · ACCEPTED · PROCESSING · IN_REVIEW · PROCESSED · RETURNED · FAILED · CANCELLED · EXPIRED | | `Account.status` | PENDING · ACTIVE · REJECTED · REQUIRES_INFORMATION | | `PayoutAddress.status` | PENDING · ACTIVE · REJECTED · REQUIRES_INFORMATION | | `AccountCapability.status` | PENDING · ACTIVE · REJECTED · REQUIRES_INFORMATION | * Quotes terminate at EXPIRED or CONSUMED. * Trades terminate at EXECUTED or REVERSED. * Deposits terminate at COMPLETED, REJECTED, or ERROR. * Withdrawals terminate at COMPLETED or CANCELLED. * Payouts terminate at RETURNED, FAILED, CANCELLED, or EXPIRED. PROCESSED is not terminal: reconcile it as delivered, pending the return window. * Accounts, payout addresses, and capabilities share one four-state machine. ACTIVE is not terminal, and REJECTED has no documented exit. See [Status enums reference](/v3/glossary#status-enums). ## Amount precision | Currency type | Max decimals | Example | Over-precision error | | - | - | - | - | | Fiat | 2 | `"1000.00"` | `422` WITHDRAWAL_INVALID_AMOUNT_PRECISION | | Crypto | 6 | `"1000.000001"` | `422` WITHDRAWAL_INVALID_AMOUNT_PRECISION | Amounts are JSON **strings**, never numbers. Regex: `^-?[0-9]+(\.[0-9]{1,8})?$`. See [Amounts](/v3/amounts). ## Idempotency TTLs | Endpoint | TTL | Reason | | - | - | - | | `POST /v3/fx/quotes` | 30 min | Duplicates are cheap (re-quote) | | `POST /v3/fx/trades` | 24 h | Duplicates move thousands of dollars | | `POST /v3/fx/trades/{id}/reverse-quote` | 30 min | Duplicates are cheap (re-quote) | | `POST /v3/fx/trades/{id}/reverse` | 24 h | Duplicates move thousands of dollars | | `POST /v3/fx/trades/{id}/settle` | 24 h | Duplicates move thousands of dollars | | `POST /v3/fx/withdrawals` | 7 days | Sized for long-running rails (SWIFT, weekend ACH, end-of-month batches) | Payments `POST` endpoints follow the Payments API: "A key is consumed by its first accepted request and is never reusable: there is no expiry and nothing to outlive." See [Idempotency](/v3/idempotency) for replay and retry behavior. ## Pagination The unbounded lists (`trades`, `deposits`, `withdrawals`, `accounts`, `payout-addresses`, `payouts`) use cursor pagination, newest-first by `createdAt`. Default page size is **25** and the maximum is **100**. Their responses wrap `{data, pagination: {limit, hasNext, nextCursor, hasPrev, prevCursor}}`; cursors are opaque tokens that you pass back verbatim. The bounded lists (`pairs`, `balances`, `financial-accounts`) return their complete `data` array without pagination parameters or a `pagination` object. No endpoint uses `total_count` or page numbers. | Param | Type | | - | - | | `limit` | int 1–100 | | `startingAfter` | opaque cursor string (older than) | | `endingBefore` | opaque cursor string (newer than) | See [Pagination](/v3/pagination) for cursor handling. ## Error response shape ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "error": { "code": "QUOTE_EXPIRED", "type": "CONFLICT", "message": "The quoted rate has expired. Request a new quote.", "retryStrategy": "FIX_AND_RESUBMIT", "details": { "quoteId": "qte_3FfGK34vwMvVFDedyb2nkf", "expiredAt": "2026-04-28T10:00:00.000Z" } } } ``` `code`, `type`, `message`, `retryStrategy`, and `details` are **all required** on every v3 error response (`details` is `{}` when there's no structured context). `code` is stable across versions; `message` may change. Branch on `code` and `type` for behavior, or read `retryStrategy` directly for retry handling. Never branch on `message`. For body-portable correlation, capture the `X-Trace-Id` header at call time. Full catalog: [Errors](/v3/errors). ## HTTP status × type quick map | Status | Typical `type` | Meaning | | - | - | - | | 400 | VALIDATION_ERROR | Malformed JSON, wrong types | | 401 | AUTHENTICATION_ERROR | Token missing/invalid/expired | | 403 | AUTHORIZATION_ERROR | Auth ok, not allowed | | 404 | NOT_FOUND | Resource missing (also covers cross-org leakage prevention) | | 409 | CONFLICT | State-driven conflict (insufficient balance, in-flight key) | | 422 | VALIDATION_ERROR / CONFLICT | Semantic violation; idempotency-mismatch | | 428 | VALIDATION_ERROR | Missing `Idempotency-Key` on a write | | 429 | RATE_LIMITED | Throttled | | 500 | INTERNAL_ERROR | INTERNAL_ERROR catch-all; write-path 500s (TRADE_EXECUTION_FAILED, WITHDRAWAL_INITIATION_FAILED) echo `details.resourceId` for safe check-state-then-retry | ## What's next > [card] [Quickstart](/v3/quickstart) > > 5-minute round trip from JWT to executed trade. > [card] [API reference](/v3/api-reference/trade/list-currency-pairs) > > Full schemas with the interactive playground. > [card] [Errors](/v3/errors) > > Every documented error code with retry semantics. # Coding agents Source: https://docs.openfx.com/v3/coding-agents Give your coding agent the OpenFX v3 rules, docs, and task prompts so it builds a correct integration in any language. Use an AI coding agent to build an OpenFX v3 integration in the language and framework you already use. You give the agent three things: the OpenFX documentation, a short rules file that prevents the most common integration mistakes, and a prompt for the task. ## Choose your starting point | You want to | Start with | | - | - | | Ask an AI app about your own trades, deposits, and withdrawals | [MCP connectors](/v3/mcp-connectors) | | Build an integration with a coding agent | [Add the rules file and skill](#add-the-rules-file-and-skill) and the [prompt library](#prompt-library) | | Ask a chat assistant a quick question about the API | [Machine-readable docs](#machine-readable-docs) | > [!NOTE] > > The OpenFX MCP connector reads your account data and is read-only. It does not read this documentation and can't place trades or move funds. Your coding agent writes code that calls the API with your Sandbox API key. ## Before you begin * **A Sandbox API key file.** The key JSON contains `kid` and `privateKey`, and Sandbox keys carry a `sandbox_` prefix. See [Authentication](/v3/authentication) and [Environments](/v3/environments). * **A coding agent** that reads an `AGENTS.md` file or a project instruction file, such as Claude Code, Codex, Cursor, or GitHub Copilot. > [!WARNING] > > Build and test against Sandbox first. Sandbox and Live use the same endpoints and code, so going live means changing the API key, the webhook signing secret, and the `X-App-Mode` value in configuration. Never paste an API key, private key, or webhook signing secret into a chat. Give the agent the path to the key file or the name of an environment variable. ## Machine-readable docs Point your agent at these files so it reads the documentation instead of guessing. | File | What it contains | Use it for | | - | - | - | | `https://docs.openfx.com/llms.txt` | An index of every documentation page | Coding agents. The agent reads the index first, then the pages for your task. | | `https://docs.openfx.com/llms-full.txt` | The full documentation in one file | Chat assistants that can't open links. The file is large, so avoid it in coding agents. | Where a guide page and the OpenAPI specification disagree, the specification is the contract. ## Add the rules file and skill Add `AGENTS.md` to your repository so every coding agent starts with the OpenFX v3 rules. Add the skill if you use Claude Code. Commit both so every contributor and agent session uses the same rules. They link to the documentation instead of copying it, so they stay current when the documentation changes. > [accordion] AGENTS.md > > `AGENTS.md` is a plain Markdown file at the root of your repository that coding agents read before they work. Copy this file into your repository. It states each rule briefly and links to the page that owns the detail. > > ```text AGENTS.md theme={"theme":{"light":"poimandres","dark":"poimandres"}} > # OpenFX v3 integration rules > > This repository calls the OpenFX v3 API. Follow these rules in every change that touches OpenFX. > > ## Sources of truth > > - Read https://docs.openfx.com/llms.txt first, then the pages for the task. > - The OpenAPI specifications define the wire contract. If a guide page and the specification disagree, follow the specification and report the disagreement. > - Cite the docs page for every endpoint you use. Do not guess an endpoint, field, error code, or event name. If the docs do not cover it, say so. > > ## Environment and secrets > > - Build and test against Sandbox first. Sandbox and Live use the same endpoints and code, so keep the API key, webhook signing secret, and `X-App-Mode` value in configuration. Switch to Live by changing those values, and only when a human asks you to. > - Read the API key from a file path or an environment variable. Never ask for, print, log, or commit a private key, JWT, or webhook signing secret. > - Send `X-App-Mode` on every request, set to the environment of the key in use (`SANDBOX` or `LIVE`). Never rely on the header being optional. > - Keep Sandbox and Live keys and webhook secrets in separate configuration entries. Sandbox ids are not Live ids. > - See https://docs.openfx.com/v3/environments. > > ## Authentication > > - Every request carries a fresh ES256 JWT bearer token (60 seconds maximum lifetime, a unique `nonce` in the header) and an `X-Request-Signature` header. > - The request signature uses IEEE P-1363 encoding, not DER, and covers the exact body bytes you send. Serialize the body once. > - Build the signing helper from https://docs.openfx.com/v3/authentication. Do not reuse a JWT or a nonce. > > ## Requests and responses > > - Routes: FX under `/v3/fx/...`, Payments under `/v3/payments/...` and `/v3/common/...`. The base URL is `https://api.openfx.com`. > - Amounts are JSON strings. Parse them as decimals, never floats. See https://docs.openfx.com/v3/amounts. > - Responses wrap the result in a `data` object. Most list endpoints use cursor pagination with `limit`, `startingAfter`, and `endingBefore`, and return a `pagination` object. `GET /v3/fx/pairs`, `GET /v3/fx/balances`, and `GET /v3/common/financial-accounts` return the complete `data` array with no cursor parameters or `pagination`. See https://docs.openfx.com/v3/pagination. > - Send an `Idempotency-Key` on every write. Create one key per logical operation, store it before you send the request, and reuse the same key to retry. See https://docs.openfx.com/v3/idempotency. > > ## Errors and rate limits > > - Branch on `error.code` and the retry strategy in the error response, not on the HTTP status alone. See https://docs.openfx.com/v3/errors. > - Cap retries and back off. On `429`, wait for `Retry-After`. See https://docs.openfx.com/v3/rate-limiting. > > ## Webhooks > > - Verify the signature on the raw request body before you parse it, compare in constant time, and deduplicate by event `id`. > - Handlers must tolerate duplicate and out-of-order events. Refetch the resource by id when in doubt. > - See https://docs.openfx.com/v3/webhooks/setup and https://docs.openfx.com/v3/webhooks/authentication. > > ## Working agreement > > - Ask which language and HTTP client the repository uses if it is not obvious. > - Keep a reusable signing helper, a thin API client, and tests that run against Sandbox. Do not hard-code credentials or resource ids. > - Report which pages you read and anything you could not verify. > ``` > > Claude Code reads `CLAUDE.md`, not `AGENTS.md`. If your repository doesn't already have a `CLAUDE.md`, create one that contains the single line `@AGENTS.md` so Claude Code loads the same rules. > [accordion] SKILL.md (Claude Code) > > A skill packages a repeatable workflow that Claude Code loads when a request matches its description. Save this file as `.claude/skills/openfx-integration/SKILL.md` in your repository. It sends the agent to the rules file and the matching task prompt, so the rules stay in one place. > > ```text SKILL.md theme={"theme":{"light":"poimandres","dark":"poimandres"}} > --- > name: openfx-integration > description: Build, debug, or review an OpenFX v3 API integration. Use when the task involves OpenFX FX quotes and trades, payouts, deposits, withdrawals, request signing, or webhooks. > --- > > # OpenFX v3 integration > > 1. Read `AGENTS.md` in the repository root and follow it. If it does not exist, stop and ask the user to add it from https://docs.openfx.com/v3/coding-agents. > 2. Read https://docs.openfx.com/llms.txt, then read the docs pages for the task. > 3. Find the matching prompt in the prompt library at https://docs.openfx.com/v3/coding-agents and follow its steps. > 4. Work against Sandbox first, and keep the key and `X-App-Mode` in configuration so going live is a configuration change. State which pages you read and what you could not verify. > ``` > > Codex, Cursor, and GitHub Copilot read `AGENTS.md` or their own instruction files directly. Skills are specific to Claude Code. ## Prompt library Each prompt tells the agent which pages to read, what to build, and what to deliver. The prompts point to the documentation for contract details, so they stay correct when the documentation changes. ### Use a prompt **1. Copy a prompt** Choose the prompt for your task below and copy its code block. **2. Paste it into your agent** The agent asks for your language, HTTP client, and the path to your Sandbox key file. Answer with paths and names, not secrets. **3. Review and keep the output** Read the code the agent writes, run its tests against Sandbox, and commit the helpers and tests so you can rerun them. Each prompt assumes the agent can read `https://docs.openfx.com`. If it can't fetch URLs, paste the pages it names into the conversation. ### Start here > [accordion] Ask a question about the API > > Use this in a chat assistant when you don't have a coding agent open yet. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Read the OpenFX API docs at https://docs.openfx.com/llms.txt and help me integrate with the OpenFX v3 API. Start by asking what I want to build (FX trades, payouts, deposits, withdrawals, or webhooks) and which language I use. Start with Sandbox (X-App-Mode: SANDBOX) and keep the key and X-App-Mode in configuration so going live is a configuration change. Never ask me to paste a Live key or private key, and cite the docs page for every endpoint you use. > ``` > [accordion] Sandbox quickstart > > Builds a signing helper, a thin client, and a smoke script that completes one Sandbox trade. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Set up a working OpenFX v3 Sandbox integration in this repository and prove it with one completed FX trade. > > Read first: https://docs.openfx.com/llms.txt, https://docs.openfx.com/v3/quickstart, https://docs.openfx.com/v3/authentication, https://docs.openfx.com/v3/environments, https://docs.openfx.com/v3/amounts, and https://docs.openfx.com/v3/idempotency. Where a guide page and the OpenAPI specification disagree, follow the specification and tell me about the disagreement. > > Before you write code, ask me for my language, my HTTP client, and the path to my Sandbox API key file. Never ask me to paste the key. > > Build, in order: > 1. A signRequest helper that follows the Authentication page exactly and mints a fresh JWT and signature for every request. > 2. A thin client for https://api.openfx.com that reads the API key and X-App-Mode from configuration (SANDBOX for now) and unwraps the data envelope. > 3. A smoke script that lists pairs, lists balances, creates a quote, executes a trade from the quote, and fetches the trade by id. Use a different Idempotency-Key for each write. > 4. Output that prints every created resource id and the final trade status. > > On any failed call, print error.code, error.message, and the retry strategy, not only the HTTP status. > > Deliver the helper, the client, the smoke script, an example environment file, and a short README that explains how to run it and how to switch to Live later. > ``` ### Build a flow > [accordion] FX quotes and trades > > Builds the conversion flow: discover pairs, quote, execute before expiry, and track the trade. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Build an FX conversion feature on the OpenFX v3 API in this codebase: discover pairs, create a quote, show the price, execute the trade, and track it. > > Read first: https://docs.openfx.com/v3/trades, https://docs.openfx.com/v3/quotes, https://docs.openfx.com/v3/currencies, https://docs.openfx.com/v3/amounts, https://docs.openfx.com/v3/idempotency, https://docs.openfx.com/v3/pagination, https://docs.openfx.com/v3/errors, and the Trade pages of the API reference. Assume a working signing helper exists. If not, build it first from https://docs.openfx.com/v3/authentication. > > Requirements: > - Validate user input against the pairs endpoint. > - Show the amounts the quote returns. Don't invent fields the API doesn't return. > - Use a separate Idempotency-Key for the quote and for the trade, one per logical operation. > - Handle quote expiry by re-quoting and asking the user to confirm. Never execute silently at a new price. > - Store each Idempotency-Key before you send the request. Replay with the same key after a timeout. If the trade returns TRADE_EXECUTION_FAILED, look it up by ID. If it exists, track it. If the lookup confirms it is missing, get a fresh quote and submit the trade with a new key. > - Represent amounts with a decimal type end to end. > > Deliver a service module, Sandbox tests for the happy path, quote expiry, and a duplicate submit, and a short list of every error code the module handles. > ``` > [accordion] Trade settlement and reversals > > Builds settle and reverse flows for the settlement model your organization uses. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Add post-trade settlement and reversal handling to this OpenFX v3 integration. > > Read first: https://docs.openfx.com/v3/settlement-models, https://docs.openfx.com/v3/trades (the state machine, settle, and reverse sections), https://docs.openfx.com/v3/exposure, https://docs.openfx.com/v3/balances, https://docs.openfx.com/v3/idempotency, https://docs.openfx.com/v3/webhooks/setup, the Trade event pages under Webhooks, and the settle, reverse-quote, and reverse operations in the API reference. > > Ask me which settlement model my organization uses before you write code, and implement only what that model needs. The field tradeSettlementMode appears only in trade webhook payloads. It isn't on the REST Trade resource, so don't look for it there. > > Build: > 1. The trade state machine from the Trades page, driven by trade webhook events, with the trade endpoint as the fallback. > 2. Settlement for per-trade organizations: settle a trade when it is ready to settle, with its own Idempotency-Key, and confirm the result from the trade webhook or by fetching the trade. > 3. Reversal: create a reverse quote, show the reversal price to the user, then reverse the trade. Use a separate Idempotency-Key for each call and handle quote expiry. > 4. Exposure and balances: show exposure that settles later so operations don't treat it as stuck, and read withdrawableBalance separately from totalBalance after settlement. > > Trade webhooks are delivered only to Live webhook endpoints. In Sandbox, poll the trade endpoint, and keep the polling path in production as a fallback. Handlers must be idempotent and tolerate duplicate and out-of-order events. > > Deliver the settlement and reversal services, the webhook handlers, tests for settle, a duplicate event, an out-of-order event, and reversal quote expiry, and a state diagram of the trade states you handle. > ``` > [accordion] Payouts end to end > > Builds recipients, payout addresses, quotes, payouts, confirmation, and lifecycle tracking. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Build a payout feature on the OpenFX v3 Payments API: create recipients, register payout addresses, price a payout, send it, and track it to a terminal state. > > Read first: https://docs.openfx.com/v3/payouts, https://docs.openfx.com/v3/account-model, https://docs.openfx.com/v3/capabilities, https://docs.openfx.com/v3/supported-networks, the payout integration guide for each currency I ask about, the Payments pages of the API reference, and the payout, account, and payout-address pages under Webhooks. The Payments OpenAPI specification is the source of truth where pages disagree. > > Ask me which currencies and corridors I need before you write code. > > Requirements: > - Follow the order of operations and the required capabilities on the Payouts and Capabilities pages. > - Build a state machine for the payout status values the specification defines, driven by payout webhooks, with the payout endpoint as the fallback. Handle a payout that is created already failed. > - Send an Idempotency-Key on every write. Carry your own ids in metadata. > - Show the fee breakdown from the payout quote. > - Handle capability and address verification states asynchronously. > - If a Payments call returns 403 AUTH_INSUFFICIENT_SCOPE, tell me my API key lacks Payments access, record the exact response, and continue with the tests that don't call the API. > > Deliver services for accounts, payout addresses, and payouts, the webhook handler, a status-machine test suite (happy path, rejected address, quote expiry, failed payout), and a sequence diagram. > ``` > [accordion] Webhooks end to end > > Builds one receiver for every event family with signature verification, deduplication, and state tracking. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Build a production webhook receiver for every OpenFX v3 event we subscribe to. > > Read first: https://docs.openfx.com/v3/webhooks/setup, https://docs.openfx.com/v3/webhooks/authentication, every event page under Webhooks, and the webhook definitions in both OpenAPI specifications. Where a page and the specification differ on the signature header or scheme, follow the specification and tell me. > > Build: > 1. One endpoint that captures the raw body bytes before parsing and verifies the signature in constant time, with the replay window the documentation specifies. > 2. Separate signing secrets per environment, loaded from configuration. > 3. Storage for each event (id, type, payload, received time). Return 2xx immediately and process from a queue. > 4. Deduplication on event id, and handlers that are idempotent and tolerate out-of-order delivery by comparing against the resource's current state. > 5. State updates for deposits, withdrawals, trades, accounts, payout addresses, and payouts. > 6. A fallback poller for each resource type, because any webhook can be missed. > > Deliver the receiver, verifier unit tests (valid, tampered, wrong secret, stale timestamp), the handlers, and a table that maps each event to the state change it causes. > ``` > [accordion] Idempotency and retries > > Builds persisted idempotency keys, crash recovery, and error-driven retries for every write. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Add a shared idempotency and retry layer in front of every OpenFX v3 write call in this codebase. > > Read first: https://docs.openfx.com/v3/idempotency (including crash recovery and TTL alignment), https://docs.openfx.com/v3/errors (the retry strategy values and the triage guidance), and https://docs.openfx.com/v3/rate-limiting. Take each endpoint's key lifetime from the Idempotency page and the API reference page for that operation. If an endpoint documents no lifetime, use a conservative default, make it configurable, and tell me which endpoints use it. > > Build: > 1. A persistence table for writes (key, endpoint, request body, status, resource id, response body, HTTP status, created and completed times). Insert the row before you send the request. > 2. One Idempotency-Key per logical operation. A quote and the trade that uses it are two operations with two keys. Include Payments writes. > 3. Routing by the retry strategy in the error response, exactly as the Errors page defines each value. Retry with the same key when the strategy says so, check the resource's state before retrying when it says so, and use a new key when resubmitting a corrected request or starting a new operation. For FX trade execution or withdrawal initiation failures, confirm that the resource is missing before starting a new operation. Stop on terminal errors. > 4. Handling for a request that is still in flight and for a key reused with a different body. Treat a key reused with a different body as a bug and alert on it. > 5. A recovery worker that replays rows stuck in flight with the same key, signs each replay with a fresh JWT and request signature, and stops before the endpoint's key lifetime expires. > 6. Capped retries with backoff. On 429, wait for Retry-After. > > For FX writes that time out, reuse the existing key within the idempotency window. After a trade execution or withdrawal initiation failure, complete the resource lookup before submitting a new write. > > Deliver the table migration, the wrapper, the recovery worker, and tests for a crash after send, a request in flight, a mismatched body, and a 429. > ``` ### Debug and review > [accordion] Implement or debug request signing > > Builds a tested JWT and `X-Request-Signature` helper, or diagnoses `401` and `403` responses from an existing one. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Implement or fix OpenFX v3 request authentication in this codebase, and prove it works against Sandbox. > > Read first: https://docs.openfx.com/v3/authentication completely, including the path canonicalization steps and the language samples, https://docs.openfx.com/v3/errors for the authentication and authorization codes, and https://docs.openfx.com/v3/environments. Ask me which language and HTTP client we use if the repository doesn't make it clear. > > Step 1, find out where we are. If the repository has no signing helper, build signRequest({ method, url, body }) so it returns the headers and the exact body bytes to send, following the page for the JWT claims and header, the canonical string, path and query canonicalization, and the P-1363 signature encoding. If a helper exists and requests fail, start from the exact error response for a failing request: error.code, message, details, and the request id. Map the code to its cause using the Errors page. Never print the private key or the full token. > > Step 2, for signature failures, check in this order: > 1. The path you signed against the path you sent, after canonicalization. Watch for double slashes and base URL joins. > 2. The body bytes you hashed against the bytes you sent. Watch for re-serialization and pretty-printing. > 3. DER against P-1363 signature encoding. > 4. Query string sorting and encoding. > 5. The nonce in the signature against the nonce in the JWT header. > Also check the JWT claims and lifetime, and never reuse a JWT or a nonce. > > Step 3, check the environment: key prefix, X-App-Mode, and, for Live keys, the IP allowlist. > > Step 4, add temporary debug logging that prints the canonical string and the decoded JWT header and claims. Reproduce the failure, fix it, and remove the logging. > > Step 5, add unit tests that prove: > - A path with a doubled slash and a path with a dot segment canonicalize to the same path as the clean path. > - Query parameters are sorted by key, then value. > - The raw signature is exactly 64 bytes before base64url encoding. > - Re-serializing the body changes the hash, and the helper returns the exact bytes it hashed. > - Every call gets a new nonce and a JWT lifetime of at most 60 seconds. > > Step 6, make one Sandbox call to list pairs using the key file path I give you, and show me the response status. If I haven't given you a key file path, say so and skip this step. > > Report the root cause if there was one, the fix, and the tests you added. > ``` > [accordion] Review an existing integration > > Audits an integration against the v3 contract and ranks findings by risk to money. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > Audit this codebase's OpenFX v3 integration for correctness and resilience. Don't change code. Produce a ranked findings report. > > Read first: https://docs.openfx.com/llms.txt, then https://docs.openfx.com/v3/authentication, https://docs.openfx.com/v3/environments, https://docs.openfx.com/v3/amounts, https://docs.openfx.com/v3/idempotency, https://docs.openfx.com/v3/errors, https://docs.openfx.com/v3/rate-limiting, https://docs.openfx.com/v3/pagination, https://docs.openfx.com/v3/webhooks/authentication, https://docs.openfx.com/v3/live-checklist, and the OpenAPI specifications. Where a guide page and the specification disagree, follow the specification and tell me. > > Check each area and cite the file and line: > 1. Authentication: a fresh JWT and nonce per request, a lifetime of at most 60 seconds, a request signature with P-1363 encoding, and body bytes hashed equal to the bytes sent. > 2. Environment: X-App-Mode sent explicitly and derived from the same configuration as the key, and Sandbox and Live secrets stored separately. > 3. Money: amounts are strings and parsed as decimals everywhere, with no floats. > 4. Idempotency: a key on every write, including settle, reverse, and Payments writes, stored before sending, reused on retry, and unique per logical operation. > 5. Errors: handling branches on error.code and the retry strategy, retries are capped, and unknown codes reach a generic handler. > 6. Rate limits: 429 handling that honors the documented headers. > 7. Webhooks: verification on the raw body, constant-time comparison, the replay window, deduplication by event id, asynchronous processing, and a fallback poller. > 8. State: status values match the specification, with no assumed statuses. > 9. Pagination: cursor loops terminate. > 10. Secrets and logging: no keys, JWTs, or signatures in logs. > > Output a table with severity, area, file and line, the issue, the failure scenario, and the fix. Put anything that can lose or duplicate money first, then add a short summary and list the areas you couldn't verify. > ``` > [accordion] Prepare for Live > > Verifies readiness and produces a go/no-go report before you switch to Live. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > We are about to switch our OpenFX v3 integration from Sandbox to Live. Verify that we are ready and produce a go/no-go report. > > Read first: https://docs.openfx.com/v3/live-checklist, https://docs.openfx.com/v3/environments, https://docs.openfx.com/v3/rate-limiting, and https://docs.openfx.com/v3/webhooks/setup. > > Check the codebase and configuration against every item on the Live checklist, and ask me for anything you can't check yourself. Don't read or print any key or secret value. > > Output a checklist with PASS, FAIL, or UNVERIFIED for each item with evidence, blocking items first, and a first-day Live test plan that uses small amounts. > ``` ## Verify what the agent built An agent can produce code that looks correct and still fails on the first Live request. Before you rely on it: 1. Run the integration against Sandbox and confirm it completes a trade or a payout end to end. 2. Review the signing helper against [Authentication](/v3/authentication). 3. Confirm every write sends an `Idempotency-Key` that is stored before the request. 4. Confirm webhook handlers verify the signature on the raw body. 5. Work through the [Live checklist](/v3/live-checklist) before you switch to a Live key. ## What's next > [card] [MCP connectors](/v3/mcp-connectors) > > Query your account data from an AI app. > [card] [Live checklist](/v3/live-checklist) > > Review the full pre-launch checklist. # Payouts to Colombia Source: https://docs.openfx.com/v3/cop-payout-integration Pay a Colombian bank account or Bre-B key in COP: register the account or key, then meet the memo and limit rules. Pay a Colombian recipient in Colombian pesos (COP), to a bank account or a Bre-B key. For the general flow, see [Payout lifecycle](/v3/payouts). The quote, confirm, and webhook steps are the same as for EUR, and so is the fee model. [Supported payout currencies](/v3/payouts#supported-payout-currencies) compares every payout currency side by side. ## Before you start * Your organization must be enabled for COP. Until it is, listing the financial accounts that can fund a COP payout fails with `403` PAYOUT_CURRENCY_NOT_ENABLED, and a quote or payout fails with `409` PAYOUT_NOT_ENABLED. * The recipient's account needs the Colombian-peso receiving capability, ACTIVE before you pay. [Capabilities](/v3/capabilities#the-capability-catalog) lists the id, and [Be paid in Colombian pesos](/v3/capabilities#be-paid-in-colombian-pesos) lists the identity the recipient owes. * COP has no sending capability. Don't send a `sender` on a quote or payout, or it fails with `422` SENDER_NOT_SUPPORTED. * Every `POST` needs an `Idempotency-Key` header. See [Idempotency](/v3/idempotency#payments-endpoints). ## Register the bank account or Bre-B key A Colombian recipient can be paid in two ways, and the address you register decides which. The recipient owes a nationality and an identity document, or for an organization a NIT. See [Be paid in Colombian pesos](/v3/capabilities#be-paid-in-colombian-pesos). > [tab] Bank account > > Register the account with `routingFamily` CO_LOCAL, the four-digit `bankCode`, the `accountNumber`, and the `bankAccountType`. The payout goes over CO_ACH. OpenFX decides whether it settles the same day or in the next clearing batch, and you can't choose. > > The `bankAccountType` is checked against the kinds the bank accepts, and a kind it doesn't accept is rejected when you create the address. No name check runs, so `verifications[]` stays empty. > > ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} > curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ > -H "Authorization: Bearer $OPENFX_JWT" \ > -H "X-Request-Signature: $OPENFX_SIGNATURE" \ > -H "Idempotency-Key: $(uuidgen)" \ > -H "Content-Type: application/json" \ > -d '{ > "payoutAddressType": "BANK_ACCOUNT", > "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", > "bankAccount": { > "routingFamily": "CO_LOCAL", > "bankCode": "1007", > "accountNumber": "24512345678", > "bankAccountType": "SAVINGS" > } > }' > ``` > [tab] Bre-B key > > Register the key with `routingFamily` CO_BREB and the `brebKey`, written exactly as the account holder gave it: a mobile number, an email address, an identity document number, or a handle with its leading `@`. You don't say which kind it is. The payout goes over BREB, Colombia's instant transfer system. > > A key lookup (BREB_KEY_LOOKUP) runs while you create the address and compares the holder the key is registered to with the account holder's name. Only a NO_MATCH result rejects the address. A lookup that can't complete leaves it payable. > > Each BREB payout is capped at about COP 12,110,000. A larger `receiveAmount` is refused when the payout is priced, with `422` AMOUNT_OUT_OF_RANGE. `error.details` carries the exact bound. > > ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} > curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ > -H "Authorization: Bearer $OPENFX_JWT" \ > -H "X-Request-Signature: $OPENFX_SIGNATURE" \ > -H "Idempotency-Key: $(uuidgen)" \ > -H "Content-Type: application/json" \ > -d '{ > "payoutAddressType": "BANK_ACCOUNT", > "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", > "bankAccount": { "routingFamily": "CO_BREB", "brebKey": "@camilarestrepo" } > }' > ``` ## Memos On CO_ACH and BREB, a `receiverMemo` is at most 40 letters, digits, and spaces. A memo that is too long or holds any other character fails with `400` RECEIVER_MEMO_INVALID. OpenFX never truncates it. ## Track settlement [Trace a payout with the receiving bank](/v3/payouts#trace-a-payout-with-the-receiving-bank) lists the `settlementTraceId` key for CO_ACH and BREB. ## Common mistakes * **Naming a `sender`.** COP has no sending capability. Remove `sender` from the quote and the payout. * **Sending `purpose`.** Only AED takes one. * **Paying a Bre-B recipient more than the cap.** A `receiveAmount` above about COP 12,110,000 fails with `422` AMOUNT_OUT_OF_RANGE. ## What's next > [card] [Payout lifecycle](/v3/payouts) > > The general payout flow. > [card] [Capabilities](/v3/capabilities#the-capability-catalog) > > The receiving capability and identity each currency needs. > [card] [Payouts in EUR](/v3/eur-payout-integration) > > Paying euro accounts over SEPA or SWIFT. > [card] [Payouts to Mexico](/v3/mxn-payout-integration) > > Paying Mexican bank accounts over SPEI. > [card] [Payouts to the UAE](/v3/aed-payout-integration) > > Paying UAE bank accounts by IBAN. > [card] [Payment Webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Every payout and address event. # Currencies Source: https://docs.openfx.com/v3/currencies Fiat and stablecoin currencies for FX trading, first-party withdrawals, and payout funding, with rails, networks, and early-access labels. This catalog is for two first-party flows: FX trading, and withdrawals to a verified account you own. Use it to pick the `currency` value on `/v3/fx/` requests, validate inputs before a quote, and see which assets are still early access. It does not list receive currencies for third-party payouts. Those are a separate catalog: [Supported payout currencies](/v3/payouts#supported-payout-currencies) lists the currencies you can pay to someone else's bank account. > [!NOTE] > > **Source of truth for trading.** Trading pairs can differ by organization. > [`GET /v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs) > is the live list of what *your* account can trade. The tables below are the > platform-wide set. An account's enabled subset may be smaller. Request more > pairs through Customer Success at > [support@mail.openfx.com](mailto:support@mail.openfx.com). For how amounts are encoded as strings, and how precision works in requests and responses, see [Amounts](/v3/amounts). ## What this catalog covers | Flow | What you do | How you learn what is enabled | | - | - | - | | FX trading | Quote and execute a conversion | [`GET /v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs) | | First-party withdrawal | Send from your balance to a [verified withdrawal account](/v3/verified-accounts) you own | Rails and networks in the tables below, bound to that account | A code that appears here can be a valid `CurrencyCode` on a payout request and still fail later: payout support is gated by capability coverage and the destination address, not by this list. ## Currency code format Currencies use the `CurrencyCode` type (regex `^[A-Z0-9]{2,15}$`). * Fiat follows ISO 4217 (USD, EUR, GBP). * Stablecoins use canonical tickers (USDC, USDT, EURC). * Codes are case-sensitive and always uppercase. ## Fiat For first-party fiat withdrawals, rails accept at most 2 decimal places (for example `"1000.00"`) and reject sub-cent amounts. This rail limit does not constrain FX amounts: FX requests and responses may contain up to 16 fractional digits. See [Amounts](/v3/amounts). | Name | Code | First-party withdrawal rails | | - | - | - | | US Dollar | USD | Fedwire, SWIFT | | Euro | EUR | SEPA, SEPA Instant, SWIFT | | British Pound | GBP | FPS, CHAPS, SWIFT | | Mexican Peso | MXN | SPEI | | UAE Dirham | AED | UAEFTS, SWIFT | | Australian Dollar | AUD | NPP | | Brazilian Real | BRL | PIX | | Colombian Peso | COP | PSE, ACH | | Argentine Peso Beta | ARS | Transferencia 3.0 | | Philippine Peso | PHP | PESONet | Beta currencies are available for integration testing. The contract may still change. Do not promise production SLAs to your customers yet. No state label means the currency is generally available and supported for production traffic. The rails above are first-party withdrawal rails. Third-party payouts route over their own rails, for example CO_ACH and BREB for COP and AE_LOCAL for AED, so a currency can show different rail names here and in the payout catalog. A GBP payout goes over FPS only. Per-currency cut-offs for first-party withdrawals are on [Settlement times](/v3/settlement-times). Confirm cut-offs and submission rules with Customer Success before you integrate Beta fiat. ## Stablecoins For first-party stablecoin withdrawals, rails accept up to 6 decimal places (for example `"1000.123456"`). FX amount schemas allow up to 16 fractional digits. See [Amounts](/v3/amounts). Withdrawal chain selection is bound to the verified withdrawal account, not the `currency` field. A USDC `withdrawableBalance` spans enabled chains until you pick a `withdrawalAccountId`. The API `network` value for each chain, and how withdrawals route, live on [Supported networks](/v3/supported-networks). | Name | Code | First-party withdrawal networks | | - | - | - | | USD Coin | USDC | Aptos, Arbitrum, Avalanche, Base, Binance Smart Chain, Ethereum, Optimism, Polygon, Solana, Tron | | Tether | USDT | Aptos, Arbitrum, Avalanche, Base, Binance Smart Chain, Ethereum, Optimism, Polygon, Solana, Tron | | Euro Coin | EURC | Avalanche, Base, Ethereum, Solana | ## How `currency` is used per endpoint | Endpoint | What `currency` means | | - | - | | [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances) | One row per currency. `currency` is the account-side identifier. | | [`POST /v3/fx/quotes`](/v3/api-reference/trade/create-quote) | `buyCurrency` + `sellCurrency`, plus exactly one of `buyAmount` or `sellAmount`. | | [`POST /v3/fx/trades`](/v3/api-reference/trade/execute-trade) | Inherited from the quote. No `currency` field on the trade body. | | [`POST /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/create-withdrawal) | Currency leaving the balance. Must match the verified withdrawal account’s currency. | | [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits) | Detected from the incoming wire or on-chain transfer. | ## Adding a new currency The listed set is the platform default. To request a trading pair or account-level enablement, contact Customer Success at [support@mail.openfx.com](mailto:support@mail.openfx.com). Once enabled, pairs show up in [`GET /v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs) and can be quoted immediately. ## What's next > [card] [Payouts](/v3/payouts) > > Third-party payouts to a recipient's bank account. > [card] [Supported networks](/v3/supported-networks) > > Stablecoin × chain matrix, API `network` values, and withdrawal routing. > [card] [Settlement times](/v3/settlement-times) > > Fiat-rail submission cut-offs for first-party withdrawals. > [card] [Amounts](/v3/amounts) > > String-encoding rules and per-currency precision. # Deposits Source: https://docs.openfx.com/v3/deposits Deposit status values, detection mechanics per rail, and the reconciliation pattern for incoming funds. A deposit record uses one of the four statuses listed below. A deposit starts as PENDING and ends in exactly one of the other three. > [!NOTE] > > A deposit reaches COMPLETED when the funds are > credited to your balance. Use the [Deposit completed webhook](/v3/webhooks/deposits/deposit-completed) > to receive completion updates. Use [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits) > with cursor pagination to reconcile deposit records and check their current > statuses when a webhook is unavailable. ## State machine ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% stateDiagram-v2 direction TB [*] --> PENDING: OpenFX observes incoming funds PENDING --> COMPLETED: Funds credited to your balance PENDING --> REJECTED: Bank rejects the deposit PENDING --> ERROR: Processing error COMPLETED --> [*] REJECTED --> [*] ERROR --> [*] classDef ok stroke-width:1px classDef bad stroke-width:1px classDef pending stroke-width:1px classDef hold stroke-width:1px classDef returned stroke-width:1px classDef neutral stroke-width:1px class PENDING pending class COMPLETED ok class REJECTED,ERROR bad ``` | Status | Meaning | | - | - | | PENDING | OpenFX has observed the incoming funds. They are not in your balance yet | | COMPLETED | The funds are credited to your balance. Final | | REJECTED | The bank rejected the deposit. Final | | ERROR | A processing error stopped the deposit. Final | Only COMPLETED sends a webhook; poll [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits) to see the other two. ## How OpenFX detects deposits | Rail | Detection mechanism | | - | - | | Stablecoin (see [Supported networks](/v3/supported-networks) for the chain matrix) | On-chain monitoring of OpenFX's wallet addresses | | Wire (Fedwire) | Bank notification webhook from partner | | ACH | Bank file processing | ## Listing recent deposits ```bash theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl "https://api.openfx.com/v3/fx/deposits?limit=25" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" ``` Deposit lists use cursor pagination with `startingAfter` and `endingBefore`. See [Pagination](/v3/pagination). ## Field reference * `id`: permanent deposit ID (readable, `dpt_`-prefixed) * `depositAmount`, `currency`: what was deposited * `network`: settlement network (for example, ETHEREUM for a stablecoin deposit); `null` for a fiat deposit * `transactionHash`: on-chain transaction hash for crypto deposits, `null` otherwise * `referenceId`: external reference id supplied by the customer, if any * `paymentDetails`: payment-rail-specific identifiers keyed by transfer type (for example, Fedwire IMAD/OMAD). Present only for fiat deposits; `null` for crypto deposits and any deposit without rail metadata * `createdAt`: when OpenFX first observed the deposit ## Common mistakes * **Ignoring `network` for stablecoin reconciliation.** A USDC deposit on Ethereum and a USDC deposit on Polygon are both USDC but different on-chain rails: read `network` to tell them apart. * **Reaching for `transactionHash` on a fiat deposit.** It's `null` for fiat. Match fiat deposits on `referenceId` and `paymentDetails` instead. * **Waiting for a webhook on a failed deposit.** fx.deposit.completed is the only deposit webhook. A REJECTED or ERROR deposit sends nothing, so poll `GET /v3/fx/deposits` to find it. ## What's next > [card] [Settlement models](/v3/settlement-models) > > How deposits flow into balances and out as withdrawals. > [card] [Withdrawals](/v3/withdrawals) > > The companion state machine. > [card] [Pagination](/v3/pagination) > > Cursor-based reconciliation patterns. # Environments Source: https://docs.openfx.com/v3/environments The Sandbox and Live environments available on the OpenFX API, and how a request selects between them. OpenFX runs Sandbox and Live on the **same base URL** (`api.openfx.com`). Use `X-App-Mode` to select SANDBOX or LIVE. Each API key is bound to one environment and must match the environment you select. Omit it and the request defaults to SANDBOX, so a Live key must send `X-App-Mode: LIVE` explicitly or the request fails with `403` AUTH_API_KEY_SANDBOX_REQUIRED. Any other value returns `400` INVALID_APP_MODE. Sandbox API keys carry a **`sandbox_` prefix**; Live keys are unprefixed, so you can tell the two apart at a glance. Sandbox and Live use the same endpoints, code paths, and rate-limit ceiling; the difference is real-vs-simulated funds and the key prefix. Code validated in Sandbox therefore follows the same API contract, traffic pattern, and rate limits in Live. ## Sandbox vs Live | Aspect | Live | Sandbox | | - | - | - | | Base URL | `api.openfx.com` | `api.openfx.com` (same) | | API key | Unprefixed (bound to env server-side) | `sandbox_`-prefixed (bound to env server-side) | | `X-App-Mode` header | LIVE | SANDBOX | | Real funds | Yes | No (simulated) | | Webhook signing key | Unprefixed | `sandbox_`-prefixed | | Rate limits | 300 requests / 10-second window | 300 requests / 10-second window (same as Live) | | Data persistence | Permanent | May reset periodically | Sandbox and Live share the same rate-limit ceiling as separate buckets, so a traffic pattern validated in Sandbox carries over directly. See [Rate limiting](/v3/rate-limiting) for the back-off pattern. ## Sample request A Sandbox call differs from a Live call by the `sandbox_`-prefixed key and the `X-App-Mode` value; everything else, including the required `X-Request-Signature`, is the same. > [!WARNING] > > **Use the interactive API reference playground with Sandbox credentials > only.** Never paste a Live key or Live `X-App-Mode` value into a browser-based > tool. Use a language sample with your own request-signing code for Live calls > instead. ```bash theme={"theme":{"light":"poimandres","dark":"poimandres"}} # X-Request-Signature is an ES256 signature over the canonical request string; # compute it with one of the language helpers in /v3/authentication (shell signing is impractical). # Sandbox curl https://api.openfx.com/v3/fx/pairs \ -H "Authorization: Bearer $OPENFX_SANDBOX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: SANDBOX" # Live curl https://api.openfx.com/v3/fx/pairs \ -H "Authorization: Bearer $OPENFX_LIVE_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: LIVE" ``` The JWT in each case was minted with the matching environment's API key (Sandbox keys carry a `sandbox_` prefix; Live keys don't). See [Authentication](/v3/authentication) for the minting flow. ## Safety net: wrong-environment errors If your key doesn't match the environment you're trying to reach, OpenFX rejects the request instead of silently doing the wrong thing: you can't accidentally execute a Live trade with Sandbox credentials, or vice versa. | Error code | When you'll see it | | - | - | | AUTH_API_KEY_SANDBOX_REQUIRED | A Live key reaches Sandbox, including a Live key that omits `X-App-Mode` | | AUTH_API_KEY_LIVE_REQUIRED | Live traffic uses a Sandbox key | Both codes return AUTHORIZATION_ERROR / 403: the request authenticated successfully, but the key isn't valid for this environment. An `X-App-Mode` value other than LIVE or SANDBOX returns `400` INVALID_APP_MODE, and `details.allowed` lists the accepted values. Full entries live in the v3 [error catalog](/v3/errors#error-code-catalog). ## Going live The full pre-launch list lives in the [Live checklist](/v3/live-checklist). The minimum cutover from a working Sandbox integration is: **1. Swap credentials** Replace the Sandbox `kid` and `privateKey` in your secrets store with the Live values from the dashboard. **2. Set X-App-Mode to LIVE** Send `X-App-Mode: LIVE` on every request. An omitted header defaults to SANDBOX, and a Live key then returns `403` AUTH_API_KEY_SANDBOX_REQUIRED. Wire the value from the same config that selects your key. **3. Update webhook signing key** Live webhook signing keys are unprefixed; Sandbox keys start with `sandbox_`. Point your verifier at the Live signing key. > [!TIP] > > Run end-to-end through Sandbox first. Identical endpoints, code paths, and > rate limits mean what works in Sandbox works in Live, including load patterns > tested against the 300 req/10s ceiling. ## Common mistakes * **Mixing credentials in the same process.** Two key pairs (one Sandbox, one Live) stored in two distinctly-named secrets. Never read `OPENFX_KEY` and hope it's the right one. * **Assuming Sandbox data persists.** Sandbox may be reset periodically; don't seed long-running test workflows with Sandbox IDs you expect to still exist next month. * **Hard-coding the base URL.** It's the same in both environments, but writing `api.openfx.com` as a literal in two places will trip you up the day OpenFX adds a regional endpoint. * **Sending an `X-App-Mode` value that doesn't match the key.** The header and the key's bound environment must agree. Wire it from the same environment-aware config that selects your key, not a hard-coded constant. ## What's next > [card] [Live checklist](/v3/live-checklist) > > Full pre-launch checklist: keys, IP allowlist, monitoring. > [card] [Authentication](/v3/authentication) > > JWT minting flow with code samples in Node, Python, Java, C++, and Go. > [card] [Errors](/v3/errors#authentication-authorization) > > `AUTH_*` codes and recovery patterns. # Errors Source: https://docs.openfx.com/v3/errors Errors return in a stable, machine-readable envelope with a code, type, human message, retry strategy, and per-code details. Every v3 error response has the same shape, regardless of status code. Wire your client up once to switch on `error.code` and you're done. > [!NOTE] > > **`type` is required on every v3 error.** Alongside `code` and `message`, the > `type` field is now a **mandatory** part of the envelope: it is always present > on every non-2xx response and is part of the OpenAPI `required` set. You can > safely rely on `error.type` for coarse routing (auth vs validation vs > CONFLICT vs rate-limited vs internal) without null-checks. Treat a response > without `type` as a transport-level bug, not a normal API outcome. ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "error": { "code": "QUOTE_EXPIRED", "type": "CONFLICT", "message": "The quoted rate has expired. Request a new quote.", "retryStrategy": "FIX_AND_RESUBMIT", "details": { "quoteId": "qte_3FfGK34vwMvVFDedyb2nkf", "expiredAt": "2026-04-28T10:00:00.000Z" } } } ``` > [!WARNING] > > **The trace ID is in the `X-Trace-Id` response header, not the error body.** > Every response (success and error) carries it. Log it alongside the request > payload; support uses it as the first input on every triage. See [Metadata & > Tracing](/v3/metadata-and-tracing). ## Why this shape A bare `{ "status": "error", "message": "..." }` shape has three problems: 1. **No code.** You'd have to string-match `message`, which breaks the moment a copy edit lands. 2. **No trace ID.** Triage starts with "send us your logs." 3. **No structure.** "Insufficient balance" tells you what's wrong, but not by how much, in which currency. The error envelope below fixes all three. ## Error envelope fields | Field | Type | Required | Notes | | - | - | - | - | | `code` | string | yes | Stable, machine-readable. Format `_`. Never renamed or removed without a major version bump. | | `type` | string | yes | Coarse category. Always present on every error response. One of: VALIDATION_ERROR, AUTHENTICATION_ERROR, AUTHORIZATION_ERROR, NOT_FOUND, CONFLICT, RATE_LIMITED, INTERNAL_ERROR. | | `message` | string | yes | Human-readable. **May change** between versions. Switch on `code`, not `message`. | | `retryStrategy` | string | yes | Machine-readable recovery hint, independent of `code` and `type`. Always present. One of: RETRY_SAME_KEY, WAIT_THEN_RETRY_SAME_KEY, FIX_AND_RESUBMIT, CHECK_STATE_THEN_RETRY, TERMINAL. See [Triage matrix](#triage-matrix). | | `details` | object | yes | Per-code, structured context. Shape varies by `code`. Always present (`{}` when there is no structured context for this code). | Errors are returned as `application/json`; the envelope above is the complete contract. > [!NOTE] > > **Error responses never carry a `metadata` field.** Client-supplied > request-body `metadata` is echoed back only on **success** responses. On any > non-2xx, the envelope is exactly `code`, `type`, `message`, `retryStrategy`, > and `details`. Don't look for your request `metadata` on an error. ## Triage matrix `error.retryStrategy` is the direct, server-declared signal for how to react. Read it instead of pattern-matching on `error.code` or HTTP status. It's one of five values, and every error response carries one: | `retryStrategy` | Meaning | Example codes | | - | - | - | | RETRY_SAME_KEY | Safe to retry immediately with the same `Idempotency-Key`. Reserved for future use (no current code emits this value, but you must still handle it). | *(none currently)* | | WAIT_THEN_RETRY_SAME_KEY | Transient backpressure, then retry with the **same** key. RATE_LIMIT_EXCEEDED and IDEMPOTENCY_IN_FLIGHT carry `Retry-After` (seconds); wait that long. IDEMPOTENCY_UNAVAILABLE carries no `Retry-After`; apply your own short backoff. | RATE_LIMIT_EXCEEDED, IDEMPOTENCY_IN_FLIGHT, IDEMPOTENCY_UNAVAILABLE | | FIX_AND_RESUBMIT | This exact request cannot succeed as submitted. Fix the request or wait out the blocking state, then resubmit with a **new** key. | VALIDATION_BODY_FAILED, WITHDRAWAL_INSUFFICIENT_BALANCE, QUOTE_EXPIRED, IDEMPOTENCY_MISMATCH | | CHECK_STATE_THEN_RETRY | Indeterminate write. `GET /v3/fx/{resource}/{id}` first (using `details.resourceId` when present) before deciding whether to retry. | TRADE_EXECUTION_FAILED, WITHDRAWAL_INITIATION_FAILED, INTERNAL_ERROR | | TERMINAL | Do not retry. Auth failures, `*_NOT_FOUND`, and account-level policy blocks. | AUTH_TOKEN_EXPIRED, TRADE_NOT_FOUND, TRADE_DISABLED, WITHDRAWAL_DISABLED_FOR_ACCOUNT | Default-handle unknown future `retryStrategy` values as TERMINAL, the same open-vocabulary rule as `error.code` and `error.type` (see [Client error modeling](#client-error-modeling)). The table below cross-references the same catalog by HTTP status, for clients that key off status first: | HTTP status | `type` examples | Behavior bucket | Example codes | | - | - | - | - | | **400** schema | VALIDATION_ERROR | Your JSON is malformed or has wrong field types. Fix and resubmit. | VALIDATION_BODY_FAILED, VALIDATION_QUERY_FAILED, VALIDATION_PATH_FAILED, VALIDATION_CONTENT_TYPE | | **401** auth | AUTHENTICATION_ERROR | Token missing, invalid, or expired. Mint a fresh JWT. | AUTH_TOKEN_EXPIRED, AUTH_API_KEY_INVALID | | **403** authz | AUTHORIZATION_ERROR | Authenticated, but not allowed. Check your key's scope, IP allowlist, environment, and product entitlement. | AUTH_INSUFFICIENT_SCOPE, AUTH_FORBIDDEN_IP, SANDBOX_MODE_REQUIRED, TRADE_DISABLED, FEATURE_NOT_ENABLED | | **404** not found | NOT_FOUND | Resource doesn't exist. Treat as terminal in your app. | TRADE_NOT_FOUND, WITHDRAWAL_NOT_FOUND, DEPOSIT_NOT_FOUND | | **405** method | VALIDATION_ERROR | Wrong HTTP method on this path. Check the API reference. | METHOD_NOT_ALLOWED | | **409** state conflict | CONFLICT | Well-formed request blocked by current state. Resolve state, then retry as a new operation. | WITHDRAWAL_INSUFFICIENT_BALANCE, TRADE_INSUFFICIENT_BALANCE, IDEMPOTENCY_IN_FLIGHT, QUOTE_EXPIRED, QUOTE_ALREADY_CONSUMED, TRADE_CREDIT_LIMIT_EXCEEDED | | **413** payload too large | VALIDATION_ERROR | The request body exceeds the endpoint's payload limit. Reduce the body size and resubmit. | VALIDATION_PAYLOAD_TOO_LARGE | | **422** semantic | VALIDATION_ERROR, CONFLICT | Well-formed input that violates a business rule. Fix the value and resubmit. | WITHDRAWAL_INVALID_AMOUNT_PRECISION, TRADE_AMOUNT_ABOVE_LIMIT, IDEMPOTENCY_MISMATCH | | **428** missing precondition | VALIDATION_ERROR | A required precondition header is missing. Add it and retry with the SAME key. | IDEMPOTENCY_KEY_MISSING | | **429** rate limited | RATE_LIMITED | Wait `Retry-After` seconds, then retry with the same key. | RATE_LIMIT_EXCEEDED | | **500** internal | INTERNAL_ERROR | Server error. For write paths that echo `details.resourceId` (TRADE_EXECUTION_FAILED, WITHDRAWAL_INITIATION_FAILED), check state by ID before retrying. See [Retrying trade execution or withdrawal initiation](#retrying-trade-execution-failed). | INTERNAL_ERROR, TRADE_EXECUTION_FAILED, WITHDRAWAL_INITIATION_FAILED | | **503** unavailable | INTERNAL_ERROR | A required upstream dependency (the idempotency service) is temporarily unreachable. Wait, then retry with the same key. | IDEMPOTENCY_UNAVAILABLE | ## Decision flow Use `error.retryStrategy` to choose a recovery strategy, then use `error.code` for resource-specific steps such as recovering a failed trade or withdrawal. ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% flowchart LR Start([API call returns non-2xx]) --> ReadCode{{Read error.code}} ReadCode --> Auth401(["401 AUTH_TOKEN_*
AUTH_API_KEY_INVALID
AUTH_API_KEY_MISSING?"]) ReadCode --> Authz403(["403 AUTH_FORBIDDEN_IP
AUTH_INSUFFICIENT_SCOPE
SANDBOX_MODE_REQUIRED
*_KEY_*_REQUIRED?"]) ReadCode --> Schema400(["400 VALIDATION_BODY_FAILED
VALIDATION_QUERY_FAILED
VALIDATION_PATH_FAILED?"]) ReadCode --> Semantic422(["422 *_INVALID_AMOUNT_PRECISION
TRADE_AMOUNT_*_LIMIT
IDEMPOTENCY_MISMATCH?"]) ReadCode --> Precondition428(["428 IDEMPOTENCY_KEY_MISSING?"]) ReadCode --> Idem(["IDEMPOTENCY_IN_FLIGHT?"]) ReadCode --> Rate(["429 RATE_LIMIT_EXCEEDED?"]) ReadCode --> NotFound(["404 *_NOT_FOUND?"]) ReadCode --> StateConflict(["409 *_INSUFFICIENT_*
*_LIMIT_REACHED
QUOTE_EXPIRED
*_ADDRESS_NOT_VERIFIED?"]) ReadCode --> ExecFailed(["500 TRADE_EXECUTION_FAILED
WITHDRAWAL_INITIATION_FAILED?"]) ReadCode --> Internal(["500 INTERNAL_ERROR?"]) Auth401 -->|yes| MintToken[/"Mint a fresh JWT.
If it still fails, check API key validity in the dashboard."/] Authz403 -->|yes| CheckEntitlement[/"Check IP allowlist, key scope, environment header."/] Schema400 -->|yes| FixSchema[/"Fix the request shape.
Resubmit with NEW idempotency key."/] Semantic422 -->|yes| FixSemantic[/"Fix the business-rule violation in details.
Resubmit with NEW key.
IDEMPOTENCY_MISMATCH = reused key with different body."/] Precondition428 -->|yes| AddHeader[/"Add the Idempotency-Key header.
Retry with SAME key."/] Idem -->|yes| WaitRetry[/"Wait, then retry
with the SAME key."/] Rate -->|yes| WaitRetry NotFound -->|yes| Terminal[/"Terminal.
Treat as not found in your app."/] StateConflict -->|yes| ResolveState[/"Resolve underlying state, then retry as NEW operation with NEW key.
For QUOTE_EXPIRED specifically: re-quote."/] ExecFailed -->|yes| CheckState[/"GET the trade or withdrawal by ID.
If found, track the existing resource.
If 404, use a NEW key and, for trades, a fresh quote."/] Internal -->|yes| Investigate[/"For writes, reconcile resource state before retrying."/] classDef ok stroke-width:1.5px classDef bad stroke-width:1.5px classDef info stroke-width:1.5px classDef hold stroke-width:1.5px class MintToken,CheckEntitlement,FixSchema,FixSemantic,AddHeader,ResolveState ok class WaitRetry hold class CheckState,Investigate info class Terminal bad class Terminal terminal ``` When in doubt, read `error.retryStrategy` directly. Switch on the specific `error.code` for finer-grained handling, and fall back to the `type` column for categorization. ## HTTP status mapping A duplicate JSON key in a request body returns `400` VALIDATION_BODY_FAILED. A rejected `X-Request-Id` returns `400` VALIDATION_HEADER_FAILED; its `details.issues` identifies the header. Response bodies use `Content-Type: application/json` without a charset parameter. `type` is the coarse routing taxonomy. HTTP status is the wire-level signal. They line up like this: | `type` | Status | Used for | | - | - | - | | VALIDATION_ERROR | **400** | Schema / syntax violations: malformed JSON, wrong types, missing required fields | | VALIDATION_ERROR | **422** | Semantic violations: well-formed input that breaks a business rule, cross-field constraint, or precision rule | | VALIDATION_ERROR | **428** | Missing required precondition header (`Idempotency-Key`) | | VALIDATION_ERROR | **405** | HTTP method not allowed for this path | | VALIDATION_ERROR | **413** | Request body exceeds the endpoint's payload size limit | | AUTHENTICATION_ERROR | **401** | Token missing, invalid, or expired | | AUTHORIZATION_ERROR | **403** | Authenticated, but not allowed: wrong scope, wrong env, IP blocked, account disabled | | NOT_FOUND | **404** | Resource doesn't exist | | NOT_FOUND | **410** | Endpoint has been sunset (v1 after December 31, 2026). `Sunset` + `Link` headers carry the migration info | | CONFLICT | **409** | State-driven conflict: well-formed request blocked by current system state (insufficient balance, expired quote, in-flight idempotency key, exposure limit reached) | | CONFLICT | **422** | IDEMPOTENCY_MISMATCH: same key reused with different parameters | | RATE_LIMITED | **429** | Per-org or per-key rate limit | | INTERNAL_ERROR | **500** | Server error. Read the affected resource state before retrying a write, or retry a read with backoff. Write-path codes may echo `details.resourceId` for the state check. | | INTERNAL_ERROR | **503** | A required upstream dependency (the idempotency service) is temporarily unreachable | **VALIDATION_ERROR spans five statuses, not one.** 400 and 422 carry most of the volume and are worth distinguishing: 400 means "your input didn't pass the schema." 422 means "your input is well-formed JSON of the right types, but it violates a business rule" (a withdrawal amount with too many decimals, a trade above your account limit, an idempotency-key reuse with mismatched body). Modern clients can build different UI flows for the two: 400 → "fix the field"; 422 → "tell the user about the rule." The remaining three are each single-purpose and don't need their own flow: 428 (missing `Idempotency-Key`), 405 (method not allowed), and 413 (payload too large). A common confusion: **negative request-body amount → 400, not 422.** Request amount fields (e.g. `WithdrawalCreateRequest.withdrawalAmount`) are typed as `PositiveAmount` and the schema regex `^[0-9]+(\.[0-9]{1,8})?$` rejects the leading sign. So `POST /v3/fx/withdrawals` with `"withdrawalAmount": "-1.00"` returns `400` VALIDATION_BODY_FAILED (schema), not `422` WITHDRAWAL_INVALID_AMOUNT_PRECISION (semantic). The precision codes (WITHDRAWAL_INVALID_AMOUNT_PRECISION, etc.) are only reached by inputs that already pass the schema regex, i.e. positive numbers with too many fractional digits. **Why two statuses for CONFLICT?** 409 is the state-driven conflict bucket (a fact about the system blocks the request). 422 is reserved for the one case where idempotency-key semantics are violated. ### 404 vs 403: when each fires The boundary between 404 ("doesn't exist") and 403 ("not allowed") is precise in v3. Use this table when classifying a non-2xx that landed before your business logic ran: | Scenario | Status | Code | | - | - | - | | The path doesn't exist in v3 at all | 404 | ROUTE_NOT_FOUND | | The path exists, but the resource ID doesn't, or it belongs to another org (we don't disclose which) | 404 | `*_NOT_FOUND` (e.g. TRADE_NOT_FOUND, QUOTE_NOT_FOUND, WITHDRAWAL_NOT_FOUND, WITHDRAWAL_ADDRESS_NOT_FOUND) | | The path exists, but a specific resource is toggled off for your org | 403 | TRADE_CURRENCY_NOT_ENABLED_FOR_ACCOUNT, WITHDRAWAL_ACCOUNT_NOT_LIVE | | The path exists, but the whole domain is disabled for your org | 403 | TRADE_DISABLED, WITHDRAWAL_DISABLED_FOR_ACCOUNT | | The path exists, but your API key is missing the required scope | 403 | AUTH_INSUFFICIENT_SCOPE | A 404 means the request never reached an entitlement check: it was rejected at routing or hidden for leakage prevention. A 403 means the request reached a handler that knows who you are and is telling you what to fix (or who to contact). Switch on the specific `error.code` rather than the status to decide the next action. **Product-level entitlement uses `_DISABLED` codes.** A `_DISABLED` code means access has been revoked or blocked; this catalog defines TRADE_DISABLED and WITHDRAWAL_DISABLED_FOR_ACCOUNT (both 403). The second names the account scope in its suffix. Resource-level toggles keep their own codes (TRADE_CURRENCY_NOT_ENABLED_FOR_ACCOUNT). Only codes in the generated catalog are part of the contract. ## Code stability guarantee Once a code ships in v3, **it does not get renamed or removed without a major version bump.** New codes may be introduced in a minor version. ### Client error modeling **Treat `error.code`, `error.type`, and `error.retryStrategy` as non-exhaustive (open) vocabularies.** All three can gain new members in a minor version, so model each as an open enum: switch on the value but **always keep a `default` branch**. When you hit a value you don't recognize: * Handle an **unknown `error.type`** as INTERNAL_ERROR (treat it as a server-side category you don't yet model). * Bubble up an **unknown `error.code`** with its `X-Trace-Id` so a newly-added code never silently breaks your client. * Handle an **unknown `error.retryStrategy`** as TERMINAL (the safest default: don't retry automatically). This keeps your client forward-compatible: a code, type, or retry strategy added after you shipped degrades to a safe default instead of an unhandled branch. **Every `details` object is typed and closed.** Each code maps to a dedicated schema through `x-openfx-error-catalog`; codes without additional context reference the shared closed `EmptyErrorDetails` schema. Adding an optional detail field is additive. Removing or renaming a field, or making an optional field required, is a breaking change. ## Error code catalog The FX and Payments APIs define **109 distinct error codes**; a code shared by both appears once, or once per surface when the surfaces define it differently. The OpenAPI extension `x-openfx-error-catalog` is the source of truth for status, client action, lifecycle, and the closed `details` schema. > [tab] Authentication > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | AUTH_API_KEY_INVALID | 401 | AUTHENTICATION_ERROR | The referenced API key does not exist or is inactive. | `{}` | Do not retry automatically; correct access or surface the error. | > | AUTH_API_KEY_LIVE_REQUIRED | 403 | AUTHORIZATION_ERROR | Live traffic uses a Sandbox API key. | `{}` | Do not retry automatically; correct access or surface the error. | > | AUTH_API_KEY_MISSING | 401 | AUTHENTICATION_ERROR | The bearer token does not reference an API key. | `{}` | Do not retry automatically; correct access or surface the error. | > | AUTH_API_KEY_SANDBOX_REQUIRED | 403 | AUTHORIZATION_ERROR | Sandbox traffic uses a Live API key. | `{}` | Do not retry automatically; correct access or surface the error. | > | AUTH_FORBIDDEN_IP | 403 | AUTHORIZATION_ERROR | The source IP address is outside the API key allowlist. | `{ ip? }` | Do not retry automatically; correct access or surface the error. | > | AUTH_INSUFFICIENT_SCOPE | 403 | AUTHORIZATION_ERROR | The API key lacks a scope required by the operation. | `{}` | Do not retry automatically; correct access or surface the error. | > | AUTH_TOKEN_EXPIRED | 401 | AUTHENTICATION_ERROR | The bearer token expiry time is in the past. | `{ expiredAt? }` | Do not retry automatically; correct access or surface the error. | > | AUTH_TOKEN_INVALID | 401 | AUTHENTICATION_ERROR | The bearer token or request signature is malformed or fails verification. | `{ reason? }` | Do not retry automatically; correct access or surface the error. | > | AUTH_TOKEN_INVALID_CONFIG | 401 | AUTHENTICATION_ERROR | The bearer token claims or validity window violate the authentication contract. | `{ reason, maxSeconds? }` | Do not retry automatically; correct access or surface the error. | > | AUTH_TOKEN_MISSING | 401 | AUTHENTICATION_ERROR | The Authorization header is missing. | `{}` | Do not retry automatically; correct access or surface the error. | > | SANDBOX_MODE_REQUIRED | 403 | AUTHORIZATION_ERROR | A request reaches the Sandbox environment with an `X-App-Mode` other than SANDBOX, for example LIVE. | `{}` | Do not retry automatically; correct access or surface the error. | > [tab] Validation > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | INVALID_APP_MODE | 400 | VALIDATION_ERROR | The `X-App-Mode` header is present with a value other than LIVE or SANDBOX. Matching ignores case, and an empty value is also rejected. | `{ received, allowed }` | Correct the request or blocking state, then submit a new operation. | > | INVALID_ORGANIZATION | 400 | VALIDATION_ERROR | The organization identifier on the request is malformed. | `{}` | Correct the request or blocking state, then submit a new operation. | > | METHOD_NOT_ALLOWED | 405 | VALIDATION_ERROR | The HTTP method is not supported on the request path. | `{ method, allowed }` | Correct the request or blocking state, then submit a new operation. | > | MISSING_REQUEST_CONTEXT | 400 | VALIDATION_ERROR | The organization, user, or idempotency context every request carries was absent or unreadable. | `{}` | Correct the request or blocking state, then submit a new operation. | > | VALIDATION_BODY_FAILED | 400 | VALIDATION_ERROR | The request body fails schema validation. | `{ issues, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > | VALIDATION_CONTENT_TYPE | 400 | VALIDATION_ERROR | The request's Content-Type is not application/json, or specifies an unsupported charset. | `{}` | Correct the request or blocking state, then submit a new operation. | > | VALIDATION_HEADER_FAILED | 400 | VALIDATION_ERROR | A supplied X-Request-Id header does not match the required format. | `{ issues, firstIssuePath }` | Correct the request or blocking state, then submit a new operation. | > | VALIDATION_PATH_FAILED | 400 | VALIDATION_ERROR | One or more path parameters fail schema validation. | `{ issues, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > | VALIDATION_PAYLOAD_TOO_LARGE | 413 | VALIDATION_ERROR | The request body exceeds the maximum allowed payload size of 8192 bytes. | `{ reason, receivedBytes?, limitBytes }` | Correct the request or blocking state, then submit a new operation. | > | VALIDATION_QUERY_FAILED | 400 | VALIDATION_ERROR | One or more query parameters fail schema validation. | `{ issues, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > | UNSUPPORTED_MEDIA_TYPE | 415 | VALIDATION_ERROR | The request's Content-Type is not application/json. | `{}` | Correct the request or blocking state, then submit a new operation. | > [tab] Idempotency > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | IDEMPOTENCY_IN_FLIGHT | 409 | CONFLICT | Another request with the same idempotency key is still processing. | `{}` | Wait as directed, then retry with the same idempotency key. | > | IDEMPOTENCY_KEY_INVALID | 400 | VALIDATION_ERROR | The Idempotency-Key value does not match ^\[a-zA-Z0-9\_-]\$. | `{}` | Correct the request or blocking state, then submit a new operation. | > | IDEMPOTENCY_KEY_MISSING | 428 | VALIDATION_ERROR | A write request omits the Idempotency-Key header. | `{ endpoint, pattern? }` | Correct the request or blocking state, then submit a new operation. | > | IDEMPOTENCY_MISMATCH | 422 | CONFLICT | An idempotency key is reused with a different request body. | `{ originalRequestHash, firstSeenAt? }` | Correct the request or blocking state, then submit a new operation. | > | IDEMPOTENCY_UNAVAILABLE | 503 | INTERNAL_ERROR | The idempotency service is temporarily unreachable, so the request's Idempotency-Key could not be checked. | `{}` | Wait as directed, then retry with the same idempotency key. | > [tab] Routing > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | ROUTE_NOT_FOUND | 404 | NOT_FOUND | The request path does not match a v3 route. | `{ path }` | Do not retry automatically; correct access or surface the error. | > [tab] Rate limiting > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | RATE_LIMIT_EXCEEDED | 429 | RATE_LIMITED | The organization exceeds its request limit. | `{}` | Wait as directed, then retry with the same idempotency key. | > [tab] Trading > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | TRADE_ALREADY_SETTLED | 409 | CONFLICT | The trade has already been settled. | `{}` | Do not retry automatically; correct access or surface the error. | > | TRADE_AMOUNT_ABOVE_LIMIT | 422 | VALIDATION_ERROR | The trade amount exceeds the organization's maximum. | `{ requestedAmount, currency, limitAmount }` | Correct the request or blocking state, then submit a new operation. | > | TRADE_AMOUNT_BELOW_MINIMUM | 422 | VALIDATION_ERROR | The trade amount is below the organization's minimum. | `{ requestedAmount, currency, minimumAmount }` | Correct the request or blocking state, then submit a new operation. | > | TRADE_CREDIT_LIMIT_EXCEEDED | 409 | CONFLICT | The trade would exceed the organization's exposure limit. | `{ usedAmount, limitAmount, currency }` | Correct the request or blocking state, then submit a new operation. | > | TRADE_CURRENCY_NOT_ENABLED_FOR_ACCOUNT | 403 | AUTHORIZATION_ERROR | The requested currency is not enabled for the organization. | `{ currency }` | Do not retry automatically; correct access or surface the error. | > | TRADE_CURRENCY_NOT_SUPPORTED | 400 | VALIDATION_ERROR | The requested currency is not supported. | `{ currency }` | Correct the request or blocking state, then submit a new operation. | > | TRADE_DISABLED | 403 | AUTHORIZATION_ERROR | Trading is disabled for the organization. | `{}` | Do not retry automatically; correct access or surface the error. | > | TRADE_DUPLICATE_CLIENT_REFERENCE | 409 | CONFLICT | A trade already exists with the given clientReferenceId. | `{}` | Correct the request or blocking state, then submit a new operation. | > | TRADE_EXECUTION_FAILED | 500 | INTERNAL_ERROR | Trade execution fails after the write is accepted. | `{ resourceId, timeoutMs? }` | Read the resource state before deciding whether to retry. | > | TRADE_INSUFFICIENT_BALANCE | 409 | CONFLICT | The sell-side balance is insufficient at execution time. | `{ requiredAmount, availableAmount, currency, side }` | Correct the request or blocking state, then submit a new operation. | > | TRADE_NOT_FOUND | 404 | NOT_FOUND | The trade identifier is unknown or inaccessible to the caller. | `{ tradeId }` | Do not retry automatically; correct access or surface the error. | > | TRADE_NOT_MANUAL | 409 | CONFLICT | The trade is not a manual trade and cannot be settled through this endpoint. | `{}` | Do not retry automatically; correct access or surface the error. | > | TRADE_NOT_REVERSIBLE | 409 | CONFLICT | The trade is outside its reversal window or has already been reversed or settled. | `{}` | Correct the request or blocking state, then submit a new operation. | > | TRADE_NOT_SETTLEABLE | 409 | CONFLICT | The trade isn't in a settleable state (already settled, not yet executed, or reversed). | `{}` | Correct the request or blocking state, then submit a new operation. | > | TRADE_PAIR_NOT_ENABLED_FOR_ACCOUNT | 403 | AUTHORIZATION_ERROR | The requested currency pair is not enabled for the organization. | `{ pair }` | Do not retry automatically; correct access or surface the error. | > | TRADE_PAIR_NOT_SUPPORTED | 400 | VALIDATION_ERROR | The requested currency pair is not supported. | `{ pair }` | Correct the request or blocking state, then submit a new operation. | > | TRADE_PAIR_VOLUME_LIMIT_REACHED | 409 | CONFLICT | The currency pair reaches its global net-position limit. | `{ pair }` | Do not retry automatically; correct access or surface the error. | > [tab] Quotes > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | QUOTE_INVALID_REFERENCE_UNIT | 400 | VALIDATION_ERROR | The reference unit does not match either currency in the requested pair. | `{}` | Correct the request or blocking state, then submit a new operation. | > [tab] Deposits > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | DEPOSIT_NOT_FOUND | 404 | NOT_FOUND | The deposit identifier is unknown or inaccessible to the caller. | `{ depositId }` | Do not retry automatically; correct access or surface the error. | > [tab] Withdrawals > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | WITHDRAWAL_ADDRESS_CHECKSUM_FAILED | 422 | VALIDATION_ERROR | The destination address checksum is invalid for the selected network. | `{ address, network }` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_ADDRESS_CURRENCY_MISMATCH | 422 | VALIDATION_ERROR | The request currency differs from the destination account currency. | `{ expected, received }` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_ADDRESS_NOT_FOUND | 404 | NOT_FOUND | The destination account identifier is unknown or inaccessible to the caller. | `{ accountId }` | Do not retry automatically; correct access or surface the error. | > | WITHDRAWAL_ADDRESS_NOT_VERIFIED | 409 | CONFLICT | The destination account is inactive or unverified. | `{ accountId }` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_CURRENCY_NOT_SUPPORTED | 400 | VALIDATION_ERROR | The requested currency is not supported for withdrawals. | `{}` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_DISABLED_FOR_ACCOUNT | 403 | AUTHORIZATION_ERROR | Withdrawals are currently disabled for the caller's account. | `{}` | Do not retry automatically; correct access or surface the error. | > | WITHDRAWAL_INITIATION_FAILED | 500 | INTERNAL_ERROR | Withdrawal initiation fails after the write is accepted. | `{ resourceId, timeoutMs? }` | Read the resource state before deciding whether to retry. | > | WITHDRAWAL_INSUFFICIENT_BALANCE | 409 | CONFLICT | The available balance is lower than the withdrawal amount. | `{ requiredAmount, availableAmount, currency }` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_INVALID_AMOUNT_PRECISION | 422 | VALIDATION_ERROR | The withdrawal amount exceeds the currency's decimal precision. | `{ maxDecimals, currency }` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_NOT_FOUND | 404 | NOT_FOUND | The withdrawal identifier is unknown or inaccessible to the caller. | `{}` | Do not retry automatically; correct access or surface the error. | > | WITHDRAWAL_PENDING_DEPOSIT_REQUIRED | 409 | CONFLICT | An outstanding settlement deposit must be paid first. | `{ outstandingAmount, currency }` | Correct the request or blocking state, then submit a new operation. | > [tab] Withdrawal accounts > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | WITHDRAWAL_ACCOUNT_CRYPTO_INVALID_RAIL | 400 | VALIDATION_ERROR | The `rail` filter was supplied together with `assetType=CRYPTO`, which has no rail. | `{ rail }` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_ACCOUNT_FIAT_INVALID_NETWORK | 400 | VALIDATION_ERROR | The `network` filter was supplied together with `assetType=FIAT`, which has no network. | `{ network }` | Correct the request or blocking state, then submit a new operation. | > | WITHDRAWAL_ACCOUNT_NOT_LIVE | 403 | AUTHORIZATION_ERROR | The destination withdrawal account is not active. | `{ accountId, status }` | Do not retry automatically; correct access or surface the error. | > [tab] Exposures > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | EXPOSURE_NOT_ENABLED | 403 | AUTHORIZATION_ERROR | No exposure limit is configured for the organization. | `{}` | Do not retry automatically; correct access or surface the error. | > [tab] Platform > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | FEATURE_NOT_ENABLED | 403 | AUTHORIZATION_ERROR | The caller's organization is not enabled for this feature. | `{}` | Do not retry automatically; correct access or surface the error. | > | INTERNAL_ERROR | 500 | INTERNAL_ERROR | An unclassified server-side failure occurs. | `{ resourceId? }` | Wait as directed, then retry with the same idempotency key. | > [tab] Accounts > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | ACCOUNT_ARCHIVED | 409 | CONFLICT | The account named by the request is archived, a one-way state. | `{ accountId }` | Do not retry automatically; correct access or surface the error. | > | ACCOUNT_HOLDER_MISMATCH | 409 | CONFLICT | The receiving-side account holder name check on the destination payout address returned a blocking result, or the account identifier is known bad. | `{}` | Correct the request or blocking state, then submit a new operation. | > | ACCOUNT_NOT_ACTIVE | 409 | CONFLICT | The account's standing with OpenFX is not ACTIVE. | `{ accountId, status }` | Correct the request or blocking state, then submit a new operation. | > | ACCOUNT_NOT_FOUND | 404 | NOT_FOUND | The account identifier is unknown or inaccessible to the caller. | `{}` | Do not retry automatically; correct access or surface the error. | > | AGREEMENTS_NOT_ACTIVE | 409 | CONFLICT | An agreement the organization needs exists but is not active, expired, or revoked. | `{}` | Correct the request or blocking state, then submit a new operation. | > | AGREEMENTS_PENDING | 409 | CONFLICT | An agreement the organization must accept before this payout can settle is still awaiting acceptance. | `{}` | Correct the request or blocking state, then submit a new operation. | > | BENEFICIARY_DETAILS_MISSING | 409 | CONFLICT | A detail the receiving institution requires for this payout is missing from the destination payout address. | `{}` | Correct the request or blocking state, then submit a new operation. | > | FINANCIAL_ACCOUNT_NOT_FOUND | 404 | NOT_FOUND | The financial account identifier is unknown or inaccessible to the caller. | `{}` | Do not retry automatically; correct access or surface the error. | > | IDENTITY_REQUIREMENT_UNMET | 422 | VALIDATION_ERROR | The request exercises a capability the account's supplied identity information does not support. | `{ issues, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > | KYC_REQUIRED | 409 | CONFLICT | A know-your-customer check the receiving side requires has not cleared. | `{}` | Correct the request or blocking state, then submit a new operation. | > [tab] Capabilities > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | ADDRESS_SERVES_NO_CAPABILITY | 409 | CONFLICT | The account the payout address would belong to holds no capability able to receive at it, in any status. | `{ accountId, required }` | Correct the request or blocking state, then submit a new operation. | > | CAPABILITY_DUPLICATE | 422 | VALIDATION_ERROR | The account already holds a cell for a requested capability, or the request names the same capability twice. | `{ duplicates, issues?, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > | CAPABILITY_NOT_ACTIVE | 409 | CONFLICT | The account named for this activity holds no ACTIVE capability covering what the request needs. | `{ accountId, required, capabilityId, status }` | Correct the request or blocking state, then submit a new operation. | > | CAPABILITY_NOT_REQUESTABLE | 422 | VALIDATION_ERROR | A requested capability is one this account cannot hold: unknown to the catalog, not offered to its identityType, or retired. | `{ notRequestable, duplicates?, issues?, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > [tab] Payout addresses > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | BANK_ACCOUNT_NOT_FOUND | 404 | NOT_FOUND | No usable account exists at the submitted identifiers. | `{ reason }` | Correct the request or blocking state, then submit a new operation. | > | PAYOUT_ADDRESS_ARCHIVED | 409 | CONFLICT | The destination payout address, or the account that holds it, is archived. | `{}` | Correct the request or blocking state, then submit a new operation. | > | PAYOUT_ADDRESS_BANK_ACCOUNT_NOT_FOUND | 409 | CONFLICT | No usable bank account was found for the account details of this payout address, so it cannot back a payout. Create a payout address with corrected account details, then retry. | `{}` | Correct the request or resource state before resubmitting. | > | PAYOUT_ADDRESS_CONFLICT | 409 | CONFLICT | The bank details in the request already back a payout address on the same account. | `{ payoutAddressId, status }` | Do not retry automatically; correct access or surface the error. | > | PAYOUT_ADDRESS_FIELD_MISSING | 400 | VALIDATION_ERROR | A field required by the selected routingFamily is missing or invalid. | `{}` | Correct the request or resource state before resubmitting. | > | PAYOUT_ADDRESS_NOT_FOUND | 404 | NOT_FOUND | The payout address identifier is unknown or inaccessible to the caller. | `{}` | Do not retry automatically; correct access or surface the error. | > | PAYOUT_ADDRESS_REJECTED | 409 | CONFLICT | The destination payout address is REJECTED and cannot back a payout. | `{}` | Correct the request or blocking state, then submit a new operation. | > | PAYOUT_ADDRESS_VERIFICATION_FAILED | 409 | CONFLICT | Verification of the payout address failed, so the payout was not created. | `{}` | Correct the request or resource state before resubmitting. | > | VERIFICATION_EXECUTION_FAILED | 500 | INTERNAL_ERROR | The verification could not be performed because of a technical failure on the platform's or the scheme's side. | `{}` | Wait as directed, then retry with the same idempotency key. | > [tab] Payout quotes > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | QUOTE_ALREADY_CONSUMED | 409 | CONFLICT | The quote is already bound to another payout. | `{ quoteId?, consumedAt? }` | Correct the request or blocking state, then submit a new operation. | > | QUOTE_EXPIRED | 409 | CONFLICT | The applied quote has expired. | `{ quoteId?, expiredAt? }` | Correct the request or blocking state, then submit a new operation. | > | QUOTE_NOT_FOUND | 404 | NOT_FOUND | The quote identifier is unknown or inaccessible to the caller. | `{ quoteId? }` | Do not retry automatically; correct access or surface the error. | > | AMOUNT_OUT_OF_RANGE | 422 | VALIDATION_ERROR | The amount is outside the permitted range for payouts to this destination. | `{ issues, firstIssuePath?, amount?, minimum?, maximum?, currency? }` | Correct the request or blocking state, then submit a new operation. | > | CURRENCY_NOT_SUPPORTED | 422 | VALIDATION_ERROR | No rail can deliver the requested receiveCurrency to this destination country. | `{}` | Correct the request or blocking state, then submit a new operation. | > | QUOTE_RAIL_UNAVAILABLE | 422 | VALIDATION_ERROR | No settlement rail serves the requested receiveCurrency to this payout address. | `{}` | Correct the request or blocking state, then submit a new operation. | > | QUOTE_REJECTED | 422 | VALIDATION_ERROR | Pricing declined the request. | `{}` | Correct the request or blocking state, then submit a new operation. | > | QUOTE_SEND_CURRENCY_UNAVAILABLE | 422 | VALIDATION_ERROR | The sendCurrency of the named financial account cannot fund the requested receiveCurrency. | `{}` | Correct the request or blocking state, then submit a new operation. | > | QUOTE_TEMPORARILY_UNAVAILABLE | 409 | CONFLICT | Quoting is temporarily halted for reasons independent of the request. | `{}` | Wait as directed, then retry with the same idempotency key. | > | SENDER_ACCOUNT_REQUIRED | 422 | VALIDATION_ERROR | The payout needs a sender account named on sender and none was supplied. | `{ issues, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > | SENDER_NOT_SUPPORTED | 422 | VALIDATION_ERROR | The payout names a sender, and a payout in this receiveCurrency cannot carry one. | `{ issues, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > [tab] Payouts > > | Code | Status | Type | Trigger | Details | Client action | > | - | -: | - | - | - | - | > | FINANCIAL_ACCOUNT_CURRENCY_MISMATCH | 422 | VALIDATION_ERROR | The financial account's currency does not match the send currency for this payout. | `{}` | Correct the request or resource state before resubmitting. | > | INSUFFICIENT_FUNDS | 409 | CONFLICT | The financial account named by financialAccountId cannot cover this payout's debit. | `{ financialAccountId? }` | Correct the request or blocking state, then submit a new operation. | > | PAYOUT_CANCELLATION_NOT_ALLOWED | 409 | CONFLICT | The payout isn't in REQUIRES_CONFIRMATION. | `{}` | Correct the request or blocking state, then submit a new operation. | > | PAYOUT_CONFIRMATION_NOT_ALLOWED | 409 | CONFLICT | The payout isn't in REQUIRES_CONFIRMATION. | `{}` | Correct the request or blocking state, then submit a new operation. | > | PAYOUT_CURRENCY_NOT_ENABLED | 403 | AUTHORIZATION_ERROR | The organization isn't enabled for payouts in the requested receiveCurrency. | `{ receiveCurrency }` | Do not retry automatically; correct access or surface the error. | > | PAYOUT_NOT_ENABLED | 409 | CONFLICT | The organization has no active provider configuration for this destination and receiveCurrency. | `{}` | Do not retry automatically; correct access or surface the error. | > | PAYOUT_NOT_FOUND | 404 | NOT_FOUND | The payout identifier is unknown or inaccessible to the caller. | `{}` | Do not retry automatically; correct access or surface the error. | > | PAYOUT_TEMPORARILY_UNAVAILABLE | 409 | CONFLICT | Payout processing is temporarily unavailable because of a provider outage or a platform pause. | `{}` | Wait as directed, then retry with the same idempotency key. | > | PURPOSE_INVALID | 422 | VALIDATION_ERROR | The payout's purpose is missing where its receiveCurrency requires one, refused for that receiveCurrency, or given where the receiveCurrency takes none. | `{ issues?, firstIssuePath? }` | Correct the request or blocking state, then submit a new operation. | > | RECEIVER_MEMO_INVALID | 400 | VALIDATION_ERROR | receiverMemo violates the character set or length the bound rail's own grammar allows. | `{}` | Correct the request or blocking state, then submit a new operation. | ## Handling errors: the catch-and-branch pattern Handle known codes that need bespoke behavior first (quote refresh, structured balance details), then fall back to `error.retryStrategy` for everything else. It sorts any current or future code into the right bucket without a client-side code list to maintain. Always capture `X-Trace-Id` before parsing the body, so you have it even when the body is malformed. ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Sign on every attempt. Do not capture one. JWTs have a 60s TTL and the // X-Request-Signature is bound to the JWT's nonce, so a captured pair goes // stale across any wait that approaches the TTL (next attempt fails with // `401 AUTH_TOKEN_EXPIRED` or `401 AUTH_TOKEN_INVALID`). Request bodies are // also consumed by the first fetch(), so retrying the same Request object // throws `TypeError: Body has already been read`. // // The caller passes `method`, `body`, an `extraHeaders` object for things like // `Idempotency-Key` that must stay stable across attempts, and `signRequest`. // Each recursive retry signs fresh and rebuilds the `init`. See Rate limiting → // Handling rate limits pattern (canonical reference): // https://docs.openfx.com/v3/rate-limiting#handling-rate-limits-pattern async function call( url, method, body, extraHeaders, signRequest, attempt = 0, maxAttempts = 5, ) { const signed = signRequest({ method, url, body }); const res = await fetch(url, { method, headers: { ...signed.headers, ...extraHeaders }, body: signed.body, }); const traceId = res.headers.get("x-trace-id"); // Capture FIRST: always present console.log({ url, trace_id: traceId, status: res.status }); if (res.ok) return res.json(); const { error } = await res.json(); switch (error.code) { // Bespoke: quote stale, get a fresh one instead of a blind retry case "QUOTE_EXPIRED": { return refreshQuoteAndRetry(url, method, body, extraHeaders, signRequest); } // Bespoke: surface the structured balance shortfall to the user case "WITHDRAWAL_INSUFFICIENT_BALANCE": { const { requiredAmount, availableAmount, currency } = error.details; throw new Error( `${error.code}: required ${requiredAmount} ${currency}, available ${availableAmount} ${currency} (trace ${traceId})`, ); } } // No code-specific override matched above. Fall back to the // server-declared retryStrategy. This is where every future code lands // automatically, with no client-side code list to maintain. switch (error.retryStrategy) { // Retry immediately with the same Idempotency-Key. case "RETRY_SAME_KEY": { if (attempt + 1 >= maxAttempts) { throw new Error( `Retry budget exhausted: ${error.code} (trace ${traceId})`, ); } return call( url, method, body, extraHeaders, signRequest, attempt + 1, ); // next attempt: fresh JWT + signature } // Transient backpressure. See the Triage matrix above for which codes // carry Retry-After. Falls back to a fixed short wait when it's absent. case "WAIT_THEN_RETRY_SAME_KEY": { const retryAfterHeader = res.headers.get("retry-after"); const retryAfter = retryAfterHeader === null ? NaN : Number(retryAfterHeader); const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 5000; // 5s fallback when Retry-After is absent if (attempt + 1 >= maxAttempts) { throw new Error( `Retry budget exhausted: ${error.code} (trace ${traceId})`, ); } await sleep(waitMs); return call( url, method, body, extraHeaders, signRequest, attempt + 1, ); // next attempt: fresh JWT + signature } // FIX_AND_RESUBMIT, CHECK_STATE_THEN_RETRY, TERMINAL, and any future // unrecognized value: bubble up. The trace ID is always present for support. case "FIX_AND_RESUBMIT": case "CHECK_STATE_THEN_RETRY": case "TERMINAL": default: throw new Error( `API error: ${error.code} (${error.retryStrategy}) — ${error.message} (trace ${traceId})`, ); } } // Usage: // const idempotencyKey = randomUUID(); // stable per logical operation // const body = JSON.stringify(payload); // await call( // 'https://api.openfx.com/v3/fx/trades', // 'POST', // body, // { 'Idempotency-Key': idempotencyKey }, // stable across attempts; merged after signed headers // signRequest, // ); ``` > [!TIP] > > **Don't retry blindly on 5xx.** When `error.retryStrategy` is > CHECK_STATE_THEN_RETRY (e.g. TRADE_EXECUTION_FAILED, > WITHDRAWAL_INITIATION_FAILED, INTERNAL_ERROR) on a write endpoint, GET the > resource by `details.resourceId` before deciding to retry. See [the rule > below](#retrying-trade-execution-failed). When in doubt, fetch the resource by > ID before retrying. See [Idempotency → Crash > recovery](/v3/idempotency#crash-recovery). ### Retrying trade execution or withdrawal initiation A trade or withdrawal may already exist when you receive a `500` TRADE_EXECUTION_FAILED or WITHDRAWAL_INITIATION_FAILED response. During the [idempotency window](/v3/idempotency#endpoints), sending the same request with the same key replays the original failure. 1. Use `error.details.resourceId` from the failure to look up the resource. For a trade, call [Get a trade](/v3/api-reference/trade/get-trade) (`GET /v3/fx/trades/{id}`). For a withdrawal, call [Get a withdrawal](/v3/api-reference/trade-settlement/get-withdrawal) (`GET /v3/fx/withdrawals/{id}`). 2. If the resource exists, continue tracking its status and stop retrying the create request. 3. If the lookup returns `404` TRADE_NOT_FOUND, request a fresh quote and submit the trade with a new `Idempotency-Key`. If it returns `404` WITHDRAWAL_NOT_FOUND, submit the withdrawal with a new `Idempotency-Key`. If the lookup fails for another reason, resolve the lookup failure before submitting a new write. ## Common mistakes * **Switching on `message` instead of `code`.** `message` is human-readable and may be rephrased between releases. Only `code` is stable. The trade-up: lock your switch statement to codes the day you ship. * **Forgetting to read `X-Trace-Id` until something breaks.** Capture it on every response (success too) and store it in the same log line as the request. Asking support to find a request without a trace ID adds hours to triage. * **Assuming HTTP status maps cleanly to `error.type`.** Most do, but IDEMPOTENCY_MISMATCH returns **422** with `type: "CONFLICT"`. Always branch on `error.code` for behavior; use `type` only for categorization. * **Rebuilding a code-pattern list to decide retry behavior.** `error.retryStrategy` already carries this. Read it directly instead of maintaining your own mapping of codes to retry buckets. It also covers codes added after you shipped. * **Treating WITHDRAWAL_INSUFFICIENT_BALANCE as retryable.** It's a 409 (well-formed request, state-driven failure). Retrying without resolving the underlying balance hits the same error every time. * **Using a fresh key before checking whether the trade or withdrawal exists.** This can create a duplicate. Follow the [trade and withdrawal recovery steps](#retrying-trade-execution-failed). ## What's next > [card] [Idempotency](/v3/idempotency#how-it-works) > > Understand same-key, different-body collisions and the in-flight rule. > [card] [Rate limiting](/v3/rate-limiting#handling-rate-limits-pattern) > > The back-off pattern for RATE_LIMIT_EXCEEDED. > [card] [Metadata & tracing](/v3/metadata-and-tracing#filing-a-support-ticket) > > Capture `X-Trace-Id` on every response for fast triage. # Payouts in EUR Source: https://docs.openfx.com/v3/eur-payout-integration Pay a euro bank account over SEPA or SWIFT: set up the account and bank details, then price, create, and confirm the payout. Pay a euro bank account over SEPA, or over SWIFT where SEPA can't reach it. This guide covers only what's specific to EUR. For the general flow, see [Payouts](/v3/payouts). The bank account decides the rail, not you: * **SEPA**: an IBAN in a country the SEPA scheme covers. * **SWIFT**: anything else, such as an IBAN outside SEPA or an account with no IBAN. If an address supports both, the payout goes over SEPA. A failed SEPA payout never falls back to SWIFT. ## Set up the account and payout address Before you can pay, three things must be ACTIVE: the account you're paying, its EUR-receiving capability, and the payout address for their bank account. [Account model](/v3/account-model#the-shared-state-machine) explains each status. You do this once. If the account and address already exist, skip to [pricing the payout](#price-and-create-the-payout). **1. Create the organization account** Create the account you're paying, with the EUR-receiving capability, and keep the returned `acc_` id. [Capabilities](/v3/capabilities#the-capability-catalog) lists the capability id and the identity it needs. The capability starts PENDING and usually activates within a minute; wait for [`common.account.capability_activated`](/v3/webhooks/payments/accounts-webhooks/account-capability-activated). You don't need to wait to create the payout address, so do both at the same time. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/common/accounts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "capabilities": ["cap_Ce3AJmAmDGcJgTmTqgFVZ"], "identity": { "identityType": "ORGANIZATION", "organization": { "legalName": "Novalia Handels GmbH", "registeredAddress": { "country": "DE" } } } }' ``` **2. Create the payout address** Create a `BANK_ACCOUNT` payout address for that `acc_`, with `routingFamily` set to SEPA or SWIFT. Send `accountHolderName` only if the bank account is in a different name from the account's. > [tab] SEPA > > Send the IBAN as `accountNumber`. A `bic` is optional; adding one makes the account payable over SWIFT too, and `supportedRails` shows it. > > The IBAN is checked during the call: its country must be in SEPA, and the account must be reachable over SEPA. If either check fails, or the value isn't an IBAN, the request fails and `details.issues[]` says why. Register those accounts with SWIFT instead. > > A name match (Verification of Payee) also runs, but finishes after the call, so the address may come back PENDING. Wait for [`payments.payout_address.activated`](/v3/webhooks/payments/addresses-webhooks/payout-address-activated) or [`payments.payout_address.rejected`](/v3/webhooks/payments/addresses-webhooks/payout-address-rejected), and continue only once the address is ACTIVE. > > ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} > curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ > -H "Authorization: Bearer $OPENFX_JWT" \ > -H "X-Request-Signature: $OPENFX_SIGNATURE" \ > -H "Idempotency-Key: $(uuidgen)" \ > -H "Content-Type: application/json" \ > -d '{ > "payoutAddressType": "BANK_ACCOUNT", > "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", > "bankAccount": { "routingFamily": "SEPA", "accountNumber": "DE89370400440532013000" } > }' > ``` > [tab] SWIFT > > Send the `accountNumber` (it doesn't have to be an IBAN), the bank's `bic`, and the holder's `accountHolderAddress`. > > `accountHolderAddress` is where the account holder lives, not where the bank is, and OpenFX doesn't compare the two. The city and country travel with the payment, so both are required. The BIC must be in a country OpenFX can pay over SWIFT; this is checked during the call. > > SWIFT has no name check, so `verifications[]` is empty. The address still starts PENDING while OpenFX finishes its own setup. Wait for the same two webhooks, and continue only once it's ACTIVE. > > ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} > curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ > -H "Authorization: Bearer $OPENFX_JWT" \ > -H "X-Request-Signature: $OPENFX_SIGNATURE" \ > -H "Idempotency-Key: $(uuidgen)" \ > -H "Content-Type: application/json" \ > -d '{ > "payoutAddressType": "BANK_ACCOUNT", > "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", > "bankAccount": { > "routingFamily": "SWIFT", > "accountNumber": "8801234567", > "bic": "PAVEGE22XXX", > "accountHolderAddress": { > "country": "DE", > "city": "Berlin", > "line1": "Friedrichstrasse 100", > "postalCode": "10117" > } > } > }' > ``` ## Price and create the payout **1. (Optional) List the financial accounts that can fund a EUR payout** Skip this if you already know the `finacc_` id. [List financial accounts](/v3/api-reference/payments/accounts/list-financial-accounts) returns every balance that can fund the payout: a EUR balance pays without conversion, and a USD balance is converted. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl "https://api.openfx.com/v3/common/financial-accounts?receiveCurrency=EUR" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" ``` **2. Quote the payout** Get a price before you create the payout. A quote moves no money. It returns a `pytqte_` id and a rate locked until `fxRates.expiresAt`. The quote shows the `rail`, which sets the fees. Every payout pays a NETWORK_FEE, and a SWIFT payout adds a flat SWIFT_FEE, both in your send currency. They add up to `fees.totalAmount`. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payout-quotes \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "financialAccountId": "finacc_AmKC5dMVXUbiAW8VzKBfqz", "receiver": { "payoutAddressId": "pytadd_PbDQ126YUAbkNrNX6XbGL" }, "sendAmount": "1087.00", "receiveCurrency": "EUR" }' ``` **3. Create the payout from the quote** Create the payout with `type: "FROM_QUOTE"` and the `pytqte_` id. The payout keeps the quote's rate and rail. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payouts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "type": "FROM_QUOTE", "quoteId": "pytqte_5PKPvtstSbXf9BurnLJfLA" }' ``` Besides the QUOTE entry, what `confirmations[]` contains depends on the rail. **SEPA**: the payout includes an `AccountHolderNameConfirmation` comparing the `accountHolderName` you registered with the name the receiving bank holds. If the address's latest Verification of Payee is a MATCH, the payout reuses it and keeps its original `verifiedAt`. Otherwise the check runs again, and `verifiedAt` is when the bank reached that result, so it's null when the check got no answer. A NO_MATCH refuses the payout with `409` ACCOUNT_HOLDER_MISMATCH. An IBAN the scheme reports as invalid returns BANK_ACCOUNT_NOT_FOUND, which refuses the payout with `409` PAYOUT_ADDRESS_BANK_ACCOUNT_NOT_FOUND and rejects the address. Confirming accepts a CLOSE_MATCH or an UNAVAILABLE; PENDING refuses the payout the same way as a NO_MATCH. Cancel to decline it. **SWIFT**: the payout includes a `ReceiveAmountDeductionsConfirmation`. Banks along the way may take their own charges from the payment, so the account can receive less than `receiveAmount`. Those charges aren't known when the payout is priced and aren't part of `fees`. OpenFX adds this entry, so you can't accept it in advance. **4. Confirm the payout** [Confirm the payout](/v3/api-reference/payments/payouts/confirm-payout) to accept everything in `confirmations[]` and move it to ACCEPTED. [Payouts](/v3/payouts) covers confirming and cancelling in more detail. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payouts/pyt_9P3Gs3GSn4hMdHQ22Evi5f/confirm \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" ``` ## Track settlement After ACCEPTED, the payout settles in the background. See [Payouts](/v3/payouts#send-the-payout) for each status and webhook. `settlementTraceId` gives you the payment's reference: the end-to-end identifier on SEPA, or the UETR on SWIFT, which follows the payment through every bank. It doesn't track `Payout.status`, so the create response never has it, and it can still read PENDING after the payout reaches PROCESSED. Use it once it reads AVAILABLE. ## Common mistakes * **Registering a non-SEPA account as SEPA.** SEPA needs an IBAN in a SEPA country. Register anything else as SWIFT, with its `bic` and `accountHolderAddress`. * **Expecting a name check on a SWIFT address.** SWIFT has none, so `verifications[]` stays empty. Check the address `status` instead. * **Skipping the SEPA name check on the payout.** Unless the address's latest result is MATCH, it runs again when you create the payout and can come back different. Read it in `confirmations[]`; don't rely on the address's status. * **Confirming without reading `confirmations[]`.** A CLOSE_MATCH or UNAVAILABLE doesn't block confirmation. The decision is yours. ## What's next > [card] [Payouts](/v3/payouts) > > The general payout flow. > [card] [Capabilities](/v3/capabilities#be-paid-in-euro-over-sepa) > > What the EUR-receiving capability requires. > [card] [Payment Webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Every payout and address event. # Exposure Source: https://docs.openfx.com/v3/exposure The organization's exposure-limit usage: how much is committed to unsettled trades, and the breakdown by currency and settlement stage. **What this is.** OpenFX sets an exposure limit for your organization. It is the amount of unsettled trades you can have open at one time, so you can execute trades and settle them before you withdraw. Every executed trade that hasn't fully settled counts against that limit. [`GET /v3/fx/exposures`](/v3/api-reference/exposure/get-exposure-summary) returns how much of the limit is currently committed, aggregated and broken down by currency. Both [settlement models](/v3/settlement-models) count toward it, in different ways. On an AUTO account, an IMMEDIATE or T0 trade settles at execution even when the sell-side balance is short, and the resulting negative balance counts as exposure. On a MANUAL account, execution returns TRADE_INSUFFICIENT_BALANCE unless the sell-side balance covers the trade, and trades awaiting settlement are held against the limit. A LOCKED T1/T2 trade accrues `settlableLater` exposure on either model. **When it matters.** Before submitting a large trade, to confirm you have headroom left under your exposure limit. When reconciling, to understand why a trade was rejected with TRADE_CREDIT_LIMIT_EXCEEDED. ## Response shape A successful response wraps this in `data`. The exposure summary itself is: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "aggregate": { "currency": "USD", "limitAmount": "50000", "usedAmount": "1200", "availableAmount": "48800", "usageBreakdown": { "settlableNow": "800", "settlableLater": "400" } }, "currencyExposures": [ { "currency": "USD", "exposureAmount": "1200", "usageBreakdown": { "settlableNow": { "amount": "800" }, "settlableLater": { "amount": "400" } } } ] } ``` > [!NOTE] > > Amounts are decimal strings **without fixed precision**: trailing zeros aren't > padded (`"1200"`, not `"1200.00"`). Don't assume a fixed number of decimal > places when parsing. * **`aggregate`** rolls up exposure-limit usage into a single currency (`aggregate.currency`). `limitAmount` is the total exposure limit; `usedAmount` is what's committed; `availableAmount` is the difference and **can be negative** if open exposure currently exceeds the limit (for example, right after a limit reduction). * **`currencyExposures`** breaks the same open exposure down per currency, in each currency's own denomination. A currency with no open trades is omitted from the array rather than listed at zero. > [!NOTE] > > Only currencies with currently open exposure appear in `currencyExposures`. An > empty array means the organization has no open exposure at all. ## Settlable now vs Settlable later Both `aggregate.usageBreakdown` and each currency's `usageBreakdown` split exposure by trade status: * **`settlableNow`**: everything in the open exposure that is not a LOCKED trade. It covers trades in READY_TO_SETTLE, whose settlement window has opened but settlement hasn't been finalized, and, on an AUTO account, the sell-side shortfall left when an IMMEDIATE or T0 trade settled against insufficient funds. That shortfall stays in `settlableNow` after the trade reads EXECUTED. * **`settlableLater`**: the trade is LOCKED, meaning it is future-dated (T1/T2) and its settlement window hasn't opened yet. `settlableNow` and `settlableLater` add up to the open exposure, so `usedAmount` includes any AUTO shortfall. On an AUTO account, which has no READY_TO_SETTLE trades, `settlableNow` is the negative sell-side balance itself. See [Trades](/v3/trades#state-machine) for how `settlementWindow` and `Trade.status` relate, and [Trades → Settlement window](/v3/trades#settlement-window) for what happens when a window opens. ## No exposure limit configured If your organization has no exposure limit configured, the endpoint returns `403` EXPOSURE_NOT_ENABLED instead of a summary. Contact your Customer Success representative at [support@mail.openfx.com](mailto:support@mail.openfx.com) to have a limit configured. ## What's next > [card] [Quotes](/v3/quotes) > > Quote-then-trade workflow and quote lifecycle. > [card] [Settlement models](/v3/settlement-models) > > Balances, deposits, withdrawals, and verified withdrawal accounts. > [card] [Errors](/v3/errors) > > Stable error codes and the retry triage matrix. # Payouts to the UK Source: https://docs.openfx.com/v3/gbp-payout-integration Pay a UK bank account in GBP over Faster Payments: register the sort code and account number, read the UK name check, then price, create, and confirm the payout. Pay a UK bank account in pounds sterling (GBP) over Faster Payments (FPS). This guide covers only what's specific to GBP. For the general flow, see [Payouts](/v3/payouts). [Supported payout currencies](/v3/payouts#supported-payout-currencies) compares every payout currency side by side. ## Before you start * Your organization must be enabled for GBP. Until it is, [`GET /v3/common/financial-accounts`](/v3/api-reference/payments/accounts/list-financial-accounts) fails with `403` PAYOUT_CURRENCY_NOT_ENABLED, and a quote or payout fails with `409` PAYOUT_NOT_ENABLED, or with `409` CAPABILITY_NOT_ACTIVE while the capability never activates. * The recipient's account needs the GBP-receiving capability, ACTIVE before you pay. [Capabilities](/v3/capabilities#the-capability-catalog) lists the id, and [Be paid in pounds sterling](/v3/capabilities#be-paid-in-pounds-sterling) lists the identity the recipient owes. * GBP has no sending capability. A `sender` on a quote or an INLINE payout fails with `422` SENDER_NOT_SUPPORTED. A FROM_QUOTE payout has no `sender` field, so sending one fails with `400` VALIDATION_BODY_FAILED. * Every `POST` needs an `Idempotency-Key` header. See [Idempotency](/v3/idempotency#payments-endpoints). ## Set up the account and payout address Before you can pay, three things must be ACTIVE: the account you're paying, its GBP-receiving capability, and the payout address for their bank account. [Account model](/v3/account-model#the-shared-state-machine) explains each status. You do this once. If the account and address already exist, skip to [pricing the payout](#price-and-create-the-payout). **1. Create the account** Create the account you're paying, with the GBP-receiving capability, and keep the returned `acc_` id. An organization owes its legal name and registered country; an individual owes their name and country of residence. The capability starts PENDING; wait for [`common.account.capability_activated`](/v3/webhooks/payments/accounts-webhooks/account-capability-activated). You don't need to wait to create the payout address, so do both at the same time. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/common/accounts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "capabilities": ["cap_CgLwtEvHBaWUixEMH8RK7"], "identity": { "identityType": "ORGANIZATION", "organization": { "legalName": "Harbourline Analytics Ltd", "registeredAddress": { "country": "GB" } } } }' ``` **2. Create the payout address** Create a `BANK_ACCOUNT` payout address for that `acc_`, with `routingFamily` set to GB_LOCAL, the `sortCode`, and the `accountNumber`. Send `accountHolderName` only if the bank account is in a different name from the account's. The address always carries one: OpenFX copies the account's legal name when you create it, freezes it, and every read returns it under `bankAccount.accountHolderName`. You can send both numbers as people usually write them. Spaces and hyphens are stripped, so the sort code `12-34-56` comes back as `123456`. A six- or seven-digit account number is zero-padded to eight digits, so `1234567` comes back as `01234567`. Any other length fails with `400` VALIDATION_BODY_FAILED, including the nine- and ten-digit numbers some banks issue, and `details.issues[]` names the field. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "payoutAddressType": "BANK_ACCOUNT", "accountId": "acc_E9SH9LAmymn9qyhYszweYn", "bankAccount": { "routingFamily": "GB_LOCAL", "sortCode": "12-34-56", "accountNumber": "1234567" } }' ``` The UK name check runs during the call, so the response already shows its result in `verifications[]`, with `mode` COP_GB. [Read the UK name check](#read-the-uk-name-check) explains each result. If it's NO_MATCH or BANK_ACCOUNT_NOT_FOUND, the address is already REJECTED. Otherwise it comes back PENDING while OpenFX finishes its own setup. Wait for [`payments.payout_address.activated`](/v3/webhooks/payments/addresses-webhooks/payout-address-activated) or [`payments.payout_address.rejected`](/v3/webhooks/payments/addresses-webhooks/payout-address-rejected), and continue only once the address is ACTIVE. [`payments.payout_address.verification_resolved`](/v3/webhooks/payments/addresses-webhooks/payout-address-verification-resolved) also fires whenever a check reaches a result, including one that changes `verifications[]` without moving the status. ## Read the UK name check The UK name check, Confirmation of Payee, compares the address's `accountHolderName` with the name the receiving bank holds for the sort code and account number. It never returns the bank's name, so `registeredName` is always null. | `result` | On the payout address | On a payout | | - | - | - | | MATCH | Payable | Reused. The payout doesn't check again | | CLOSE_MATCH | Payable | Checked again. You accept the new result when you confirm the payout | | UNAVAILABLE | Payable. The check got no answer, so it says nothing about the name, and `verifiedAt` is null | Checked again. You accept the new result when you confirm the payout | | NO_MATCH | REJECTED. Create a new address in the name the account is held in | Refused with `409` ACCOUNT_HOLDER_MISMATCH, and the address becomes REJECTED | | BANK_ACCOUNT_NOT_FOUND | REJECTED. No account exists at that sort code and account number, so the name was never compared. Create a new address with the corrected details | Refused with `409` PAYOUT_ADDRESS_BANK_ACCOUNT_NOT_FOUND, and the address becomes REJECTED | A REJECTED address can't back a payout: quoting one fails with `409` PAYOUT_ADDRESS_REJECTED. An address still PENDING is quotable. ## Price and create the payout **1. (Optional) List the financial accounts that can fund a GBP payout** Skip this if you already know the `finacc_` id. A GBP payout is funded from a GBP, USD, USDC, USDT, or EURC balance. A GBP balance pays without conversion, and the others are converted. Any other send currency fails with `422` QUOTE_SEND_CURRENCY_UNAVAILABLE. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl "https://api.openfx.com/v3/common/financial-accounts?receiveCurrency=GBP" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" ``` **2. Quote the payout** Get a price before you create the payout. A quote moves no money. It returns a `pytqte_` id and, when the send currency differs from GBP, a rate locked until `fxRates.expiresAt`. A quote funded from your GBP balance is like for like: it carries no `fxRates.expiresAt` and doesn't expire. Its `rail` is FPS. A single payout can receive at most £1,000,000. A larger `receiveAmount` is refused when you quote, with `422` AMOUNT_OUT_OF_RANGE, and `error.details` carries the bound. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payout-quotes \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "financialAccountId": "finacc_SnLywp9FK9cyGuGE2H5nUU", "receiver": { "payoutAddressId": "pytadd_KkvrkAMeCNypkGVz69bVLb" }, "sendAmount": "1000.00", "receiveCurrency": "GBP" }' ``` **3. Create the payout from the quote** Create the payout with `type: "FROM_QUOTE"` and the `pytqte_` id. The payout keeps the quote's rate and rail. [`type: "INLINE"`](/v3/api-reference/payments/payouts/create-payout) is supported for GBP too: it prices and creates the payout in one call, taking the same fields the quote does. Don't send a `purpose`: a GBP payout takes none, and sending one fails with `422` PURPOSE_INVALID. [Memos](#memos) covers `receiverMemo`. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payouts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "type": "FROM_QUOTE", "quoteId": "pytqte_Ez9FrrRTnELFSSWTDem5mT", "receiverMemo": "Invoice 4012" }' ``` Besides the QUOTE entry, `confirmations[]` holds an `AccountHolderNameConfirmation`, whose `type` is ACCOUNT_HOLDER_NAME, with `mode` COP_GB. If the address's latest check is a MATCH, the payout reuses it, so its `verifiedAt` is when the address was checked. Otherwise the check runs again and the entry shows the new result. A NO_MATCH or PENDING refuses the payout with `409` ACCOUNT_HOLDER_MISMATCH, as does any other blocking result the check can return. A BANK_ACCOUNT_NOT_FOUND refuses it with `409` PAYOUT_ADDRESS_BANK_ACCOUNT_NOT_FOUND, and the address becomes REJECTED. Either refusal records the payout FAILED with no `confirmations[]`, returns no `pyt_` id, and spends the quote: retrying that quote fails with `409` QUOTE_ALREADY_CONSUMED, so quote again. Confirming accepts a CLOSE_MATCH or an UNAVAILABLE. Cancel to decline it. **4. Confirm the payout** [Confirm the payout](/v3/api-reference/payments/payouts/confirm-payout) to accept everything in `confirmations[]` and move it to ACCEPTED. [Payouts](/v3/payouts) covers confirming and cancelling in more detail. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payouts/pyt_Y6ZrY1JJvFqzaP3VsNojWN/confirm \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" ``` ## Memos On FPS, a `receiverMemo` is 1 to 18 ASCII letters, digits, and spaces, the length of the Faster Payments reference. A memo of spaces alone is accepted. An empty string, a memo that is too long, and one that holds any other character each fail with `400` RECEIVER_MEMO_INVALID; an empty string is refused rather than replaced by the default. OpenFX never truncates it. If you leave `receiverMemo` out, the payout uses the last 18 characters of its `id`. The payout `pyt_Y6ZrY1JJvFqzaP3VsNojWN`, for example, carries the memo `Y1JJvFqzaP3VsNojWN`. ## Track settlement After ACCEPTED, the payout settles in the background. See [Payouts](/v3/payouts#send-the-payout) for each status and webhook. On an FPS payout, `settlementTraceId.status` reads UNSUPPORTED. [Trace a payout with the receiving bank](/v3/payouts#trace-a-payout-with-the-receiving-bank) lists the key for every rail. ## Testing in sandbox In Sandbox, a GBP payout settles through a simulated provider, and you choose each outcome with a word in a name. **Choose the name check result.** Put one of these words in the payout address's `accountHolderName`, or in the account's name if you don't send one. The check strips every character that isn't a letter and compares what's left, ignoring case, so "Bruno Match Ltd" is a NO_MATCH and "Invalid Partners" is a BANK_ACCOUNT_NOT_FOUND. | Word in the name | `result` | | - | - | | None of the words below | MATCH | | "NOMATCH" | NO_MATCH | | "CLOSEMATCH" | CLOSE_MATCH | | "UNAVAILABLE" | UNAVAILABLE | | "INVALID" | BANK_ACCOUNT_NOT_FOUND | When a name holds more than one word, the first in this order wins: "NOMATCH", then "CLOSEMATCH", then "UNAVAILABLE", then "INVALID". Every check also takes 1 to 5 seconds, and the create call waits for it. Add "SLOW" to make it take about 10 seconds longer, for example "CLOSEMATCH SLOW Ltd"; unlike the other words, "SLOW" is case-sensitive and must be uppercase. The result is the same each time the check runs, so a payout to the address gets the same result as its setup. **Reject the capability.** An account whose name contains "REJECTED" has its GBP-receiving capability rejected instead of activated. Otherwise the capability activates within a few seconds. **Settle a payout.** A confirmed payout moves to PROCESSING once it's debited, then to PROCESSED 10 to 60 seconds later. ## Common mistakes * **Sending a nine- or ten-digit account number.** Only six- to eight-digit account numbers are accepted, and OpenFX doesn't shorten longer ones. * **Naming a `sender` or sending a `purpose`.** A GBP payout takes neither. Remove them from the quote and from an INLINE payout; a FROM_QUOTE payout has no `sender` field, so one there is a `400` VALIDATION_BODY_FAILED rather than a `422`. * **Sending a memo longer than 18 characters.** It fails instead of being truncated. Shorten it, or leave it out to get the default. * **Expecting `registeredName`.** The UK name check never returns the bank's name, so it's always null. A NO_MATCH address can't be fixed, only replaced. * **Changing the name after BANK_ACCOUNT_NOT_FOUND.** The sort code and account number reach no account, so check the numbers with the account holder, not the name. * **Confirming without reading `confirmations[]`.** A CLOSE_MATCH or UNAVAILABLE doesn't block confirmation. The decision is yours. ## What's next > [card] [Payouts](/v3/payouts) > > The general payout flow. > [card] [Capabilities](/v3/capabilities#be-paid-in-pounds-sterling) > > What the GBP-receiving capability requires. > [card] [Payouts in EUR](/v3/eur-payout-integration) > > Paying euro accounts over SEPA or SWIFT. > [card] [Payment Webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Every payout and address event. # Glossary Source: https://docs.openfx.com/v3/glossary Definitions for the vocabulary: resources, headers, status enums, and concepts used across the spec. A single-page reference for v3 vocabulary. Terms are alphabetical; each links out to the page that uses it in context. ## A **Account** The identity of a person or organization you move money to or on behalf of, plus its payout capabilities. An `Account` holds no money; a `FinancialAccount` holds the funds. See [Account model](/v3/account-model). **Atomic execution** A trade either succeeds at the quoted rate or fails; there is no partial fill. See [Trades](/v3/trades#state-machine). ## B **Balance** The per-currency record returned by [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances). One row per currency, carrying `withdrawableBalance` and `totalBalance`. The response also carries an `aggregate` block with the org's net equity across all currencies, converted to USD. **Bearer token** The JWT passed in `Authorization: Bearer `. ES256-signed, 60s TTL, single-use. Every request also carries a body-bound `X-Request-Signature` header. See [Authentication](/v3/authentication). ## C **Capability** Permission for an account to receive payouts in a currency or act as a payout's sender. Each `AccountCapability` has an opaque id, read-only coverage details, and its own status. See [Capabilities](/v3/capabilities). **Cursor pagination** v3's pagination model: `startingAfter` / `endingBefore` with stable IDs. No `page` / `offset` integers. See [Pagination](/v3/pagination). **Cut-off** The latest time OpenFX submits a fiat withdrawal to a rail on the same banking day. Submissions after the cut-off roll to the next banking day. Tables in [Settlement times](/v3/settlement-times). ## D **Deposit** Incoming funds (fiat wire or on-chain stablecoin transfer) observed by OpenFX and (once cleared) credited to your balance. Read via [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits). See [Deposits](/v3/deposits). ## E **ES256** The ECDSA signature algorithm OpenFX uses to sign JWTs (and validate yours). Asymmetric: your private key signs, OpenFX validates with the public key on file. See [Authentication](/v3/authentication). **`expiresAt`** On a `Quote`, the wall-clock at which the quoted rate is no longer executable. Default 3 seconds from creation; configurable via `quoteForSeconds` (standard durations: 3, 15, 30, 45, 60). Holds longer than 15 seconds are priced higher to account for market volatility. See [Quotes → Quote lifecycle](/v3/quotes#quote-lifecycle). **Exposure limit** The amount of unsettled trades your organization can have open at one time. You can execute trades up to this limit and settle them before you withdraw. Read via [`GET /v3/fx/exposures`](/v3/api-reference/exposure/get-exposure-summary). See [Exposure](/v3/exposure). ## F **Financial account** A balance your organization holds with OpenFX that can fund a payout. The payout debits `financialAccountId`; the recipient is identified separately through `receiver.payoutAddressId`. See [Account model](/v3/account-model#the-four-resources). ## I **Idempotency-Key** Client-generated UUID (or any unique string) passed on state-changing requests. A retry with the same key returns the cached result instead of executing the operation twice. **Required** on every write; returns `428` IDEMPOTENCY_KEY_MISSING per RFC 6585 when omitted. See [Idempotency](/v3/idempotency). **Idempotency-Replayed** Response header emitted on every response from idempotent endpoints (`POST /quotes`, `POST /trades`, `POST /withdrawals`). `true` on a cache hit (the body is replayed from a prior request with the same key); `false` on a fresh execution. Always present on these three endpoints; omitted on GETs. See [Idempotency → How to tell a replay from a fresh execution](/v3/idempotency#how-to-tell-a-replay-from-a-fresh-execution). ## J **JWT (JSON Web Token)** The bearer token format v3 uses for authentication. ES256-signed, 60s TTL, single-use (server-enforced nonce uniqueness). Mint a fresh one per request and pair it with a freshly computed `X-Request-Signature` header. See [Authentication](/v3/authentication). ## N **Naming conventions** Three layers, three rules. JSON field keys are `camelCase` (`withdrawalAccountId`, `buyAmount`, `createdAt`). URL path segments are `kebab-case` (`/v3/fx/withdrawal-accounts`, `/v3/fx/pairs`). Type / schema / resource names are `PascalCase` in prose and OpenAPI components (`WithdrawalAccount`, `Trade`, `Quote`). HTTP headers keep their HTTP-spec form (`X-Trace-Id`, `Idempotency-Key`). Same split used by Stripe, Plaid, Twilio. **`network`** On a `Deposit` or `Withdrawal`, the settlement network or rail (e.g. ETHEREUM for a stablecoin movement, FIAT for a bank-rail movement). See [Supported networks](/v3/supported-networks) for the stablecoin chain matrix. ## P **Pair** A tradable `(buyCurrency, sellCurrency)` combination with `minTradeAmount` and `maxTradeAmount` (denominated in `sellCurrency`). Listed via [`GET /v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs). See [Currencies](/v3/currencies) for the platform-wide set. **Payout** Money sent from one of your financial accounts to a recipient's payout address. A payout starts in REQUIRES_CONFIRMATION without moving funds; you confirm it to accept the priced payout. Unlike a first-party withdrawal, a payout can pay someone else's bank account. See [Payouts](/v3/payouts). **Payout address** A recipient's registered bank destination, represented by `PayoutAddress` and owned by an `Account`. It is separate from a verified withdrawal account. To correct an address, create a replacement and archive the old one. See [Account model → Payout addresses](/v3/account-model#payout-addresses). **Payout quote** An immutable, time-bounded price snapshot that moves no funds. Pass its id as `quoteId` to create a payout from that price, or create an inline-priced payout without a separate quote. See [Payouts](/v3/payouts). **Status enums** Different resources expose different status values. | Resource | Values | | - | - | | Trade | PENDING, LOCKED, READY_TO_SETTLE, EXECUTED, REVERSED | | Deposit | PENDING, COMPLETED, REJECTED, ERROR | | Withdrawal | PENDING, COMPLETED, CANCELLED | | WithdrawalAccount | PENDING, ACTIVE, ARCHIVED, REJECTED, DEACTIVATED, ADDITIONAL_ACTION_NEEDED | | Quote | ACTIVE, EXPIRED, CONSUMED | | Account, AccountCapability, PayoutAddress | PENDING, ACTIVE, REJECTED, REQUIRES_INFORMATION | | Payout | REQUIRES_CONFIRMATION, ACCEPTED, PROCESSING, IN_REVIEW, PROCESSED, RETURNED, FAILED, CANCELLED, EXPIRED | For payouts, PROCESSED is not terminal: funds can still be returned. The terminal states are RETURNED, FAILED, CANCELLED, and EXPIRED. See [Payouts](/v3/payouts) and [Account model](/v3/account-model#the-shared-state-machine). Trades terminate at EXECUTED or REVERSED; LOCKED and READY_TO_SETTLE are transitional states: LOCKED on a future-dated (T1/T2) trade, READY_TO_SETTLE on a manually settled trade. Deposits terminate at COMPLETED, REJECTED, or ERROR. Withdrawals terminate at COMPLETED or CANCELLED. All documented values are **UPPERCASE**, consistent with currency codes (USD, EUR), network identifiers (ETHEREUM, SOLANA), and error codes (TRADE_NOT_FOUND) elsewhere in v3. See [Trades](/v3/trades#state-machine), [Deposits](/v3/deposits), and [Withdrawals](/v3/withdrawals). ## Q **Quote** A binding rate returned by [`POST /v3/fx/quotes`](/v3/api-reference/trade/create-quote). Single-execution: pass the `id` to `POST /v3/fx/trades` before `expiresAt`. Retrievable by ID for 2 days from `createdAt`; see [Quotes → Retrieving a quote](/v3/quotes#retrieving-a-quote). ## R **Rail** The fiat settlement system a withdrawal or payout travels through (e.g. Fedwire, SWIFT, SEPA, SPEI, FPS, PIX, NPP, UAEFTS). For withdrawals, it is bound to the verified withdrawal account and reported as `WithdrawalAccount.rail`. For payouts, the platform selects the rail and reports it on the quote and payout. CHAPS is a withdrawal settlement route that OpenFX chooses; it is not a `WithdrawalAccount.rail` value. See [Settlement times](/v3/settlement-times) and [Payouts](/v3/payouts#supported-payout-currencies). **Receiver** The account being paid, identified on a payout through `receiver.payoutAddressId`. The address belongs to that account, so you do not name its account id separately. See [Account model → Roles on a payout](/v3/account-model#roles-on-a-payout). **`reference_amount` / `reference_currency`** *(v2, removed in v3)* v2 quote-create indirection: client passed an amount plus the currency it was denominated in. **Removed in v3**; the v3 quote request supplies exactly one of `buyAmount` or `sellAmount` directly. **Routing family** The `routingFamily` on a payout address determines which bank details it needs, such as an IBAN for SEPA or a CLABE for Mexico. It is not the same as the settlement rail selected for a payout. See [Account model → Payout addresses](/v3/account-model#payout-addresses). ## S **Sandbox** The OpenFX test environment. Same base URL (`api.openfx.com`) as Live; each API key is bound to one environment, and Sandbox keys carry a `sandbox_` prefix. `X-App-Mode` must match the key's environment and defaults to SANDBOX when omitted. See [Environments](/v3/environments). **Sender** An account on whose behalf you make a payout, distinct from the recipient. Funds still come from your financial account. See [Account model → Roles on a payout](/v3/account-model#roles-on-a-payout). **Stablecoin** Fiat-pegged crypto assets supported on v3: USDC, USDT, EURC. Each is tradable, depositable, and withdrawable on one or more chains. See [Currencies → Stablecoins](/v3/currencies#stablecoins). ## T **Timestamps** All v3 timestamps are ISO 8601 UTC with millisecond precision: `YYYY-MM-DDTHH:mm:ss.sssZ` (e.g. `2026-04-28T10:00:00.000Z`). The trailing `Z` is required. Always parse as UTC; convert to a local zone only at display time. **`totalBalance`** Total funds held in a currency on a `Balance` row, including any amount earmarked against pending operations. Ordinarily `withdrawableBalance` ≤ `totalBalance`, but `totalBalance` can itself go negative if the org owes a settlement in that currency; in that case `withdrawableBalance` is `0`. The held portion is the difference `totalBalance − withdrawableBalance` (when `totalBalance` is non-negative) and is not broken out as a separate field in v3. See [Amounts → Balance lifecycle](/v3/amounts#balance-lifecycle-available-vs-total). **Trade** The execution of a quote. Status progresses through PENDING, LOCKED (future-dated only), and READY_TO_SETTLE (manual settlement only) to a terminal EXECUTED, or to REVERSED if unwound before settlement. See [Trades](/v3/trades#state-machine). **Trade Settlement** The v3 surface that covers balances, deposits, withdrawals, and verified withdrawal accounts. Sits under `/v3/fx/`. See [Settlement models](/v3/settlement-models). **`transactionHash`** The on-chain transaction hash of a stablecoin deposit or withdrawal. Null until the transaction is broadcast, and always null on fiat movements. ## W **Webhook** A signed HTTP POST OpenFX sends to your endpoint when an event occurs. The envelope carries `type` (the resource noun, e.g. `"withdrawals"`), `eventType` (the product-prefixed event name, e.g. `"fx.withdrawal.completed"`), `id`, `createdAt`, and a single `data` object: close to, but not identical to, the resource's v3 REST shape (`data.status: "COMPLETED"`, camelCase keys, string amounts), not an array. HMAC-SHA256 signed via the `X-OpenFX-Signature` header. See [Webhook authentication](/v3/webhooks/authentication) and [Webhooks setup](/v3/webhooks/setup). **Verified withdrawal account** A pre-configured bank account or on-chain address that withdrawals can settle to. Created via the dashboard; referenced by `withdrawalAccountId` on withdrawals. The rail or chain is bound to the withdrawal account at creation. See [Verified accounts](/v3/verified-accounts). **Withdrawal** An outgoing transfer initiated via [`POST /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/create-withdrawal). Same endpoint covers fiat and stablecoin; the rail is resolved server-side from the referenced withdrawal account. See [Withdrawals](/v3/withdrawals). **`withdrawalAccountId`** The ID (`wac_` prefix; a bare UUID is also accepted on input) of the verified withdrawal account a withdrawal settles to: either a fiat bank account or a stablecoin wallet. Created in the [OpenFX dashboard](https://app.openfx.com), read via [`GET /v3/fx/withdrawal-accounts`](/v3/api-reference/trade-settlement/list-withdrawal-accounts), and supplied on `POST /v3/fx/withdrawals`. Carries the rail/chain, so the request body never names a network. Renamed from the v2 request field `withdrawalAddressId`. See [Verified accounts](/v3/verified-accounts). **`withdrawableBalance`** Funds usable right now for trades or withdrawals: on a `Balance` row (per currency) or on the response's `aggregate` block (org-wide net equity in USD). Never negative; `0` when the corresponding `totalBalance` (or the org's overall net position) is negative. Renamed from `availableBalance`. See [Amounts → Prefix vocabulary](/v3/amounts#prefix-vocabulary). ## X **`X-Trace-Id`** Response header carrying a per-request trace ID. Include it in support requests; capture it on the success path too. See [Metadata and tracing](/v3/metadata-and-tracing). ## What's next > [card] [Payouts](/v3/payouts) > > Recipient setup, payout pricing, confirmation, and settlement. > [card] [Currencies](/v3/currencies) > > Fiat + stablecoin platform tables. > [card] [Supported networks](/v3/supported-networks) > > Per-stablecoin chain matrix. > [card] [Settlement times](/v3/settlement-times) > > Fiat-rail cut-off tables. > [card] [Errors](/v3/errors) > > Stable error codes and the retry triage matrix. # Idempotency Source: https://docs.openfx.com/v3/idempotency Idempotency-Key headers make retries safe: required on every write, TTLs from 30 minutes to 7 days, explicit responses for in-flight/mismatch, and the crash-recovery pattern to keep it safe across restarts. All state-changing requests (POST) **require** an `Idempotency-Key` header. The value is a client-generated unique string that tags one logical operation. For FX requests, if a request times out or your service crashes before it receives a response, reuse the **same** key within the idempotency window. If OpenFX has already stored a response, you get that response again, including any stored failure. For a trade or withdrawal that returns an execution or initiation failure, [check the resource before placing a new request](/v3/errors#retrying-trade-execution-failed). The TTLs, scoping rules, and recovery guidance below describe the FX endpoints. The [Payments endpoints](#payments-endpoints) follow the Payments API rules. Sending a request without it returns **`428` IDEMPOTENCY_KEY_MISSING**. 428 (RFC 6585 Precondition Required) is the precise status for this: the header is a precondition, not a schema field. > [!NOTE] > > **Related concepts** - [Resource IDs](/v3/resource-ids): server-generated > permanent IDs vs client-generated short-lived idempotency keys - > [Quickstart](/v3/quickstart): worked example of quote then trade with two > distinct keys - [Errors](/v3/errors): `IDEMPOTENCY_*` error codes and recovery > patterns ## Endpoints | Endpoint | TTL | | - | - | | [`POST /v3/fx/quotes`](/v3/api-reference/trade/create-quote) | 30 minutes | | [`POST /v3/fx/trades`](/v3/api-reference/trade/execute-trade) | 24 hours | | [`POST /v3/fx/trades/{id}/settle`](/v3/api-reference/trade/settle-trade) | 24 hours | | [`POST /v3/fx/trades/{id}/reverse-quote`](/v3/api-reference/trade/generate-reverse-quote) | 30 minutes | | [`POST /v3/fx/trades/{id}/reverse`](/v3/api-reference/trade/reverse-trade) | 24 hours | | [`POST /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/create-withdrawal) | 7 days | > [!NOTE] > > **TTLs are sized by the retry window each operation needs.** Quote and > reverse-quote duplicates are cheap (re-quote at the worst), so 30 minutes is > plenty. Trade, settle, and reverse duplicates can move thousands of dollars; > 24 hours covers most retry patterns without long-tail key sprawl. Withdrawal rails are long-running by nature (multi-day > SWIFT, weekend ACH cutoffs, end-of-month batch reconciliation), so the window > is wider at 7 days. FX keys are scoped per organization + API key + endpoint. You can safely reuse the same UUID across `/v3/fx/quotes` and `/v3/fx/trades` without conflict, but doing so generally adds confusion rather than convenience. **Generate one key per logical operation** and let the scoping take care of itself. ## Payments endpoints Every `POST` in the Payments API (`/v3/common/accounts` and `/v3/payments/...`) also requires `Idempotency-Key`. The Payments API owns its idempotency behavior; the FX TTLs above do not apply, and this guide does not specify a Payments key lifetime. Per the Payments API: * "A key is scoped to the API key, the endpoint, and the organization together, and it is case-sensitive." * "Replaying the identical request returns the stored outcome. Reusing the key with a different request body returns `422` IDEMPOTENCY_MISMATCH. Reusing it while the first request is still executing returns `409` IDEMPOTENCY_IN_FLIGHT." The key format and error codes on this page apply to both APIs. The Payments API owns whether it returns `Idempotency-Replayed`. ## Idempotency-key format ```http theme={"theme":{"light":"poimandres","dark":"poimandres"}} Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000 ``` | Constraint | | | - | - | | Pattern | `^[a-zA-Z0-9_-]{1,255}$` | | Recommended | UUID | | Avoid | sequential IDs, raw timestamps, anything containing PII | ## How it works For FX endpoints, the server stores `{key → response}` for the TTL. Subsequent requests with the same key: | Scenario | Behavior | | - | - | | Same key, **same body** | Returns the cached response, including any stored failure, with the original status code | | Same key, **different body** | Returns `422` IDEMPOTENCY_MISMATCH | | Same key, **original still PROCESSING** | Returns `409` IDEMPOTENCY_IN_FLIGHT; back off and retry with the same key | | Same key, **TTL expired** | Treated as a brand-new request | ## Safe retry pattern ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} import { randomUUID } from "node:crypto"; // `signRequest({ method, url, body })` returns { headers, body } with a freshly minted JWT // AND a freshly computed X-Request-Signature each call. See the Authentication guide. // See Rate limiting → Handling rate limits pattern (the canonical reference): // https://docs.openfx.com/v3/rate-limiting#handling-rate-limits-pattern // // Two distinct lifetimes inside this function: // - Idempotency-Key: minted ONCE per logical operation; reused on every retry of that operation. // - JWT + signature: minted ONCE per HTTP attempt; never reused. JWT TTL is 60s and the X-Request-Signature is bound to the JWT's nonce, so both rotate together. async function executeTradeWithRetry(quoteId, signRequest, maxAttempts = 3) { const idempotencyKey = randomUUID(); const url = "https://api.openfx.com/v3/fx/trades"; const body = JSON.stringify({ quoteId: quoteId }); for (let attempt = 1; attempt <= maxAttempts; attempt++) { const signed = signRequest({ method: "POST", url, body }); const res = await fetch(url, { method: "POST", headers: { ...signed.headers, "Idempotency-Key": idempotencyKey, // stable across attempts }, body: signed.body, }); if (res.ok) return res.json(); const { error } = await res.json(); // 409: the original is still PROCESSING. Wait and retry the same key. // Retry-After is seconds to wait, not an epoch timestamp. if (error.code === "IDEMPOTENCY_IN_FLIGHT") { const retryAfterHeader = res.headers.get("retry-after"); const retryAfter = retryAfterHeader === null ? NaN : Number(retryAfterHeader); const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 5000; await new Promise((r) => setTimeout(r, waitMs)); continue; } throw error; // Anything else is terminal for this attempt loop } // Every attempt was IDEMPOTENCY_IN_FLIGHT. // Surface that to the caller instead of returning undefined. throw new Error("Retry budget exhausted"); } ``` ## How to generate keys **Do**: * Generate the key **once per logical operation**, not once per HTTP request * Use unique identifier * Store the key alongside the operation in your DB if you need to reconcile after a crash **Don't**: * Generate a new key on retry (defeats the entire mechanism) * Reuse the same key for unrelated operations (trade A vs trade B) * Use predictable values (timestamps, counters) * Embed user IDs, emails, or other PII ## Crash recovery The safe retry pattern above covers retries **within one process**. If your service crashes mid-call, the request may have reached OpenFX even though your client never got a response. Surviving that needs one more piece: persist the key before you send it, and a worker that replays PENDING rows on restart. > [!WARNING] > > **Persist the idempotency key to your DB before sending the request, not > after.** A new key on a restart-retry is effectively a brand-new operation, > and the server will execute it again. With withdrawals, that means money out > the door twice. **1. Generate key, save it to DB** Mark the row `status: PENDING`. This must commit before the API call goes out. **2. Send the request** Standard call with the saved key in the `Idempotency-Key` header. **3. On success, mark the row complete** Store the response (the trade or withdrawal `id`, the executed amount, etc.). **4. On crash or timeout, leave the row PENDING** A recovery worker scans for PENDING rows and re-fires the request with the same key. The server returns the cached response if the original landed, or executes it for the first time if it didn't. ```python theme={"theme":{"light":"poimandres","dark":"poimandres"}} import json import uuid import requests # `sign_request(method, url, body)` returns (headers, body_bytes) with a freshly minted JWT # AND a freshly computed X-Request-Signature each call. See Authentication. # `db` is your app's persistence layer def execute_trade(quoteId, db, sign_request): # Save key FIRST, in case we crash before the API call returns idempotency_key = str(uuid.uuid4()) db.save_pending_trade(quoteId=quoteId, idempotency_key=idempotency_key) url = 'https://api.openfx.com/v3/fx/trades' # Serialize once: the same bytes are signed and sent. body = json.dumps({'quoteId': quoteId}).encode('utf-8') headers, body_bytes = sign_request('POST', url, body) try: resp = requests.post( url, headers={**headers, 'Idempotency-Key': idempotency_key}, data=body_bytes, timeout=30, ) resp.raise_for_status() db.mark_completed(idempotency_key, resp.json()) return resp.json() except requests.RequestException: # On restart, recovery loop will retry with the saved idempotency_key raise ``` ### A persistence schema you can copy A minimal table that supports the crash-recovery flow. Postgres-flavored; portable to any RDBMS. ```sql theme={"theme":{"light":"poimandres","dark":"poimandres"}} CREATE TABLE idempotent_writes ( key TEXT PRIMARY KEY, -- the Idempotency-Key sent to OpenFX endpoint TEXT NOT NULL, -- e.g. "POST /v3/fx/trades" request_body JSONB NOT NULL, -- exact body for replay status TEXT NOT NULL, -- "PENDING" | "SUCCEEDED" | "FAILED" resource_id TEXT, -- populated on success (readable, typed-prefix ID, e.g. tde_5W7guYdHT24JFnRQrZN9y8) response_body JSONB, -- cached for audit http_status INTEGER, -- 2xx / 4xx / 5xx received created_at TIMESTAMPTZ NOT NULL DEFAULT now(), completed_at TIMESTAMPTZ ); -- Partial index keeps the recovery sweep O(PENDING rows) regardless of history. CREATE INDEX idx_idem_pending ON idempotent_writes (created_at) WHERE status = 'PENDING'; ``` > [!NOTE] > > **Concurrency:** the recovery worker and the original request can both try to > update the same row. Use either `SELECT … FOR UPDATE SKIP LOCKED` when reading > PENDING rows, or a `WHERE status = 'PENDING'` predicate on the `UPDATE` (so a > winning writer's update fails as zero rows affected on the loser's path). If > you run more than one recovery worker, hold an advisory lock around the sweep > (`pg_try_advisory_lock(hashtext('idem-recovery'))`), or run the worker as a > leader-elected singleton. Retention rule: keep rows for at least **2× the server TTL** of the endpoint they target so audits can reconcile after a long incident. Past the server's window, replays no longer match a cached response and will execute a new operation. Guard against that in your worker. ### The recovery worker Runs on every service startup and periodically (e.g. every 60s). For each PENDING row, replays with the **same** `Idempotency-Key`. The server returns the cached response if the original landed, or executes once if it didn't. ```ts theme={"theme":{"light":"poimandres","dark":"poimandres"}} // `signRequest({ method, url, body })` returns { headers, body } with a freshly minted JWT // AND a freshly computed X-Request-Signature each call. See Authentication. async function recoverPendingWrites(signRequest) { const stale = await db.idempotent_writes.findAll({ where: { status: "PENDING", created_at: { lt: minutesAgo(2) } }, }); for (const row of stale) { const [method, path] = row.endpoint.split(" "); // Server TTLs: quotes and reverse-quotes 30min; trades, settle, and reverse 24h; withdrawals 7 days. // If we're past the window, alert and skip: replaying would create a NEW op. if (isPastTtl(path, row.created_at)) { await alert(`stale idempotent row past TTL: ${row.key}`); continue; } // isPastTtl: returns true when (now - createdAt) >= the endpoint's server TTL minus a safety margin. // function isPastTtl(path: string, createdAt: Date): boolean { // const ttlMs = // path.endsWith('/quotes') || path.endsWith('/reverse-quote') ? 25 * 60 * 1000 // 25min (server 30min) // : path.endsWith('/trades') || path.endsWith('/settle') || path.endsWith('/reverse') // ? 20 * 60 * 60 * 1000 // 20h (server 24h) // : path.endsWith('/withdrawals') ? 6 * 24 * 60 * 60 * 1000 // 6d (server 7d) // : 24 * 60 * 60 * 1000; // return Date.now() - createdAt.getTime() >= ttlMs; // } const url = `https://api.openfx.com${path}`; const requestBody = JSON.stringify(row.request_body); // Re-sign on every replay: the JWT nonce is single-use and the signature is bound to it. const signed = signRequest({ method, url, body: requestBody }); const res = await fetch(url, { method, headers: { ...signed.headers, "Idempotency-Key": row.key, // ← critical: same key }, body: signed.body, }); const body = await res.json(); await db.idempotent_writes.update(row.key, { status: res.ok ? "SUCCEEDED" : "FAILED", resource_id: res.ok ? body.data.id : null, response_body: body, http_status: res.status, completed_at: new Date(), }); } } ``` ### TTL alignment Match your client-side retention to the server's TTL so your worker doesn't replay keys the server has forgotten: | Endpoint | Server TTL | Worker should give up after | | - | - | - | | `POST /v3/fx/quotes` | 30 min | \~25 min | | `POST /v3/fx/trades` | 24 h | \~20 h | | `POST /v3/fx/trades/{id}/settle` | 24 h | \~20 h | | `POST /v3/fx/trades/{id}/reverse-quote` | 30 min | \~25 min | | `POST /v3/fx/trades/{id}/reverse` | 24 h | \~20 h | | `POST /v3/fx/withdrawals` | 7 days | \~6 days | If a row is past the worker cutoff and still PENDING, page a human: it's a real reconciliation question, not a retry. ## How to tell a replay from a fresh execution For FX responses, `Idempotency-Replayed` is present only when the response passes through idempotency handling: * `Idempotency-Replayed: true` indicates the response came from the idempotency cache. The original execution happened on a prior request with the same key. * `Idempotency-Replayed: false` indicates the response is a fresh execution. The server processed the operation just now. The header is absent on `401`, `403`, and `429` responses; gateway `400` and `413` responses; request-validation `400` responses; and idempotency errors. It is also absent on GET/list endpoints. ```http theme={"theme":{"light":"poimandres","dark":"poimandres"}} HTTP/1.1 200 OK Idempotency-Replayed: true X-Trace-Id: 4bf92f3577b34da6a3ce929d0e0e4736 Content-Type: application/json { ... cached response body ... } ``` ### What's cached and what's fresh on a replay * **Body and HTTP status code:** byte-identical to the original. v3 returns the **stored bytes verbatim**: the cache doesn't re-serialize through the current schema. If a minor version bump later adds an additive field, replays of pre-bump records will not include the new field (only fresh executions do). * **Observability headers** (`X-Trace-Id`, `X-Request-Timestamp`, `RateLimit-*`): **regenerated per attempt**. `X-Trace-Id` always identifies the *current* request hop (so debugger logs land on the right span); `X-Request-Timestamp` reflects when the replay was served; rate-limit headers reflect *current* budget. * **`Idempotency-Replayed`:** set per the rule above. This means reconciliation tooling that hashes the response body across retries gets stable hashes within the TTL, useful for audit trails and replay-safe ETL. On `settle`, `reverse`, and `reverse-quote`, reusing a key for a different trade ID returns `422` IDEMPOTENCY_MISMATCH. ## Sandbox vs live keys never collide Idempotency keys are isolated by environment. A key used in Sandbox cannot replay against Live, and vice versa. You can use the same UUID in Sandbox testing and a Live integration without cross-environment replay. ## Putting it together: the withdrawal flow Withdrawals have the highest cost-of-mistake, so they're the canonical example of the full pattern (persisted key, crash-safe send, poll to terminal): **1. Discover verified withdrawal accounts** Call [`GET /v3/fx/withdrawal-accounts`](/v3/api-reference/trade-settlement/list-withdrawal-accounts) to find your `withdrawalAccountId` values. The account `type` (fiat vs stablecoin) is inferred from this record; there's one withdrawal endpoint. **2. Save key, then POST** Persist `{ idempotency_key, withdrawalAccountId, amount, status: 'PENDING' }` to your DB, using the same schema as [above](#a-persistence-schema-you-can-copy). Then call [`POST /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/create-withdrawal) with that key. **3. Poll until terminal** Poll [`GET /v3/fx/withdrawals/{id}`](/v3/api-reference/trade-settlement/get-withdrawal) until `status` reaches COMPLETED (see the [withdrawals](/v3/withdrawals)). For stablecoin withdrawals, `transactionHash` is populated once the transaction broadcasts. ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} import { randomUUID } from "node:crypto"; // `signRequest({ method, url, body })` returns { headers, body } with a freshly minted JWT // AND a freshly computed X-Request-Signature per call. `db` is your persistence layer. // JWT TTL is 60s; this flow can run for minutes (poll loop) so the JWT + signature are minted // per HTTP attempt, never captured once. See Rate limiting → Handling rate limits pattern: // https://docs.openfx.com/v3/rate-limiting#handling-rate-limits-pattern async function withdraw({ withdrawalAccountId, amount, currency, signRequest, }) { // 1. Save key first (same crash-safety reasoning as the recovery pattern above). const idempotencyKey = randomUUID(); await db.savePendingWithdrawal({ idempotencyKey, withdrawalAccountId, amount, currency, }); // 2. Create. Verify the POST succeeded before polling, otherwise // withdrawal.id is undefined and the loop below silently misbehaves. const createUrl = "https://api.openfx.com/v3/fx/withdrawals"; const createBodyBytes = JSON.stringify({ withdrawalAccountId: withdrawalAccountId, withdrawalAmount: amount, currency, }); const createSigned = signRequest({ method: "POST", url: createUrl, body: createBodyBytes, }); const createRes = await fetch(createUrl, { method: "POST", headers: { ...createSigned.headers, "Idempotency-Key": idempotencyKey }, body: createSigned.body, }); const createBody = await createRes.json(); if (!createRes.ok) { // Leave the row in `PENDING` so the recovery worker can retry with the same key. const err = createBody.error; throw new Error( `API error: ${err.code} — ${err.message} (trace ${createRes.headers.get("x-trace-id")})`, ); } // Both POST and GET wrap the resource in { data: ... }; unwrap it. let withdrawal = createBody.data; await db.markCreated(idempotencyKey, withdrawal.id); // 3. Poll until terminal. Mint per tick: even a 5s cadence exceeds the 60s JWT TTL // by the 13th iteration, and most withdrawals settle well after that. while (withdrawal.status === "PENDING") { await new Promise((r) => setTimeout(r, 5000)); const pollUrl = `https://api.openfx.com/v3/fx/withdrawals/${withdrawal.id}`; const pollSigned = signRequest({ method: "GET", url: pollUrl }); const pollBody = await fetch(pollUrl, { headers: pollSigned.headers }).then( (r) => r.json(), ); withdrawal = pollBody.data; } return withdrawal; // terminal: COMPLETED | CANCELLED } ``` > [!TIP] > > In production, prefer **webhooks** over polling for terminal status. Polling > burns rate-limit budget and adds latency. See [Webhook > authentication](/v3/webhooks/authentication) to wire up event delivery. ## Common mistakes * **Generating a new key on every HTTP retry.** Defeats the entire mechanism. Generate the key once per logical operation, reuse it on every retry of that operation. * **Generating a new key after a restart.** Same problem. The server treats it as a new operation. Persist the key to disk before sending the request. * **Reusing the same key for two genuinely different operations.** Returns `422` IDEMPOTENCY_MISMATCH. One key per logical action. * **Treating IDEMPOTENCY_KEY_MISSING as a server bug.** It's a client bug. The header is required on every write; missing it returns 428. * **Embedding PII in the key.** The key is logged. Use UUID v4 or another opaque random string. Never email, user ID, or any identifier that lets an observer infer the action. * **Using the same key across `/quotes` and `/trades`.** Technically safe (keys are scoped per endpoint), but conceptually muddled. The quote and the trade are two operations. Two keys, one per operation. ## What's next > [card] [Errors](/v3/errors#idempotency) > > Full code catalog and status mapping for idempotency errors. > [card] [Rate limiting](/v3/rate-limiting#handling-rate-limits-pattern) > > The broader retry-with-backoff strategy. > [card] [Live checklist](/v3/live-checklist) > > Crash-recovery and key-persistence checks for go-live. > [card] [Withdrawals](/v3/withdrawals) > > Per-state recovery across the 7-day idempotency window. # Introduction Source: https://docs.openfx.com/v3/introduction OpenFX gives financial institutions programmatic access to FX and stablecoin liquidity, plus payouts to bank accounts, with a consistent `{ data }` response envelope, stable error codes, and cursor pagination. Hey builder, let’s move money. Start here. Skip the rabbit holes. Go from creating keys\ to your first200 Read our Quickstart guide → [Open](/v3/quickstart) Introduce us to your agentIt reads the docs. You review the code. [ChatGPT](https://chatgpt.com/?q=Read%20the%20OpenFX%20API%20docs%20at%20https%3A%2F%2Fdocs.openfx.com%2Fllms.txt%20and%20help%20me%20integrate%20with%20the%20OpenFX%20v3%20API.%20Start%20by%20asking%20what%20I%20want%20to%20build%20%28FX%20trades%2C%20payouts%2C%20deposits%2C%20withdrawals%20or%20webhooks%29%20and%20which%20language%20I%20use.%20Use%20Sandbox%20only%20%28X-App-Mode%3A%20SANDBOX%29%2C%20never%20ask%20me%20to%20paste%20a%20Live%20key%20or%20private%20key%2C%20and%20cite%20the%20docs%20page%20for%20every%20endpoint%20you%20use.) [Claude](https://claude.ai/new?q=Read%20the%20OpenFX%20API%20docs%20at%20https%3A%2F%2Fdocs.openfx.com%2Fllms.txt%20and%20help%20me%20integrate%20with%20the%20OpenFX%20v3%20API.%20Start%20by%20asking%20what%20I%20want%20to%20build%20%28FX%20trades%2C%20payouts%2C%20deposits%2C%20withdrawals%20or%20webhooks%29%20and%20which%20language%20I%20use.%20Use%20Sandbox%20only%20%28X-App-Mode%3A%20SANDBOX%29%2C%20never%20ask%20me%20to%20paste%20a%20Live%20key%20or%20private%20key%2C%20and%20cite%20the%20docs%20page%20for%20every%20endpoint%20you%20use.) [Cursor](https://cursor.com/link/prompt?text=Read%20the%20OpenFX%20API%20docs%20at%20https%3A%2F%2Fdocs.openfx.com%2Fllms.txt%20and%20help%20me%20integrate%20with%20the%20OpenFX%20v3%20API.%20Start%20by%20asking%20what%20I%20want%20to%20build%20%28FX%20trades%2C%20payouts%2C%20deposits%2C%20withdrawals%20or%20webhooks%29%20and%20which%20language%20I%20use.%20Use%20Sandbox%20only%20%28X-App-Mode%3A%20SANDBOX%29%2C%20never%20ask%20me%20to%20paste%20a%20Live%20key%20or%20private%20key%2C%20and%20cite%20the%20docs%20page%20for%20every%20endpoint%20you%20use.) Bring us into your toolsEvery endpoint, ready to import. [Postman Collection](https://www.postman.com/ofx-devs/workspace/openfx/collection/58952302-184b70a6-dc21-41a7-9a15-6e03fcd88303) [OpenAPI JSON](https://api.openfx.com/v3/openapi.json) *** ## First time here? Start with the basics OpenFX API enables treasury teams and fintechs to manage currency conversion and money movement programmatically, at scale. Convert and move funds between your own accounts, or pay businesses and people in other countries. ### Convert Convert currencies and withdraw to your accounts and wallets Coverage 13 currencies Key concepts [Trades](/v3/trades) [Quotes](/v3/quotes) [Withdrawals](/v3/withdrawals) Ideal for internal treasury teams at financial institutions ### Send Move money to suppliers, partners, and customers across borders Coverage 41 countries Key concepts [Payouts](/v3/payouts) [Capabilities](/v3/capabilities) [Account model](/v3/account-model) Ideal for PSPs, remittance companies, exchanges, and neobanks *** ## Need a blueprint to get started? *** Select currencies Pick the currency you sell and the currency you buy. Blueprints lists every integration step for that corridor, with the API calls behind it. [View blueprint →](/v3/blueprints) *** ## That’s the tour. Your move now Request sandbox accessReal quotes, pretend money. Test every flow before going live on production [Request access to Sandbox →](https://www.openfx.com/get-a-demo) Talk to our teamGot questions about Corridor's pricing or your setup? We are happy to help [Book a call →](https://www.openfx.com/get-a-demo) Build [Quickstart](/v3/quickstart) [API Reference](/v3/authentication) [Postman Collection](https://www.postman.com/ofx-devs/workspace/openfx/collection/58952302-184b70a6-dc21-41a7-9a15-6e03fcd88303) [OpenAPI JSON](https://api.openfx.com/v3/openapi.json) Learn [Trades](/v3/trades) [Payouts](/v3/payouts) [Blueprints](/v3/blueprints) [Glossary](/v3/glossary) Help [Status page](/v3/introduction) [Contact support](/v3/introduction) # Live checklist Source: https://docs.openfx.com/v3/live-checklist Pre-launch checklist, key rotation, IP allowlisting, monitoring, and ongoing operations guidance. This page is the pre-launch sign-off checklist for moving an OpenFX integration from Sandbox to Live. It covers authentication and secrets, idempotency and retry behavior, observability, error-handling coverage, Sandbox parity, the cutover steps, key rotation, rate-limit headroom planning, and how to escalate to support. ## Pre-launch checklist > [accordion] Authentication & secrets > > * JWT private key stored in a secrets manager (1Password, AWS Secrets Manager, HashiCorp Vault), never in source control, never in long-lived env vars on a developer laptop > * Sandbox API keys carry a `sandbox_` prefix (Live API keys are unprefixed); the environment is selected by which key you use > * Sandbox key swapped for the unprefixed Live key > * `X-App-Mode` header switched from SANDBOX to LIVE alongside the key; the two must agree > * Key rotation policy documented (minimum quarterly) > * JWT minting helper centralized in one module; not duplicated across services. See [Authentication](/v3/authentication). > [accordion] IP allowlisting > > * Live API key's IP allowlist configured to your egress IP(s) - Egress IPs > documented (find with `curl https://api.ipify.org` from each environment that > hits OpenFX) - Allowlist includes failover regions if applicable - On > AUTH_FORBIDDEN_IP, you alert (don't silently > retry; it's a config bug, not a transient) > [accordion] Live setup and webhooks > > * Live API key and Live webhook signing key created in the > [dashboard](https://app.openfx.com), separate from your Sandbox ones - Live > webhook endpoint registered and subscribed to the event types you handle; > Sandbox registrations don't carry over. See [Webhooks > setup](/v3/webhooks/setup) - If your organization uses Payments, the > `payments.*` and `common.account.*` event types are subscribed too - Trade > webhooks are delivered only to Live endpoints, so the first Live trade is your > first chance to exercise a trade handler - Your settlement model ( > AUTO or MANUAL) is > confirmed, and a MANUAL account has a handler > for fx.trade.ready_to_settle. See > [Trades](/v3/trades#settlement-window) - The currencies and withdrawal > accounts you use are enabled for your organization; a disabled currency > returns TRADE_CURRENCY_NOT_ENABLED_FOR_ACCOUNT > [accordion] Idempotency & retries > > * `Idempotency-Key` generated **once per logical operation**, persisted to > your DB **before** sending the request - Retry path handles `409` > IDEMPOTENCY_IN_FLIGHT by backing off and > re-sending the same key - 5xx on writes triggers a **state check** (GET the > resource by ID) before retrying; see [ > TRADE_EXECUTION_FAILED > rule](/v3/errors#retrying-trade-execution-failed) - Crash-recovery worker > scans for PENDING rows and replays them using > the stored idempotency key; see [Idempotency → Crash > recovery](/v3/idempotency#crash-recovery) > [accordion] Observability > > * Every request logs the response `X-Trace-Id` alongside your internal request ID; see [Metadata & tracing](/v3/metadata-and-tracing) > * Trace ID captured on the **success path too**, not just errors > * `RateLimit-Limit` and `RateLimit-Reset` recorded for capacity planning; 429 rate and `Retry-After` values tracked > * Alerts on error-rate spikes (especially 5xx, 429, and `*_NOT_FOUND` clusters) > * Dashboards group errors by `error.code` (not `error.message`; message text can change) > > **Suggested alert thresholds:** > > * Required Alert when **5xx rate > 0.5%** sustained for 5 min: covers upstream and idempotency-store outages > * Required Alert when **`AUTH_TOKEN_*` error rate > 1%** sustained for 2 min: almost always means the JWT minting flow is broken (bad key, wrong claims, clock drift) > * Recommended Alert when **IDEMPOTENCY_IN_FLIGHT responses** are sustained: indicates upstream slowness; your write latency is elevated even when calls ultimately succeed > * Recommended Alert when **webhook handler queue lag > 30s** if you're using a worker queue: OpenFX retries within the dedup window (see [Webhooks setup](/v3/webhooks/setup)), so a slow handler multiplies your processing cost > > **Clock skew:** sync your JWT-minting host's clock via NTP. The v3 JWT TTL is **60s**, so even a small drift can produce constant AUTH_TOKEN_EXPIRED. If 401s spike right after a deploy or host migration, check the clock before anything else. > [accordion] Error handling coverage > > * Catch-and-branch covers at minimum: > QUOTE_EXPIRED, > QUOTE_ALREADY_CONSUMED, > TRADE_INSUFFICIENT_BALANCE, > WITHDRAWAL_INSUFFICIENT_BALANCE, > IDEMPOTENCY_IN_FLIGHT, > RATE_LIMIT_EXCEEDED, > TRADE_EXECUTION_FAILED, > WITHDRAWAL_INITIATION_FAILED, > INTERNAL_ERROR- Unknown error codes bubble to a > generic handler that logs and alerts; don't silently retry - User-facing error > messages translate `error.code` to localized prose; don't surface raw codes to > end users - Before using a fresh key after a trade or withdrawal failure, > [confirm the resource is missing](/v3/errors#retrying-trade-execution-failed) > [accordion] Sandbox parity > > * End-to-end happy path runs nightly against Sandbox - Error paths tested in > Sandbox: insufficient balance, expired quote, idempotency mismatch, missing > key - Webhook handlers verified against the `X-OpenFX-Signature` (HMAC-SHA256) > signing contract; webhooks share the API's convention (camelCase keys and > string amounts), so **one** deserializer can cover both webhook payloads and > API responses. See [Webhook authentication](/v3/webhooks/authentication) - > Sandbox data is treated as ephemeral; no test workflows depend on records > persisting across resets > [accordion] Reconciliation and rollback > > * A scheduled reconciliation job compares your records against [`GET /v3/fx/trades`](/v3/api-reference/trade/list-trades), [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits), [`GET /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/list-withdrawals), and [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances), so a missed webhook never leaves a gap. See the [polling fallback](/v3/webhooks/setup#polling-fallback) > * One configuration switch stops new trades and withdrawals without a deploy > * The cutover is reversible: your key, signing key, and `X-App-Mode` come from one environment-aware config, so you can point the integration back at Sandbox > * Your runbook states what a rollback can't undo: an EXECUTED trade has already moved funds. Only a READY_TO_SETTLE trade can be [reversed](/v3/trades#reverse-a-trade) ## First day in Live **1. Confirm access** Call [`GET /v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs) and [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances) with the Live key and `X-App-Mode: LIVE`. Both return `200`. **2. Run one trade end to end** Create a quote, execute it, and follow the trade to its final status. Confirm the webhook arrives, verifies, and is processed once. **3. Reconcile** Compare the trade, webhook, and balance change. They agree before you send more traffic. **4. Ramp up** Raise volume in stages while you watch the alerts in the Observability section. Keep the rollback switch within reach until the first full day passes cleanly. ## Key rotation Rotate on a quarterly cadence at minimum, and immediately on any suspected compromise. Use an **overlap pattern**, never a flip: keep the old key valid while the new one goes live, then revoke the old one once every service has cut over. ## Rate-limit headroom planning The ceiling is 300 requests / 10-second window, shared across all endpoints and API keys for your org. Live and Sandbox are separate buckets with the same ceiling. To estimate headroom: * Track your own request rate per org against the `RateLimit-Limit` ceiling on a 10-second rolling window * Set a soft alert when sustained throughput exceeds \~66% of `RateLimit-Limit`; that's the cue to either batch requests, raise larger `limit=` values on list endpoints, or talk to OpenFX about a tier change * The back-off helper pattern lives in [Rate limiting: Handling rate limits](/v3/rate-limiting#handling-rate-limits-pattern); pace well under `RateLimit-Limit` and you should rarely see a 429 in Live * Need a higher ceiling? See [Rate limiting → Need a higher rate limit?](/v3/rate-limiting#need-a-higher-rate-limit) for what to send support to get a tier change ## Support escalation When something goes wrong in Live, the fastest path to a resolved ticket is: * **Trace ID first.** Every support email opens with the `X-Trace-Id` from a failing request. Without it, triage starts with "send us your logs," which adds hours. * **Email:** [support@mail.openfx.com](mailto:support@mail.openfx.com) * **For webhook signing issues:** include the raw `x-openfx-signature` header value alongside the trace ID * **For idempotency collisions (`422` IDEMPOTENCY_MISMATCH):** include both the key and the two distinct request bodies that hit it If you've followed the observability checklist above, the trace ID is already in your logs next to the request that produced it; no spelunking required. # MCP connectors Source: https://docs.openfx.com/v3/mcp-connectors Connect Claude, ChatGPT, Claude Code, or Codex to your OpenFX account to query trades, deposits, and withdrawals in plain language. Use the OpenFX connector to ask an AI app questions about your OpenFX account, build reports, and analyze trades, deposits, and withdrawals in plain language. You don't need an API key or any developer work. ## What the connector can do The OpenFX connector is read-only. It retrieves information from your OpenFX account. It can't place trades, initiate withdrawals, move funds, or change any OpenFX records. | Data | What you can ask for | | - | - | | Currency pairs | Pairs available to your organization | | Trade history | Past trades, filterable by date, pair, and status | | Deposit history | Incoming deposits and their status | | Withdrawal history | Outgoing withdrawals and their status | | Withdrawal accounts | Saved withdrawal destinations on your account | ## Before you begin * **An OpenFX admin has turned on your AI app for your organization.** In the OpenFX dashboard, go to **Organization > MCP Platforms** and switch on the toggle for Claude, ChatGPT, Claude Code, or Codex. Only users with the Admin role can change this setting. * **You have an OpenFX login.** Any OpenFX user can connect. The connector sees only what your OpenFX role already allows. * **Your AI app plan supports custom connectors.** Each tab below lists the plan requirements. * **You know which environment you want.** Live and Sandbox use different URLs. You set up each connection separately, even though your OpenFX login is shared between them. | Environment | OpenFX MCP server URL | | - | - | | Live | `https://mcp.openfx.com/mcp` | | Sandbox | `https://mcp-sandbox.openfx.com/mcp` | ## Connect your AI app Choose your AI app. Every user completes the account connection step once per environment, including the admin who added the connector. > [tab] Claude > > Claude Team and Enterprise organizations add the connector once for everyone. Claude Free, Pro, and Max users add it themselves. Free plans allow one custom connector, so Free users can add Live or Sandbox, not both. > > **Add OpenFX to Claude (Team or Enterprise)** > > Only a Claude organization Owner or Primary Owner can do this. On Enterprise, people with a custom role that includes **Manage access to Libraries** can also do it. Members skip to "Connect your OpenFX account" once it is done. > > **1. Open the connector settings** > > In Claude, go to **Organization settings > Connectors**. Select **Add**, hover over **Custom**, then select **Web**. > > **2. Name the connector and add the URL** > > Enter the name `OpenFX`, or `OpenFX Sandbox` for the Sandbox URL. Paste the OpenFX MCP server URL for your environment, then select **Continue**. > > **3. Confirm the authentication settings** > > Review the settings Claude detected and select **Continue**. Keep OAuth sign-in on, and keep **OAuth client** set to **Use Claude's published identity (Recommended)**. OpenFX doesn't support the other OAuth client options. > > **4. Add the connector** > > Select **Add**. To add both environments, repeat these steps with the Sandbox URL and name each connector clearly so members pick the right one. > > **Add OpenFX to Claude (Free, Pro, or Max)** > > **1. Open your connectors** > > In Claude, go to **Customize > Connectors**, select **+**, then select **Add custom connector**. > > **2. Enter the connector details** > > Enter the name `OpenFX`, paste the OpenFX MCP server URL for your environment, then select **Continue**. > > **3. Add the connector** > > Keep the default authentication settings, with **OAuth client** set to **Use Claude's published identity (Recommended)**. Select **Add**. > > **Connect your OpenFX account** > > **1. Start the connection** > > Go to **Customize > Connectors**, search for OpenFX, select **OpenFX**, then select **Connect**. > > **2. Sign in to OpenFX** > > Claude redirects you to OpenFX. Sign in with your usual OpenFX email, password, and 2FA. If you're already signed in, OpenFX skips this step. > > **3. Approve access** > > Review the read permissions on the OpenFX consent screen, then select **Approve**. OpenFX shows a success screen and returns you to Claude. The OpenFX connector now shows as connected. > > **Use OpenFX in a conversation** > > **1. Turn on the connector** > > Start a new chat. Select **+** at the bottom left of the message box, select **Connectors**, and make sure OpenFX is switched on. > > **2. Ask your question** > > Claude asks for permission the first time it uses each OpenFX tool. Choose **Allow once** or **Always allow**. > [tab] ChatGPT > > ChatGPT Business, Enterprise, and Edu workspaces add OpenFX once for everyone. On individual plans, custom apps require Developer mode, which depends on your plan. Check OpenAI's documentation for current availability. > > > [!WARNING] > > > > Custom apps work in ChatGPT on the web only, not in the ChatGPT mobile apps. > > **Add OpenFX to your workspace** > > A ChatGPT workspace owner or admin completes this once. Members skip to "Connect your OpenFX account" once it is done. > > Developer mode must be on for the admin doing this. On Business, each admin or owner switches it on for themselves, and can do so from the **Create** screen below. On Enterprise and Edu, an admin first allows it under **Workspace settings > Permissions & Roles > Connected Data**, then switches it on in **Settings > Apps > Advanced settings**. > > **1. Create the app** > > Go to **Workspace settings > Apps** and select **Create**. If prompted, switch on Developer mode. > > **2. Fill in the form** > > Enter these values and leave **Advanced settings** at their defaults. OpenFX doesn't use a Client ID or Client Secret. > > * **Name:** `OpenFX`, or `OpenFX Sandbox` > * **Description:** `Read-only access to OpenFX trades, deposits and withdrawals` > * **MCP Server URL:** the OpenFX URL for your environment > * **Authentication:** OAuth > > **3. Scan the tools** > > Select **Scan Tools**. Sign in to OpenFX when prompted, then wait for the scan to finish so ChatGPT loads the OpenFX tools. > > **4. Save the draft** > > Check the acknowledgment box if shown, and select **Create**. ChatGPT saves OpenFX as a draft. > > **5. Publish the app** > > Go to **Workspace settings > Apps > Drafts**, find OpenFX, and select **Publish**. On Enterprise and Edu, use **Configure Access** to choose which groups can use OpenFX, and **Configure Actions** to review the OpenFX tools. Review the safety warnings and select **Publish**. > > > [!NOTE] > > > > ChatGPT keeps a snapshot of the OpenFX tools taken when the app is published. If OpenFX adds or changes tools, an admin must refresh the app's tool list from **Workspace settings > Apps**. You don't need to delete and re-create the app. > > **Add OpenFX on an individual plan** > > **1. Turn on Developer mode** > > Go to **Settings > Apps > Advanced settings** and switch on **Developer mode**. > > **2. Create the app** > > Go to **Settings > Apps** and select **Create**. Enter the name `OpenFX`, a short description, and the OpenFX MCP server URL for your environment. Set authentication to OAuth. > > **3. Scan the tools** > > Select **Scan Tools**, sign in to OpenFX when prompted, then select **Create**. OpenFX appears under **Settings > Apps > Enabled Apps** with a **Dev** label. > > **Connect your OpenFX account** > > **1. Start the connection** > > Search for OpenFX in the ChatGPT apps directory. Your workspace's published apps are labeled **custom**. Select **OpenFX**, then select **Connect**. > > **2. Sign in to OpenFX** > > ChatGPT redirects you to OpenFX. Sign in with your usual OpenFX email, password, and 2FA. If you're already signed in, OpenFX skips this step. > > **3. Approve access** > > Review the read permissions on the OpenFX consent screen, then select **Approve**. OpenFX shows a success screen and returns you to ChatGPT. The OpenFX app now shows as connected. > > **Use OpenFX in a conversation** > > **1. Turn on the app** > > Start a new chat. Select **+** in the message box, select **More**, then select **OpenFX**. The OpenFX icon appears in the message box. > > **2. Ask your question** > > For follow-ups that need fresh data, mention `@OpenFX` again. > [tab] Claude Code > > Claude Code is included with Claude Pro, Max, Team, and Enterprise plans, and also works with a Claude Console account. Install and sign in to Claude Code before you start. > > > [!NOTE] > > > > Using Claude Code in the Claude desktop app? Desktop app sessions don't load servers added from the terminal. Use the Claude tab instead. Once OpenFX is connected in Claude, it's available in your desktop app Code sessions with no extra setup. > > **Allow OpenFX in your organization's MCP policy (admins only)** > > Skip this step if your organization doesn't restrict which MCP servers Claude Code can use. If OpenFX is blocked, members see an "enterprise policy" error when they add it. An administrator who manages Claude Code settings completes this once. Choose the option that matches how your organization manages MCP servers. > > > [accordion] Your organization uses an MCP allowlist > > > > Add the OpenFX URLs to `allowedMcpServers` in your managed settings. Use server-managed settings in the Claude admin console, or a `managed-settings.json` file deployed through your device management tool. Add this fragment to your settings file: > > > > ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} > > { > > "allowedMcpServers": [ > > { "serverUrl": "https://mcp.openfx.com/mcp" }, > > { "serverUrl": "https://mcp-sandbox.openfx.com/mcp" } > > ] > > } > > ``` > > > > Add these entries to your existing list rather than replacing it. Match OpenFX by `serverUrl`, not `serverName`, because each user chooses their own server names. Also check that no entry in `deniedMcpServers` matches the OpenFX URLs, because the denylist always wins. > > > [accordion] You want to provide OpenFX to everyone > > > > List OpenFX under `managedMcpServers` in your managed settings. Every user gets OpenFX automatically, alongside their own servers, and skips the add step. This requires Claude Code v2.1.259 or later. Add this fragment to your settings file: > > > > ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} > > { > > "managedMcpServers": { > > "openfx": { > > "type": "http", > > "url": "https://mcp.openfx.com/mcp" > > }, > > "openfx-sandbox": { > > "type": "http", > > "url": "https://mcp-sandbox.openfx.com/mcp" > > } > > } > > } > > ``` > > > > Each user still signs in to OpenFX with their own login. Don't add OpenFX credentials or headers to this file. > > > [accordion] Your organization deploys a fixed server list > > > > Users can't add servers themselves in this mode. Add the same `openfx` entries from the previous option under `mcpServers` in your `managed-mcp.json` file, then redeploy it. > > > > | Platform | `managed-mcp.json` location | > > | - | - | > > | macOS | `/Library/Application Support/ClaudeCode/managed-mcp.json` | > > | Linux and WSL | `/etc/claude-code/managed-mcp.json` | > > | Windows | `C:\Program Files\ClaudeCode\managed-mcp.json` | > > To confirm the change, run `claude mcp list` on a managed machine. OpenFX appears in the list. > > **Add OpenFX to Claude Code** > > Skip this step if your admin provides OpenFX to everyone. Run `claude mcp list`. If `openfx` is already listed, go to the next section. If you already connected OpenFX in Claude and sign in to Claude Code with the same Claude account, Claude Code picks up your Claude connectors automatically. OpenFX appears as `claude.ai OpenFX` under `/mcp`, and you can skip to "Use OpenFX in a session". > > **1. Add the server** > > Run the command for your environment. > > ```bash Live theme={"theme":{"light":"poimandres","dark":"poimandres"}} > claude mcp add --transport http --scope user openfx https://mcp.openfx.com/mcp > ``` > > ```bash Sandbox theme={"theme":{"light":"poimandres","dark":"poimandres"}} > claude mcp add --transport http --scope user openfx-sandbox https://mcp-sandbox.openfx.com/mcp > ``` > > `--scope user` makes OpenFX available in every project on your computer. Leave it out to add OpenFX to the current project only. > > **2. Confirm the server** > > Run `claude mcp list` and confirm `openfx` appears. > > **Connect your OpenFX account** > > **1. Start the sign-in** > > Run `claude`, type `/mcp`, select **openfx**, then select **Authenticate**. You can also run `claude mcp login openfx` from your terminal. > > **2. Sign in to OpenFX** > > Your browser opens to OpenFX. Sign in with your usual OpenFX email, password, and 2FA. If you're already signed in, OpenFX skips this step. If your browser doesn't open, copy the sign-in link Claude Code shows and open it yourself. > > **3. Approve access** > > Review the read permissions on the OpenFX consent screen, then select **Approve**. OpenFX shows a success screen. Return to your terminal. `/mcp` now shows OpenFX as connected. > > **Use OpenFX in a session** > > Start Claude Code in any folder and mention OpenFX in your question, for example "Using OpenFX, …". Claude Code asks for permission the first time it uses each OpenFX tool. Approve it once, or allow it for future sessions. > [tab] Codex > > Codex is included with ChatGPT Plus, Pro, Business, Edu, and Enterprise plans. Install and sign in to Codex before you start. > > > [!NOTE] > > > > The Codex app, Codex CLI, and Codex IDE extension share the same MCP settings. Add OpenFX once from any of them and it's available in all three. Codex doesn't use the OpenFX app your workspace published in ChatGPT, so set it up here even if you already use OpenFX in ChatGPT. > > **Allow OpenFX in your organization's MCP policy (admins only)** > > Skip this step if your organization doesn't restrict which MCP servers Codex can use. If OpenFX is blocked, it shows as disabled in Codex after you add it. An admin who manages Codex requirements completes this once. > > **1. Add the allowlist entries** > > Add these entries to the `mcp_servers` allowlist in your Codex requirements. > > ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} > [mcp_servers.openfx] > identity = { url = "https://mcp.openfx.com/mcp" } > > [mcp_servers.openfx-sandbox] > identity = { url = "https://mcp-sandbox.openfx.com/mcp" } > ``` > > **2. Deliver the requirements** > > Use the method your organization already uses. In the ChatGPT Admin Console, open **Agent Security** and add the entries to your cloud-managed requirements. These apply to users who sign in to Codex with ChatGPT. With device management, add the entries to the system `requirements.toml` file, or to the `requirements_toml_base64` key in the `com.openai.codex` preference domain on macOS. > > | Platform | `requirements.toml` location | > | - | - | > | macOS and Linux | `/etc/codex/requirements.toml` | > | Windows | `%ProgramData%\OpenAI\Codex\requirements.toml` | > > > [!WARNING] > > > > Codex enables a server only when both its name and its URL match an allowlist entry. Tell members to use the exact names `openfx` and `openfx-sandbox`. Add these entries to your existing allowlist rather than replacing it. An empty `mcp_servers` allowlist disables every MCP server. > > **Add OpenFX to Codex** > > Choose the path that matches how you use Codex. You only need one. > > > [tab] Codex CLI > > > > Run the command for your environment, then run `codex mcp list` and confirm `openfx` appears. > > > > ```bash Live theme={"theme":{"light":"poimandres","dark":"poimandres"}} > > codex mcp add openfx --url https://mcp.openfx.com/mcp > > ``` > > > > ```bash Sandbox theme={"theme":{"light":"poimandres","dark":"poimandres"}} > > codex mcp add openfx-sandbox --url https://mcp-sandbox.openfx.com/mcp > > ``` > > > [tab] Codex app > > > > **1. Add a server** > > > > Go to **Settings > MCP servers**, then select **Add server**. In the Codex IDE extension, the same settings are under the gear menu. > > > > **2. Enter the details** > > > > Enter the name `openfx`, or `openfx-sandbox` for the Sandbox URL. Use these exact names if your organization uses an MCP allowlist. Choose **Streamable HTTP** and paste the OpenFX MCP server URL for your environment. > > > > **3. Save the server** > > > > Save the server. > > **Connect your OpenFX account** > > **1. Start the sign-in** > > Run `codex mcp login openfx` in your terminal. In the Codex app, open **Settings > MCP servers** and select **Authenticate** next to OpenFX. > > **2. Sign in to OpenFX** > > Your browser opens to OpenFX. Sign in with your usual OpenFX email, password, and 2FA. If you're already signed in, OpenFX skips this step. > > **3. Approve access** > > Review the read permissions on the OpenFX consent screen, then select **Approve**. OpenFX shows a success screen. Return to Codex. OpenFX now shows as connected. > > **Use OpenFX in a session** > > Start a new Codex thread in the app, or run `codex` in your terminal. In the CLI, type `/mcp` to confirm OpenFX is active. Mention OpenFX in your question, for example "Using OpenFX, …". Depending on your approval settings, Codex may ask you to approve OpenFX tool calls. ## Try it Start a new conversation or session and try one of these prompts: * "Show me all my trades from last month, grouped by currency pair, with total notional per pair." * "Compare my deposit and withdrawal totals month over month for Q3 and flag anything unusual." * "List the currency pairs available to my organization." * "Build a reconciliation table of every withdrawal this week with its destination account." > [!TIP] > > Scheduled or recurring reports use your AI app's own scheduling features. OpenFX doesn't run schedules on your behalf. ## Manage or disconnect You can disconnect from your AI app or from OpenFX. | AI app | Disconnect from the app | | - | - | | Claude | Go to **Customize > Connectors**, select **OpenFX**, then select **Disconnect**. Claude organization Owners can remove the connector for everyone from **Organization settings > Connectors**. To change the URL, remove the connector and add it again. | | ChatGPT | Go to **Settings > Apps**, select **OpenFX**, then select **Disconnect**. Workspace admins can unpublish or delete OpenFX for everyone from workspace apps. | | Claude Code | Run `claude mcp list` to see status, `claude mcp logout openfx` to sign out and keep the server, or `claude mcp remove openfx` to remove it and its stored sign-in. To change the URL, remove OpenFX and add it again. If your admin provides OpenFX through managed settings, you can turn it off for yourself in `/mcp`, and admins remove it for everyone by deleting the entry from managed settings. | | Codex | Run `codex mcp list` to see status, `codex mcp logout openfx` to sign out and keep the server, or `codex mcp remove openfx` to remove it. In the Codex app, use **Settings > MCP servers**. Admins block OpenFX for everyone by removing its entries from the `mcp_servers` allowlist. | To disconnect from OpenFX, go to **Profile > MCP Platforms** in the OpenFX dashboard. Your AI app is listed with its connection status. Select **Disconnect** to end the session. This works even if you no longer have access to the AI app account or the computer where it's installed. An OpenFX admin can also switch an AI app off for the whole organization under **Organization > MCP Platforms**. This disconnects every user in the organization. ## Session length Your connection stays active for 30 days from when you approve access on the OpenFX consent screen, whether or not you use it. You don't need to sign in again during that time. After 30 days, your AI app asks you to sign in to OpenFX again. If your OpenFX user is suspended or removed, the connection stops working immediately. ## Troubleshooting | What you see | What to do | | - | - | | "MCP is not enabled for your organization" | Ask an OpenFX admin to switch on your AI app under **Organization > MCP Platforms**, then try connecting again. | | "Unsupported platform" | You added the URL to an AI app OpenFX doesn't support. Use Claude, ChatGPT, Claude Code, or Codex. | | A dataset is missing, for example withdrawal accounts | The connector shows only data your OpenFX role allows. Ask your OpenFX admin to review your role. | | You see test data, or expected test data is missing | Check that you added the right URL. Live and Sandbox are separate connections. | | Your AI app asks you to sign in again | Your session expired. Complete the OpenFX sign-in again. In Claude Code, run `/mcp`. In Codex, run `codex mcp login openfx`. | | OpenFX isn't listed in Claude under **Customize > Connectors** | Your Claude Owner hasn't added it yet. Share this page with them. | | OpenFX doesn't appear in ChatGPT search | Your workspace admin hasn't published it yet, or hasn't given your group access. Share this page with them. | | OpenFX is missing in ChatGPT on your phone | Custom apps work on the web only. Use `chatgpt.com` in a browser. | | Claude Code: "Cannot add MCP server "openfx": not allowed by enterprise policy" | Your organization uses an MCP allowlist that doesn't include OpenFX. Ask your Claude Code admin to allow the OpenFX URLs. | | Claude Code: "Cannot add MCP server "openfx": server is explicitly blocked by enterprise policy" | OpenFX matches your organization's denylist. Ask your Claude Code admin to remove the matching entry. | | Claude Code: "enterprise MCP configuration is active and has exclusive control over MCP servers" | Your organization deploys a fixed server list. Ask your Claude Code admin to add OpenFX to `managed-mcp.json`. | | OpenFX disappeared from `/mcp` after working before | Your organization's MCP policy changed and now blocks OpenFX. Share this page with your Claude Code admin. | | OpenFX is missing in the Claude desktop app | Desktop app sessions don't load servers added from the terminal. Connect OpenFX in Claude instead. | | Codex shows OpenFX as disabled | Your organization uses an MCP allowlist. Check that you named the server exactly `openfx` or `openfx-sandbox`. If it's still disabled, ask your admin to allow the OpenFX URLs. | | Every MCP server is disabled in Codex | Your organization's allowlist is empty. Share this page with your admin. | | Anything else | Contact OpenFX support at [support@mail.openfx.com](mailto:support@mail.openfx.com) with the time of the error and the AI app you were using. | > [!NOTE] > > Data you retrieve is returned to your AI app and processed under that provider's terms: Anthropic for Claude and Claude Code, OpenAI for ChatGPT and Codex. Review the provider's data policies and your organization's AI usage policy before connecting. # Metadata & tracing Source: https://docs.openfx.com/v3/metadata-and-tracing Every response carries an X-Trace-Id and an X-Request-Timestamp. Log the trace ID for correlation, retries, and support triage. Every v3 response (success or error) carries an `X-Trace-Id` and an `X-Request-Timestamp`. `X-Trace-Id` is OpenFX's correlation handle for the request. Log it on every call so you can stitch together your own logs across retries and services, and give OpenFX support the trace they need. For your own per-call correlation, send an optional `X-Request-Id` header. See [Client request correlation](#client-request-correlation). FX withdrawals additionally accept a persistent `metadata` object in the body that outlives the single request. See [Withdrawal metadata](#withdrawal-metadata). ## Response headers | Header | Type | Purpose | | - | - | - | | `X-Trace-Id` | string | The correlation and support/debug handle for this request hop. A valid client `traceparent` or (when no valid `traceparent` is supplied) `X-Trace-Id` is adopted; otherwise the gateway generates a trace ID. Quote it when filing a support ticket. | | `X-Request-Timestamp` | string (RFC 3339, ms) | The server's UTC timestamp of when the request reached the API service, e.g. `2026-05-29T12:34:56.789Z`. Useful for clock-skew checks and ordering your own logs against server time. | > [!NOTE] > > **Server-side and client-side correlation are separate headers.** `X-Trace-Id` > is the server-generated request identifier, present on every response; there > is no server `requestId` field in the response body. `X-Request-Id` is the > client-side equivalent: optional, and echoed back only when it matches the > required format. See [Client request correlation](#client-request-correlation). If > you need a body-portable copy of the server handle (for queued retries or > webhook envelopes that lose HTTP headers), capture `X-Trace-Id` into your own > log record at call time. ```http theme={"theme":{"light":"poimandres","dark":"poimandres"}} HTTP/1.1 200 OK X-Trace-Id: 4bf92f3577b34da6a3ce929d0e0e4736 X-Request-Timestamp: 2026-05-29T12:34:56.789Z Content-Type: application/json ``` ## Client request correlation `X-Trace-Id` is the **server's** correlation handle. For **your own** per-call correlation, send an optional `X-Request-Id` header on any request: | Header | Direction | Purpose | | - | - | - | | `X-Request-Id` | Request | Optional, client-chosen. Must contain 1-200 characters from `[A-Za-z0-9_.-]`; a valid value is echoed back. An invalid value returns `400` VALIDATION_HEADER_FAILED. | `X-Request-Id` is independent of `X-Trace-Id`: it's client-generated and lives in headers on both the request and the response when valid, for the lifetime of that one HTTP round-trip. There is no server-generated `requestId` field in any response body. ```http theme={"theme":{"light":"poimandres","dark":"poimandres"}} GET /v3/fx/pairs HTTP/1.1 X-Request-Id: my-req-abc-123 HTTP/1.1 200 OK X-Request-Id: my-req-abc-123 X-Trace-Id: 4bf92f3577b34da6a3ce929d0e0e4736 ``` > [!NOTE] > > **`X-Request-Id` vs `X-Trace-Id`.** `X-Request-Id` is **your** correlation > value, chosen by your client and echoed back only when you send it. > `X-Trace-Id` is **OpenFX's** debug/trace handle, present on every response > (success and error) whether or not you sent an `X-Request-Id`. Include both > when you log, and quote `X-Trace-Id` when filing a support ticket. ## Withdrawal metadata For bookkeeping that should persist with the resource (not just the one request/response round-trip), `POST /v3/fx/withdrawals` accepts an optional `metadata` object in the request body. This is a separate mechanism from `X-Request-Id`: `X-Request-Id` is per-call and lives in headers; `metadata` is per-resource, persists with the withdrawal, and travels in the body. Within the FX API (`/v3/fx/...`), `metadata` is accepted only on `POST /v3/fx/withdrawals`. The Payments API accepts its own `metadata` object on [create account](/v3/api-reference/payments/accounts/create-account), [create payout address](/v3/api-reference/payments/addresses/create-payout-address), [create payout quote](/v3/api-reference/payments/payouts/create-payout-quote), and [create payout](/v3/api-reference/payments/payouts/create-payout), with the same key-count, key-length, value-length, and total-size limits as below. Payments metadata keys are also limited to letters, digits, and underscores. It is a general-purpose, client-owned bag: keys are client-defined strings (for example `metadata.customerId`, `metadata.reconId`). All values must be **strings**. The server treats `metadata` as **opaque pass-through**: it enforces only size and structure limits, never interprets the contents, persists it with the withdrawal, and returns it nested inside the resource at `data.metadata` on the **success response**, **not** as a top-level sibling of `data`. **Limits:** at most 50 keys, each key ≤ 40 characters, each value ≤ 500 characters, and the serialized object under 8 KB. A request that exceeds any of these limits is rejected with `400` VALIDATION_BODY_FAILED. ```json title="Request: POST /v3/fx/withdrawals" theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "withdrawalAccountId": "wac_NDqQ9LmcUASpnHR6CTvdkk", "withdrawalAmount": "100.00", "currency": "USD", "metadata": { "customerId": "cus_12345", "reconId": "recon-2026-0001" } } ``` The success response nests the `Withdrawal` resource inside `data`, with `metadata` nested inside it, not as a sibling of `data`: ```json title="Success response: metadata nested inside data.metadata, not a sibling of data" theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "data": { "object": "withdrawal", "id": "wtd_6SATV6VSUdBTttHWBmCYjD", "withdrawalAccountId": "wac_NDqQ9LmcUASpnHR6CTvdkk", "withdrawalAmount": "100.00", "currency": "USD", "assetType": "FIAT", "status": "PENDING", "network": null, "actorId": "usr_7m4VsfRw4pGrS76WYj5tnx", "actorEmail": "client-user@example.com", "createdAt": "2026-04-28T10:00:00.000Z", "metadata": { "customerId": "cus_12345", "reconId": "recon-2026-0001" } } } ``` > [!WARNING] > > **Metadata is visible in the OpenFX platform, API, and MCP server, including connected AI tools.** Don't include sensitive or personal data in `metadata`. > [!WARNING] > > **`metadata` is set at creation and can't be changed afterward.** v3 has no > `PATCH` endpoints, so a withdrawal's `metadata` is fixed once the withdrawal > is created. It is also **not currently filterable** on [`GET > /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/list-withdrawals). > Fetch and filter client-side. > [!WARNING] > > **`metadata` is returned on success responses only.** It is **never** echoed > on error responses. An error envelope carries `code`, `type`, `message`, and > `details`, with no `metadata`. To correlate a failed call, read the > `X-Trace-Id` response header (and your own logged copy of the `metadata` you > sent). On read endpoints (`GET` / list), any `metadata` sent is ignored. ## Encoding Requests use UTF-8 encoded `application/json`. Responses use `Content-Type: application/json` without a charset parameter. A request body with duplicate JSON keys returns `400` VALIDATION_BODY_FAILED. ## Timestamp precision Across v3, timestamp fields such as `X-Request-Timestamp`, `createdAt`, `expiresAt`, and `completedAt` are RFC 3339 / ISO 8601 in UTC with **millisecond** precision and a trailing `Z`. `RateLimit-Reset` and `Retry-After` are not timestamps at all: both are plain integers counting **seconds until you should retry**, per the IETF `RateLimit-*` convention. See [Rate limiting](/v3/rate-limiting). ## Logging pattern A two-line capture on every request is enough to make support and incident response fast: ```javascript Node theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Logs X-Trace-Id and X-Request-Timestamp on every call — the pattern from // /v3/metadata-and-tracing#logging-pattern, run against a real endpoint. // signRequest is the real helper from /v3/authentication — adjust this path // if you've copied it somewhere else in your own project. const { signRequest } = require("../../authentication/node/sign-request"); // Pulls the two correlation fields off any v3 response. Kept separate from // the network call so it's testable without a real request. function formatLogEntry(res, op) { return { traceId: res.headers.get("x-trace-id"), serverTime: res.headers.get("x-request-timestamp"), op, status: res.status, }; } async function listPairs() { const url = "https://api.openfx.com/v3/fx/pairs"; const { headers } = signRequest({ method: "GET", url }); const res = await fetch(url, { headers }); const data = await res.json(); console.log(formatLogEntry(res, "list_pairs")); return data; } module.exports = { formatLogEntry, listPairs }; if (require.main === module) { listPairs().catch((err) => { console.error("Error:", err.message); process.exitCode = 1; }); } ``` ```python Python theme={"theme":{"light":"poimandres","dark":"poimandres"}} """Logs X-Trace-Id and X-Request-Timestamp on every call — the pattern from /v3/metadata-and-tracing#logging-pattern, run against a real endpoint.""" import os import sys # sign_request is the real helper from /v3/authentication — adjust this path # if you've copied it somewhere else in your own project. sys.path.insert( 0, os.path.join(os.path.dirname(__file__), "..", "..", "authentication", "python") ) from sign_request import sign_request # noqa: E402 import requests # noqa: E402 def format_log_entry(res, op): """Pulls the two correlation fields off any v3 response. Kept separate from the network call so it's testable without a real request.""" return { "trace_id": res.headers.get("x-trace-id"), "server_time": res.headers.get("x-request-timestamp"), "op": op, "status": res.status_code, } def list_pairs(): url = "https://api.openfx.com/v3/fx/pairs" headers, _ = sign_request("GET", url) res = requests.get(url, headers=headers) print(format_log_entry(res, "list_pairs")) return res.json() if __name__ == "__main__": list_pairs() ``` ```java Java theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Logs X-Trace-Id and X-Request-Timestamp on every call — the pattern from // /v3/metadata-and-tracing#logging-pattern, run against a real endpoint. import java.net.HttpURLConnection; import java.net.URI; import java.util.LinkedHashMap; import java.util.Map; public class LogTrace { // A response reduced to just the fields formatLogEntry needs, so it's // testable without a real HttpURLConnection. static class ResponseInfo { final String traceId; final String serverTime; final int status; ResponseInfo(String traceId, String serverTime, int status) { this.traceId = traceId; this.serverTime = serverTime; this.status = status; } } // Pulls the two correlation fields off any v3 response. Kept separate // from the network call so it's testable without a real request. static Map formatLogEntry(ResponseInfo res, String op) { Map entry = new LinkedHashMap<>(); entry.put("traceId", res.traceId); entry.put("serverTime", res.serverTime); entry.put("op", op); entry.put("status", res.status); return entry; } public static void main(String[] args) throws Exception { String url = "https://api.openfx.com/v3/fx/pairs"; // SignRequest is the real helper from /v3/authentication, compiled // on the classpath alongside this file — see that page's example. Map headers = SignRequest.signRequest("GET", url, new byte[0]); HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection(); conn.setRequestMethod("GET"); for (Map.Entry h : headers.entrySet()) { conn.setRequestProperty(h.getKey(), h.getValue()); } int status = conn.getResponseCode(); ResponseInfo info = new ResponseInfo( conn.getHeaderField("X-Trace-Id"), conn.getHeaderField("X-Request-Timestamp"), status); System.out.println(formatLogEntry(info, "list_pairs")); } } ``` ```cpp C++ theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Logs X-Trace-Id and X-Request-Timestamp on every call — the pattern from // /v3/metadata-and-tracing#logging-pattern, run against a real endpoint. // Requires OpenSSL and libcurl. #include #include #include #include #include #include // Matches the definition in ../../authentication/cpp/sign_request.cpp, // compiled together with this file — see that file for the real // implementation of signRequest. struct SignedRequest { std::string authHeader; std::string sigHeader; }; SignedRequest signRequest(const std::string& method, const std::string& urlPath, const std::string& query, const std::string& body); struct ResponseInfo { std::string traceId; std::string serverTime; long status; }; // Pulls the two correlation fields off any v3 response. Kept separate from // the network call so it's testable without a real request. std::map formatLogEntry(const ResponseInfo& res, const std::string& op) { return { {"traceId", res.traceId}, {"serverTime", res.serverTime}, {"op", op}, {"status", std::to_string(res.status)}, }; } static std::string toLower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); }); return s; } static size_t captureHeader(char* buffer, size_t size, size_t nitems, void* userdata) { auto* headers = static_cast*>(userdata); std::string line(buffer, size * nitems); size_t colon = line.find(':'); if (colon != std::string::npos) { std::string name = toLower(line.substr(0, colon)); std::string value = line.substr(colon + 1); while (!value.empty() && value.front() == ' ') value.erase(0, 1); while (!value.empty() && (value.back() == '\r' || value.back() == '\n')) value.pop_back(); (*headers)[name] = value; } return size * nitems; } #ifndef LOG_TRACE_NO_MAIN int main() { try { std::string url = "https://api.openfx.com/v3/fx/pairs"; SignedRequest req = signRequest("GET", "/v3/fx/pairs", "", ""); CURL* curl = curl_easy_init(); std::map respHeaders; curl_slist* requestHeaders = nullptr; requestHeaders = curl_slist_append(requestHeaders, ("Authorization: " + req.authHeader).c_str()); requestHeaders = curl_slist_append(requestHeaders, ("X-Request-Signature: " + req.sigHeader).c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, requestHeaders); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, captureHeader); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &respHeaders); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, +[](char*, size_t s, size_t n, void*) { return s * n; }); CURLcode rc = curl_easy_perform(curl); if (rc != CURLE_OK) throw std::runtime_error(curl_easy_strerror(rc)); long status = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status); ResponseInfo info{respHeaders["x-trace-id"], respHeaders["x-request-timestamp"], status}; for (const auto& [key, value] : formatLogEntry(info, "list_pairs")) { std::cout << key << ": " << value << std::endl; } curl_slist_free_all(requestHeaders); curl_easy_cleanup(curl); return 0; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } #endif ``` ```go Go theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Logs X-Trace-Id and X-Request-Timestamp on every call — the pattern from // /v3/metadata-and-tracing#logging-pattern, run against a real endpoint. package main import ( "fmt" "net/http" // auth is the real signRequest helper from /v3/authentication — see // go.mod's replace directive if you've copied it somewhere else. auth "openfx-v3-authentication-example" ) // Pulls the two correlation fields off any v3 response. Kept separate from // the network call so it's testable without a real request. func formatLogEntry(res *http.Response, op string) map[string]interface{} { return map[string]interface{}{ "traceId": res.Header.Get("X-Trace-Id"), "serverTime": res.Header.Get("X-Request-Timestamp"), "op": op, "status": res.StatusCode, } } func listPairs() (map[string]interface{}, error) { url := "https://api.openfx.com/v3/fx/pairs" signed, err := auth.SignRequest("GET", url, nil) if err != nil { return nil, err } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, v := range signed.Headers { req.Header.Set(k, v) } res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() entry := formatLogEntry(res, "list_pairs") fmt.Println(entry) return entry, nil } func main() { if _, err := listPairs(); err != nil { fmt.Println("Error:", err) } } ``` > [!TIP] > > Log `X-Trace-Id` on success and error paths. Success-path logs are often what > you need to explain a later failure. ## Filing a support ticket When something goes wrong, include the `X-Trace-Id` from the failing response. ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} Subject: Trade execution returning 500 on USDC_USD Hi OpenFX support, I'm seeing intermittent 500s on POST /v3/fx/trades. Latest X-Trace-Id: 4bf92f3577b34da6a3ce929d0e0e4736 Time: ~2026-04-28 10:00 UTC ``` ## Common mistakes * Reading trace info from the body: the trace handle is the `X-Trace-Id` **header**; there is no body trace field * Logging only on errors (you lose context for prior successful calls) * Truncating the trace ID in logs * Comparing `X-Request-Timestamp` against a local clock without allowing for skew ## What's next > [card] [Errors](/v3/errors) > > When something goes wrong, start with headers and code-based triage. > [card] [Rate limiting](/v3/rate-limiting) > > Headers for back-pressure. # Payouts to Mexico Source: https://docs.openfx.com/v3/mxn-payout-integration Pay a Mexican bank account in MXN over SPEI: register the CLABE, then meet the memo and ownership-check rules. Pay a bank account in Mexican pesos (MXN). For the general flow, see [Payout lifecycle](/v3/payouts). The quote, confirm, and webhook steps are the same as for EUR, and so is the fee model. [Supported payout currencies](/v3/payouts#supported-payout-currencies) compares every payout currency side by side. ## Before you start * Your organization must be enabled for MXN. Until it is, listing the financial accounts that can fund a MXN payout fails with `403` PAYOUT_CURRENCY_NOT_ENABLED, and a quote or payout fails with `409` PAYOUT_NOT_ENABLED. * The recipient's account needs the Mexican-peso receiving capability, ACTIVE before you pay. [Capabilities](/v3/capabilities#the-capability-catalog) lists the id, and [Be paid in Mexican pesos](/v3/capabilities#be-paid-in-mexican-pesos) lists the identity the recipient owes. * MXN has no sending capability. Don't send a `sender` on a quote or payout, or it fails with `422` SENDER_NOT_SUPPORTED. * Every `POST` needs an `Idempotency-Key` header. See [Idempotency](/v3/idempotency#payments-endpoints). ## Register the bank account A Mexican bank account is identified by its CLABE and paid over SPEI, which settles each transfer individually in real time. The recipient owes an RFC or a CURP, or for an organization an RFC. See [Be paid in Mexican pesos](/v3/capabilities#be-paid-in-mexican-pesos). Register the account with `routingFamily` MX_LOCAL and the CLABE as `accountNumber`. Send `accountHolderName` only if the bank holds the account under a different name from the account's. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "payoutAddressType": "BANK_ACCOUNT", "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", "bankAccount": { "routingFamily": "MX_LOCAL", "accountNumber": "012180001234567899" } }' ``` An ownership check (SPEI_ACCOUNT_OWNERSHIP) starts when you create the address. It resolves later, usually within minutes and only during Mexican banking hours. The address doesn't wait for it, so it can be ACTIVE while the check is still PENDING. Only a NO_MATCH result rejects the address. ## Memos On SPEI, a `receiverMemo` is at most 40 letters, digits, and spaces. A memo that is too long or holds any other character fails with `400` RECEIVER_MEMO_INVALID. OpenFX never truncates it. ## Track settlement `settlementTraceId` on a SPEI payout has the key TRACKING_KEY, the clave de rastreo that the receiving bank uses to find the transfer. [Trace a payout with the receiving bank](/v3/payouts#trace-a-payout-with-the-receiving-bank) lists the key for every rail. ## Common mistakes * **Naming a `sender`.** MXN has no sending capability. Remove `sender` from the quote and the payout. * **Sending `purpose`.** Only AED takes one. * **Treating a pending ownership check as a block.** A payout can be created while SPEI_ACCOUNT_OWNERSHIP is still PENDING. A later NO_MATCH still rejects the address. ## What's next > [card] [Payout lifecycle](/v3/payouts) > > The general payout flow. > [card] [Capabilities](/v3/capabilities#the-capability-catalog) > > The receiving capability and identity each currency needs. > [card] [Payouts in EUR](/v3/eur-payout-integration) > > Paying euro accounts over SEPA or SWIFT. > [card] [Payouts to Colombia](/v3/cop-payout-integration) > > Paying Colombian bank accounts and Bre-B keys. > [card] [Payouts to the UAE](/v3/aed-payout-integration) > > Paying UAE bank accounts by IBAN. > [card] [Payment Webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Every payout and address event. # Pagination Source: https://docs.openfx.com/v3/pagination Paginated list endpoints use cursor pagination with a Stripe-style startingAfter / endingBefore pattern. No page numbers, no deep-pagination cliff. **What this is.** Every v3 list endpoint returns results in chunks. You navigate forward or backward using an **opaque cursor** the server returns to you. Cursors are tokens: treat them as strings, and pass them back unchanged. **When it matters.** Any time you list trades, deposits, withdrawals, withdrawal accounts, accounts, payout addresses, or payouts. Two common patterns: "load all records" (back-fill into your DB) and "fetch what's new since I last polled" (continuous sync). **What you'll learn.** The request parameters, response envelope, forward and backward iteration patterns, and why page numbers (and total counts) don't exist here. These v3 list endpoints use cursor pagination: [`GET /v3/fx/trades`](/v3/api-reference/trade/list-trades), [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits), [`GET /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/list-withdrawals), [`GET /v3/fx/withdrawal-accounts`](/v3/api-reference/trade-settlement/list-withdrawal-accounts), [`GET /v3/common/accounts`](/v3/api-reference/payments/accounts/list-accounts), [`GET /v3/payments/payout-addresses`](/v3/api-reference/payments/addresses/list-payout-addresses), and [`GET /v3/payments/payouts`](/v3/api-reference/payments/payouts/list-payouts). Results are sorted **newest-first by `createdAt`** and you page through them using cursors returned in the response. Default page size is **25**; maximum is **100**. ## Request parameters | Param | Type | Default | Notes | | - | - | - | - | | `limit` | integer (1–100) | 25 | Max records per page | | `startingAfter` | opaque cursor string | none | Return records **older** than the cursor's position (next page) | | `endingBefore` | opaque cursor string | none | Return records **newer** than the cursor's position (previous page) | `startingAfter` and `endingBefore` are mutually exclusive. Set one or the other, not both. On the first request, omit both. You get the newest page. > [!NOTE] > > **Cursors are opaque.** The cursor value the server returns is a string token. > Treat it as opaque. Do not decode, trim, re-encode, parse, or substitute its > contents. Pass it back verbatim. The token's internal format is an > implementation detail and OpenFX reserves the right to change it. > [!TIP] > > **Mental model.** Lists are newest-first, so "starting after this cursor" > means "older than the records this cursor points at" and "ending before this > cursor" means "newer than the records this cursor points at". Think of the > cursor as a position on a vertical timeline with newest at the top. ## Response envelope Paginated responses wrap the array of records in a `pagination` envelope that carries the cursors for navigation: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "data": [], "pagination": { "limit": 25, "hasNext": true, "nextCursor": "eyJjcmVhdGVkQXQiOiIyMDI2LTAyLTA3VDEzOjAyOjI5LjE0N1oiLCJpZCI6IjZhOGRmZjAzLWFiY2QtNDEyMy1iYWNkLTAxMjM0NTY3ODlhYiJ9", "hasPrev": false, "prevCursor": null } } ``` | Field | Type | Notes | | - | - | - | | `data` | array | The records on this page, newest-first. | | `pagination.limit` | integer | The `limit` the server used (echoes your request or the default). | | `pagination.hasNext` | boolean | `true` if more records exist after this page: the signal to keep paginating forward. `false` on the last page. | | `pagination.nextCursor` | `string \| null` | Opaque token for the next page (older records); pass to `?startingAfter=`. `null` when `hasNext` is `false`. | | `pagination.hasPrev` | boolean | `true` if records exist before this page: the signal to keep paginating backward. `false` on the first page. | | `pagination.prevCursor` | `string \| null` | Opaque token for the previous page (newer records); pass to `?endingBefore=`. `null` when `hasPrev` is `false`. | `hasNext` / `hasPrev` are the booleans you branch on; `nextCursor` / `prevCursor` are the tokens you pass back. A page with both `hasNext: false` and `hasPrev: false` is the entire paginated result set. > [!NOTE] > > **Bounded lists do not paginate.** `GET /v3/fx/pairs`, > `GET /v3/fx/balances`, and `GET /v3/common/financial-accounts` return their > complete `data` array without cursor parameters or a `pagination` object. Apply the cursor flow on this page to > the paginated lists above. > [!NOTE] > > **What's not in the response.** `total`, `total_count`, and `total_pages` are > intentionally not part of the envelope. Running a `COUNT(*)` on every list > call would defeat the cursor-seek index plan that keeps list endpoints fast at > scale. Use `hasNext` / `hasPrev` to detect whether more pages exist; there is > no total-count or page-number field. ### Decoding cursors **Don't.** Cursors are opaque. Clients should never decode, parse, trim, re-encode, or substitute them. The cursor format is an implementation detail of the server, and OpenFX reserves the right to change it at any time without notice (different encoding, different payload fields, different length). Code that decodes cursors will break the day the encoding changes. The contract is: **the server returns a cursor string; the client passes that same string back verbatim** on the next request via `?startingAfter=` or `?endingBefore=`. Round-trip it as opaque bytes. ### Cursor direction visualized The timeline below shows a list of trades with the newest at the top. Suppose `pagination.nextCursor` from a previous response is currently positioned at trade `C` (highlighted). Each cursor parameter selects a different window: ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% flowchart TB N["⬆ newest"] --> A["A · 10:05"] A --> B["B · 10:04"] B --> C["C · 10:03 ← cursor position"]:::info C --> D["D · 10:02"] D --> E["E · 10:01"] E --> O["⬇ oldest"] classDef info stroke-width:1.5px ``` | Request | Returns | When to use | | - | - | - | | `?endingBefore=` | `[A, B]` (newer than C, newest-first within the window) | "Fetch what's new since I last saw trade C." | | `?startingAfter=` | `[D, E]` (older than C, newest-first within the window) | "Continue paginating into history past trade C." | | `?startingAfter=` | `[]` with `pagination.hasNext: false`, `nextCursor: null` | You've reached the oldest record: nothing older than E. | | `?endingBefore=` | `[]` with `pagination.hasPrev: false`, `prevCursor: null` | You're already at the newest record: nothing newer than A. | The records the cursor refers to are **not** included in the result page. `startingAfter` returns records older than the cursor's position; `endingBefore` returns records newer than it. ## Worked example: fetch all trades (forward iteration) Walk forward (newest → oldest) until `hasNext` is `false`. JWT TTL is 60s; a full back-fill across thousands of records can outlive it, so each of these signs per page rather than capturing one token. See [Rate limiting → Handling rate limits pattern](/v3/rate-limiting#handling-rate-limits-pattern). ```javascript Node theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Walks GET /v3/fx/trades forward (newest -> oldest) until hasNext is // false — the pattern from /v3/pagination#worked-example-fetch-all-trades-forward-iteration. // signRequest is the real helper from /v3/authentication — adjust this path // if you've copied it somewhere else in your own project. const { signRequest } = require("../../authentication/node/sign-request"); // Fetches one page. Takes signRequest and the HTTP call as parameters so // the cursor-walking logic below is testable without a real request. async function fetchPage(signRequest, cursor) { const url = new URL("https://api.openfx.com/v3/fx/trades"); url.searchParams.set("limit", "100"); if (cursor) url.searchParams.set("startingAfter", cursor); // Sign per page: the wall-clock to walk all pages is unbounded by the // JWT's 60s TTL. const { headers } = signRequest({ method: "GET", url: url.toString() }); const res = await fetch(url, { headers }); return res.json(); } // Walks forward until hasNext is false. Takes fetchPage as a parameter so // the cursor-threading and termination logic is testable without a real // request or real credentials. async function* allTrades(signRequest, fetchPageFn = fetchPage) { let cursor = null; while (true) { const page = await fetchPageFn(signRequest, cursor); for (const trade of page.data) yield trade; if (!page.pagination.hasNext) return; cursor = page.pagination.nextCursor; // opaque token, round-trip verbatim } } module.exports = { allTrades, fetchPage }; if (require.main === module) { (async () => { try { for await (const trade of allTrades(signRequest)) { console.log(trade.id, trade.createdAt); } } catch (err) { console.error("Error:", err.message); process.exitCode = 1; } })(); } ``` ```python Python theme={"theme":{"light":"poimandres","dark":"poimandres"}} """Walks GET /v3/fx/trades forward (newest -> oldest) until hasNext is false — the pattern from /v3/pagination#worked-example-fetch-all-trades-forward-iteration.""" import os import sys # sign_request is the real helper from /v3/authentication — adjust this path # if you've copied it somewhere else in your own project. sys.path.insert( 0, os.path.join(os.path.dirname(__file__), "..", "..", "authentication", "python") ) from sign_request import sign_request # noqa: E402 import requests # noqa: E402 def fetch_page(sign_request_fn, cursor): """Fetches one page. Takes sign_request as a parameter so the cursor-walking logic below is testable without a real request.""" params = {"limit": 100} if cursor: params["startingAfter"] = cursor url = "https://api.openfx.com/v3/fx/trades" prepared = requests.Request("GET", url, params=params).prepare() # Sign per page: the wall-clock to walk all pages is unbounded by the # JWT's 60s TTL. headers, _ = sign_request_fn("GET", prepared.url, b"") return requests.get(prepared.url, headers=headers).json() def all_trades(sign_request_fn, fetch_page_fn=fetch_page): """Walks forward until hasNext is false. Takes fetch_page as a parameter so the cursor-threading and termination logic is testable without a real request or real credentials.""" cursor = None while True: page = fetch_page_fn(sign_request_fn, cursor) for trade in page["data"]: yield trade if not page["pagination"]["hasNext"]: return cursor = page["pagination"]["nextCursor"] # opaque token, round-trip verbatim if __name__ == "__main__": for trade in all_trades(sign_request): print(trade["id"], trade["createdAt"]) ``` ```java Java theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Walks GET /v3/fx/trades forward (newest -> oldest) until hasNext is // false — the pattern from // /v3/pagination#worked-example-fetch-all-trades-forward-iteration. import java.net.HttpURLConnection; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.BiFunction; public class AllTrades { // A minimal page shape: just the two fields the walking logic needs. static class Page { final List tradeIds; final boolean hasNext; final String nextCursor; Page(List tradeIds, boolean hasNext, String nextCursor) { this.tradeIds = tradeIds; this.hasNext = hasNext; this.nextCursor = nextCursor; } } // Named Signer, not SignRequest, to avoid colliding with the real // SignRequest class from /v3/authentication, compiled alongside this // file on the classpath. interface Signer { Map signRequest(String method, String url, byte[] body) throws Exception; } // Fetches one page. Takes signer as a parameter so the cursor-walking // logic below is testable without a real request. static Page fetchPage(Signer signer, String cursor) throws Exception { String url = "https://api.openfx.com/v3/fx/trades?limit=100" + (cursor != null ? "&startingAfter=" + cursor : ""); // Sign per page: the wall-clock to walk all pages is unbounded by // the JWT's 60s TTL. Map headers = signer.signRequest("GET", url, new byte[0]); HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection(); conn.setRequestMethod("GET"); for (Map.Entry h : headers.entrySet()) { conn.setRequestProperty(h.getKey(), h.getValue()); } conn.getResponseCode(); // A real implementation would parse the JSON response body here, // using whatever JSON library you're already using. return new Page(List.of(), false, null); } // Walks forward until hasNext is false. Takes fetchPage as a parameter // so the cursor-threading and termination logic is testable without a // real request or real credentials. static List allTrades(Signer signer, BiFunction fetchPageFn) { List ids = new ArrayList<>(); String cursor = null; while (true) { Page page = fetchPageFn.apply(signer, cursor); ids.addAll(page.tradeIds); if (!page.hasNext) return ids; cursor = page.nextCursor; // opaque token, round-trip verbatim } } // Adapts fetchPage (which throws) to the checked-exception-free // BiFunction shape allTrades needs. static Page fetchPageUnchecked(Signer signer, String cursor) { try { return fetchPage(signer, cursor); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) { // SignRequest is the real helper from /v3/authentication, compiled // on the classpath alongside this file — see that page's example. List ids = allTrades(SignRequest::signRequest, AllTrades::fetchPageUnchecked); System.out.println(ids); } } ``` ```cpp C++ theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Walks GET /v3/fx/trades forward (newest -> oldest) until hasNext is // false — the pattern from // /v3/pagination#worked-example-fetch-all-trades-forward-iteration. // Requires OpenSSL and libcurl. #include #include #include #include #include // Matches the definition in ../../authentication/cpp/sign_request.cpp, // compiled together with this file — see that file for the real // implementation of signRequest. struct SignedRequest { std::string authHeader; std::string sigHeader; }; SignedRequest signRequest(const std::string& method, const std::string& urlPath, const std::string& query, const std::string& body); // A minimal page shape: just the two fields the walking logic needs. struct Page { std::vector tradeIds; bool hasNext; std::optional nextCursor; }; using Signer = std::function; using FetchPageFn = std::function&)>; static size_t discard(char*, size_t s, size_t n, void*) { return s * n; } // Fetches one page. Takes signer as a parameter so the cursor-walking // logic below is testable without a real request. Page fetchPage(const Signer& signer, const std::optional& cursor) { std::string query = "limit=100"; if (cursor) query += "&startingAfter=" + *cursor; std::string url = "https://api.openfx.com/v3/fx/trades?" + query; // Sign per page: the wall-clock to walk all pages is unbounded by the // JWT's 60s TTL. SignedRequest req = signer("GET", "/v3/fx/trades", query, ""); CURL* curl = curl_easy_init(); curl_slist* headers = nullptr; headers = curl_slist_append(headers, ("Authorization: " + req.authHeader).c_str()); headers = curl_slist_append(headers, ("X-Request-Signature: " + req.sigHeader).c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, discard); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); // A real implementation would parse the JSON response body here, // using whatever JSON library you're already using. return {{}, false, std::nullopt}; } // Walks forward until hasNext is false. Takes fetchPage as a parameter so // the cursor-threading and termination logic is testable without a real // request or real credentials. std::vector allTrades(const Signer& signer, const FetchPageFn& fetchPageFn) { std::vector ids; std::optional cursor = std::nullopt; while (true) { Page page = fetchPageFn(signer, cursor); for (auto& id : page.tradeIds) ids.push_back(id); if (!page.hasNext) return ids; cursor = page.nextCursor; // opaque token, round-trip verbatim } } #ifndef ALL_TRADES_NO_MAIN #include int main() { try { auto ids = allTrades(signRequest, fetchPage); for (auto& id : ids) std::cout << id << std::endl; return 0; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } #endif ``` ```go Go theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Walks GET /v3/fx/trades forward (newest -> oldest) until hasNext is // false — the pattern from // /v3/pagination#worked-example-fetch-all-trades-forward-iteration. package main import ( "fmt" "net/http" // auth is the real signRequest helper from /v3/authentication — see // go.mod's replace directive if you've copied it somewhere else. auth "openfx-v3-authentication-example" ) // Matches auth.SignRequest's signature, so that function can be passed // directly wherever a SignerFunc is expected. type SignerFunc func(method, url string, body []byte) (*auth.SignedRequest, error) // A minimal page shape: just the two fields the walking logic needs. type Page struct { TradeIDs []string HasNext bool NextCursor *string } // Fetches one page. Takes signer as a parameter so the cursor-walking // logic below is testable without a real request. func fetchPage(signer SignerFunc, cursor *string) (*Page, error) { url := "https://api.openfx.com/v3/fx/trades?limit=100" if cursor != nil { url += "&startingAfter=" + *cursor } // Sign per page: the wall-clock to walk all pages is unbounded by the // JWT's 60s TTL. signed, err := signer("GET", url, nil) if err != nil { return nil, err } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, v := range signed.Headers { req.Header.Set(k, v) } res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() // A real implementation would parse the JSON response body here. return &Page{HasNext: false}, nil } type fetchPageFunc func(signer SignerFunc, cursor *string) (*Page, error) // Walks forward until hasNext is false. Takes fetchPage as a parameter so // the cursor-threading and termination logic is testable without a real // request or real credentials. func allTrades(signer SignerFunc, fetchPageFn fetchPageFunc) ([]string, error) { var ids []string var cursor *string for { page, err := fetchPageFn(signer, cursor) if err != nil { return nil, err } ids = append(ids, page.TradeIDs...) if !page.HasNext { return ids, nil } cursor = page.NextCursor // opaque token, round-trip verbatim } } func main() { ids, err := allTrades(auth.SignRequest, fetchPage) if err != nil { fmt.Println("Error:", err) return } fmt.Println(ids) } ``` ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} #!/usr/bin/env bash # Walks GET /v3/fx/trades forward (newest -> oldest) until hasNext is false # — the pattern from # /v3/pagination#worked-example-fetch-all-trades-forward-iteration. # Illustrative only: cURL can't compute the ES256 request signature itself, # so $OPENFX_JWT/$OPENFX_SIGNATURE below are placeholders — get real values # from signRequest, in any supported language, via /v3/authentication. Sign # per page: the wall-clock to walk all pages is unbounded by the JWT's 60s # TTL. X-App-Mode is hard-coded to SANDBOX below. To target Live, use a Live API # key (mint the JWT from it) and set X-App-Mode to LIVE. set -euo pipefail extract_field() { # $1: JSON, $2: field name echo "$1" | grep -o "\"$2\":\"[^\"]*\"" | head -1 | sed -E "s/.*:\"([^\"]*)\"/\1/" } extract_bool() { # $1: JSON, $2: field name echo "$1" | grep -o "\"$2\":[a-z]*" | head -1 | sed -E "s/.*:([a-z]*)/\1/" } CURSOR="" while true; do URL="https://api.openfx.com/v3/fx/trades?limit=100" if [ -n "$CURSOR" ]; then URL="$URL&startingAfter=$CURSOR" fi export OPENFX_JWT="" export OPENFX_SIGNATURE="" PAGE=$(curl -s "$URL" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: SANDBOX") echo "$PAGE" | grep -o '"id":"[^"]*"' HAS_NEXT=$(extract_bool "$PAGE" "hasNext") if [ "$HAS_NEXT" != "true" ]; then break fi CURSOR=$(extract_field "$PAGE" "nextCursor") # opaque token, round-trip verbatim done ``` ## Worked example: walk backward from a known cursor The mirror image of the forward walk: page from a starting point toward the newest record, stopping when `hasPrev` is `false` (equivalently, when `prevCursor` is `null`). Useful for catch-up loops that recover a gap older than your most recent sync. ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} // `signRequest({ method, url, body })` returns { headers, body } with a freshly minted JWT // AND a freshly computed X-Request-Signature each call. See the Authentication guide. // `startCursor` is a cursor you saved from a previous request. Iteration ends when // prevCursor === null (the head of the list). async function* tradesNewerThan(signRequest, startCursor) { let cursor = startCursor; while (cursor !== null) { const url = new URL("https://api.openfx.com/v3/fx/trades"); url.searchParams.set("limit", "100"); url.searchParams.set("endingBefore", cursor); const signed = signRequest({ method: "GET", url: url.toString(), }); const page = await fetch(url, { headers: signed.headers }).then((r) => r.json(), ); for (const trade of page.data) yield trade; cursor = page.pagination.prevCursor; // opaque; null when we've reached the newest record } } ``` ## Worked example: fetch "what's new since last seen" The typical sync-job pattern: you've persisted the most recent cursor from your last poll; on this poll you want only the new records that have appeared since. ### Get a starting cursor A first run has no saved cursor, and the newest page returns `prevCursor: null`, so there is nothing to start from. Request a single-record page instead and keep its `nextCursor`. A `nextCursor` sits on the last record of its page, so with `limit=1` it sits on the newest record, and `endingBefore` with that cursor returns only records newer than it. The `nextCursor` is `null` when the list holds one record or none (`hasNext` is false), so wait and request again until it returns a cursor. You use the same request on every later poll to refresh your saved cursor (see [Poll for new records](#poll-for-new-records)). ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} // `signRequest({ method, url, body })` returns { headers, body } with a freshly minted JWT // AND a freshly computed X-Request-Signature each call. See the Authentication guide. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function getJson(url) { const signed = signRequest({ method: "GET", url: url.toString() }); return fetch(url, { headers: signed.headers }).then((r) => r.json()); } // Fetch the single newest record and return its nextCursor, or null if there is none yet. async function fetchNewestCursor() { const url = new URL("https://api.openfx.com/v3/fx/trades"); url.searchParams.set("limit", "1"); const page = await getJson(url); return page.pagination.nextCursor; } // First run only: retry with a pause until the list holds a cursor to start from. async function getStartingCursor(maxAttempts = 10, delayMs = 30000) { for (let attempt = 1; attempt <= maxAttempts; attempt++) { const cursor = await fetchNewestCursor(); if (cursor !== null) return cursor; if (attempt < maxAttempts) await sleep(delayMs); } return null; // Still no cursor: try again later. } ``` Take this cursor **before** you load existing history. Records created while the load runs then arrive in your first poll instead of falling between the two. Because a poll can return a record more than once, make your handler idempotent on resource ID. > [!NOTE] > > The starting-cursor request applies to the FX lists (`GET /v3/fx/trades`, > `/deposits`, `/withdrawals`, and `/withdrawal-accounts`). ### Poll for new records A backward page (`endingBefore`) returns `prevCursor` only while more newer records remain (`hasPrev` is true). The page that reaches the newest record returns `prevCursor: null`, so it gives you nothing to save. To move your saved cursor forward, request the newest-record cursor again with the `limit=1` request above. Request that cursor **before** you read the new records, so a record created during the poll arrives in the next poll instead of falling between the two. Then page toward the newest record with `prevCursor` until `hasPrev` is `false`, and save the refreshed cursor. ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Reuses `sleep`, `getJson`, and `fetchNewestCursor` from the previous example. // `signRequest` mints a fresh JWT and X-Request-Signature on every call. If you run this in a // sync loop every N minutes, call it once per poll and sleep between polls. See Rate limiting → // Handling rate limits pattern: https://docs.openfx.com/v3/rate-limiting#handling-rate-limits-pattern // // Returns the cursor to save. Persist it only after `handleRecords` has succeeded for every page. async function pollNewTrades(lastSeenCursor, handleRecords) { // 1. Refresh the saved cursor first. Null means fewer than two records exist: keep the old one. const newestCursor = await fetchNewestCursor(); // 2. Page toward the newest record. let cursor = lastSeenCursor; for (;;) { const url = new URL("https://api.openfx.com/v3/fx/trades"); url.searchParams.set("limit", "25"); url.searchParams.set("endingBefore", cursor); const page = await getJson(url); // page.data holds records newer than the cursor, newest-first within the page. await handleRecords(page.data); if (!page.pagination.hasPrev) break; // Reached the newest record. cursor = page.pagination.prevCursor; } return newestCursor ?? lastSeenCursor; } ``` > [!WARNING] > > For a continuous sync loop, persist the returned cursor **only after you've > successfully handled the records in every page**. If your handler crashes > before the DB write, the next poll re-fetches the same records. That's safe, > because your handler should be idempotent on resource ID. ## Why cursor pagination Page-based pagination (`?page=2&limit=25`) breaks down at scale: * New records appearing during pagination cause records to shift between pages (you see the same trade twice or miss one) * Deep pages get progressively slower (the database has to skip every prior row) * "How many pages total?" requires a separate `COUNT(*)` query Cursors fix all three. The cursor encodes the row's position; the server seeks directly to that position and reads the next page from there. The `pagination` envelope makes the cursor a first-class field of the response, so clients never have to guess where the cursor "is"; the server hands it back to you. ## Common mistakes * **Decoding or parsing the cursor.** Cursors are opaque. Don't decode them, don't try to extract anything from them, don't munge them. Pass the string back exactly as you received it. The format is an implementation detail and will change. * **Picking the wrong cursor for the direction you want.** For "load all" (forward), use `pagination.nextCursor` and pass it as `?startingAfter=`. For "what's new since" (backward), use `pagination.prevCursor` and pass it as `?endingBefore=`. Mixing them sends you in the wrong direction. * **Sorting the `data` array client-side and then deriving a cursor.** The cursor is in the response envelope, not in the array. Read `pagination.nextCursor` / `pagination.prevCursor` directly; sort `data` for display second. * **Re-deriving "is there more?" from the cursor when the boolean is right there.** `pagination.hasNext` and `pagination.hasPrev` are the canonical end-of-list signals: branch on them. (A cursor is `null` whenever its boolean is `false`, but the booleans are the contract.) * **Setting both `startingAfter` and `endingBefore`.** They are mutually exclusive. Pick a direction. * **Treating `limit` as a guarantee.** It's a max. The server may return fewer records. Paginate until `pagination.hasNext` is `false`, not until `data.length < limit`. * **Persisting cursors longer than the resource lives.** Cursors point to a position in the underlying sort. If the record they point to is purged (rare on Trade / Trade-account resources at any meaningful timescale), paginating past it returns the next-newest record. ## Gotchas * **Cursors are stable across requests.** A cursor you persisted yesterday continues to point to the same position in the list today (subject to record retention). * **`limit` is a max, not a guarantee.** The server may return fewer records than requested if filters apply. * **`nextCursor` and `prevCursor` reflect the chosen direction independently.** A page returned via `?startingAfter=` still carries a `prevCursor` you can use to walk back if you need to. The envelope is symmetric: only the request parameter says which direction you're moving. * **Empty page on the boundary.** Calling `?startingAfter=` returns `data: []` with `pagination.hasNext: false` and `pagination.nextCursor: null`, not an error. ## What's next > [card] [Rate limiting](/v3/rate-limiting#handling-rate-limits-pattern) > > The back-off pattern for back-fill loops that hit RATE_LIMIT_EXCEEDED. > [card] [Idempotency](/v3/idempotency) > > Make sync jobs safe across crashes and restarts. > [card] [List trades](/v3/api-reference/trade/list-trades) > > Paginate trades via the canonical list endpoint. > [card] [Retrieve a trade](/v3/api-reference/trade/get-trade) > > Fetch a single record by ID without paging. # Payouts Source: https://docs.openfx.com/v3/payouts The full payout flow: account structure, one-time recipient setup, and the payout state machine from create to settlement. A payout sends money from one of your financial accounts to a recipient's bank account, in the same currency or with a conversion. This guide covers the whole flow: the resources involved, the one-time recipient setup, and the payout itself. ## Account structure A payout involves three resources: * **`FinancialAccount`** is yours: the balance the payout is funded from. * **`Account`** identifies the recipient and holds their capabilities. You create it. * **`PayoutAddress`** is the recipient's bank account, where the money lands. You create this too. A payout debits `financialAccountId` and credits `receiver.payoutAddressId`. You don't name the recipient's account separately, because the address already belongs to it. For identity, roles, and archiving, see [Account model](/v3/account-model). You can omit `financialAccountId` when requesting a payout quote or creating an INLINE payout. If you provide it, use a valid `finacc_` id. Quote and payout responses always include the financial account used. A FROM_QUOTE payout uses the financial account from its quote. ## Endpoints | Path | Description | | - | - | | [`POST /v3/common/accounts`](/v3/api-reference/payments/accounts/create-account) | Create an account for a recipient or a sender, with the capabilities it needs | | [`GET /v3/common/financial-accounts`](/v3/api-reference/payments/accounts/list-financial-accounts) | List which of your balances can fund a given payout | | [`POST /v3/payments/payout-addresses`](/v3/api-reference/payments/addresses/create-payout-address) | Register where the money lands | | [`POST /v3/payments/payout-quotes`](/v3/api-reference/payments/payouts/create-payout-quote) | Price a payout without moving funds | | [`POST /v3/payments/payouts`](/v3/api-reference/payments/payouts/create-payout) | Create a payout, inline-priced or from a quote | | [`POST /v3/payments/payouts/{payoutId}/confirm`](/v3/api-reference/payments/payouts/confirm-payout) | Accept the priced payout | | [`POST /v3/payments/payouts/{payoutId}/cancel`](/v3/api-reference/payments/payouts/cancel-payout) | Decline a payout before acceptance | | [`GET /v3/payments/payouts/{payoutId}`](/v3/api-reference/payments/payouts/get-payout) | Look up a single payout | Every `POST` takes an `Idempotency-Key` header, and a request without one fails with `428` IDEMPOTENCY_KEY_MISSING. The samples on this page send a fresh UUID. See [Idempotency](/v3/idempotency#payments-endpoints). ## Supported payout currencies Payouts settle in the currencies below. Each is enabled per organization: until yours is, listing the financial accounts that can fund it fails with `403` PAYOUT_CURRENCY_NOT_ENABLED, and a quote or payout fails with `409` PAYOUT_NOT_ENABLED, or with `409` CAPABILITY_NOT_ACTIVE while the capability never activates. [Capabilities](/v3/capabilities#the-capability-catalog) lists the capability each one needs. | Currency | `routingFamily` | Rail | `sender` | `purpose` | Limits | | - | - | - | - | - | - | | EUR | SEPA | SEPA | Refused | Refused | — | | EUR | SWIFT | SWIFT | Refused | Refused | — | | MXN | MX_LOCAL | SPEI | Refused | Refused | `receiverMemo`: 40 characters | | COP | CO_LOCAL | CO_ACH | Refused | Refused | `receiverMemo`: 40 characters | | COP | CO_BREB | BREB | Refused | Refused | `receiverMemo`: 40 characters. Payout cap of about COP 12,110,000 | | AED | AE_LOCAL | AE_LOCAL | Refused | Required, and never INVESTMENTS or OTHER | `receiverMemo`: 100 characters. Per-payout limits | | GBP | GB_LOCAL | FPS | Refused | Refused | `receiverMemo`: 18 characters. Payout cap of GBP 1,000,000 | A dash means this page lists no corridor-specific limit. [EUR](/v3/eur-payout-integration), [MXN](/v3/mxn-payout-integration), [COP](/v3/cop-payout-integration), [AED](/v3/aed-payout-integration), and [GBP](/v3/gbp-payout-integration) have their own guides. These rules apply to every corridor: * **`purpose`.** A quote carries no `purpose`, so send it when you create the payout. Each corridor that requires one accepts its own values: the [AED guide](/v3/aed-payout-integration) lists the AED ones. A missing or refused `purpose` fails with `422` PURPOSE_INVALID. * **`receiverMemo`.** The limit counts letters, digits, and spaces. A memo that is too long or holds any other character fails with `400` RECEIVER_MEMO_INVALID. OpenFX never truncates it. * **Amount limits.** A `receiveAmount` outside the limit is refused when the payout is priced, with `422` AMOUNT_OUT_OF_RANGE. `error.details` carries the exact bound. * **Funding currency.** An AED payout is funded only from a USDC, USDT, EURC, or AED balance, and a GBP payout only from a GBP, USD, USDC, USDT, or EURC balance. Any other send currency fails with `422` QUOTE_SEND_CURRENCY_UNAVAILABLE. ## Set up the recipient You do this once per recipient. Before you can pay them, three things must be ACTIVE: the account, the capability the payout needs, and the payout address. [Account model](/v3/account-model#the-shared-state-machine) describes how each status changes. **1. Create an account for your recipient** Create an INDIVIDUAL or ORGANIZATION account with its `identity` and the `capabilities` it needs, by id. Include the identity fields each capability requires in the same request. [Capabilities](/v3/capabilities#identity-requirements) lists them. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/common/accounts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "capabilities": ["cap_Ce3AJmAmDGcJgTmTqgFVZ"], "identity": { "identityType": "ORGANIZATION", "organization": { "legalName": "Novalia Handels GmbH", "registeredAddress": { "country": "DE" } } } }' ``` The response wraps the `Account` in `data`. **Check it before you wait for webhooks**: it shows the account's `status` and each capability's, and anything already resolved won't send a webhook you need to wait for. ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "object": "account", "id": "acc_BMY3UenpGBn8ZQ8hio4BgE", "status": "ACTIVE", "capabilities": [ { "object": "accountCapability", "id": "cap_Ce3AJmAmDGcJgTmTqgFVZ", "status": "PENDING", "hasActiveAddresses": false, "details": { "grants": ["RECEIVE_PAYOUTS"], "currencies": ["EUR"] } } ], "archivedAt": null, "createdAt": "2026-06-04T10:30:00.000Z", "updatedAt": "2026-06-04T10:30:00.000Z" } ``` If the identity is missing fields a capability needs, the request fails with `422` IDENTITY_REQUIREMENT_UNMET and `error.details.issues` lists each missing field. Requesting the same capability twice fails with `422` CAPABILITY_DUPLICATE. Requesting one that isn't offered to the account's `identityType`, or that has been retired, fails with `422` CAPABILITY_NOT_REQUESTABLE, and `error.details.notRequestable` names each. **2. Wait for what came back PENDING** The account and its capabilities settle separately, and a payout needs both ACTIVE. The account's own status is OpenFX's review of the recipient, so it can be ACTIVE while a capability is still PENDING. A capability usually settles within a minute, though that isn't guaranteed. Subscribe to these webhooks before you create accounts, instead of polling. | Webhook | Fires when | | - | - | | [`common.account.capability_activated`](/v3/webhooks/payments/accounts-webhooks/account-capability-activated) | The capability is ACTIVE and can be used | | [`common.account.capability_rejected`](/v3/webhooks/payments/accounts-webhooks/account-capability-rejected) | The capability was declined; the account's own status doesn't change | | [`common.account.capability_requires_information`](/v3/webhooks/payments/accounts-webhooks/account-capability-requires-information) | OpenFX needs more information and asks for it through your usual support channel | **3. Register the payout address** Register the recipient's bank account against their `accountId`. `routingFamily` decides which fields you send: | `routingFamily` | Fields | | - | - | | SEPA | `accountNumber` (an IBAN) | | SWIFT | `accountNumber`, `bic`, and `accountHolderAddress` | | MX_LOCAL | `accountNumber` (a CLABE) | | CO_LOCAL | `bankCode`, `accountNumber`, and `bankAccountType` | | CO_BREB | `brebKey` | | AE_LOCAL | `accountNumber` (a UAE IBAN) | | GB_LOCAL | `sortCode` and `accountNumber` | The account must already hold a capability that can receive at this address. It doesn't need to be ACTIVE yet, but if there's none at all the request fails with `409` ADDRESS_SERVES_NO_CAPABILITY. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payout-addresses \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "payoutAddressType": "BANK_ACCOUNT", "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", "bankAccount": { "routingFamily": "SEPA", "accountNumber": "DE89370400440532013000" } }' ``` The response wraps the `PayoutAddress` in `data`. It's PENDING, or already ACTIVE if every check finished during the call: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "object": "payoutAddress", "id": "pytadd_PbDQ126YUAbkNrNX6XbGL", "payoutAddressType": "BANK_ACCOUNT", "accountId": "acc_BMY3UenpGBn8ZQ8hio4BgE", "bankAccount": { "routingFamily": "SEPA", "accountHolderName": "Novalia Handels GmbH", "accountNumber": "DE89370400440532013000", "country": "DE" }, "supportedCurrencies": ["EUR"], "supportedRails": ["SEPA"], "status": "PENDING", "verifications": [ { "kind": "NAME_MATCH", "mode": "SEPA_VOP", "result": "PENDING", "providedName": "Novalia Handels GmbH", "registeredName": null, "createdAt": "2026-06-04T10:30:00.000Z", "verifiedAt": null, "expiresAt": null } ], "archivedAt": null, "createdAt": "2026-06-04T10:30:00.000Z", "updatedAt": "2026-06-04T10:30:00.000Z" } ``` **4. Wait for the address to activate** Skip this if the create response already showed the outcome. `status` reflects every check on the address, including some that `verifications[]` doesn't list, so an address can stay PENDING after all its listed verifications have resolved. Checks also continue after activation, so an ACTIVE address can still change status later. | Webhook | Fires when | | - | - | | [`payments.payout_address.activated`](/v3/webhooks/payments/addresses-webhooks/payout-address-activated) | Every check passed; you can now pay to the address | | [`payments.payout_address.rejected`](/v3/webhooks/payments/addresses-webhooks/payout-address-rejected) | A check failed. Create a new address to replace it | | [`payments.payout_address.requires_information`](/v3/webhooks/payments/addresses-webhooks/payout-address-requires-information) | OpenFX needs more information. Like PENDING, this blocks payouts | ## Send the payout Once the account, capability, and address are all ACTIVE, you can send payouts. A payout's `status` shows how far the money has got. Before your account is debited: ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% stateDiagram-v2 direction TB [*] --> FAILED: created, insufficient balance [*] --> REQUIRES_CONFIRMATION: created, priced REQUIRES_CONFIRMATION --> FAILED: funding failed REQUIRES_CONFIRMATION --> CANCELLED: cancelled REQUIRES_CONFIRMATION --> EXPIRED: quote lapsed REQUIRES_CONFIRMATION --> ACCEPTED: confirmed ACCEPTED --> FAILED: settlement failed ACCEPTED --> PROCESSING: trade settled, debited classDef ok stroke-width:1px classDef bad stroke-width:1px classDef pending stroke-width:1px classDef hold stroke-width:1px classDef returned stroke-width:1px classDef neutral stroke-width:1px class PROCESSING pending class REQUIRES_CONFIRMATION neutral class ACCEPTED ok class FAILED,CANCELLED bad class EXPIRED hold ``` After the debit, PROCESSING continues: ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% stateDiagram-v2 direction TB PROCESSING --> PROCESSED: rail sent the credit PROCESSING --> IN_REVIEW: compliance hold PROCESSING --> RETURNED: rail failure IN_REVIEW --> PROCESSING: review cleared IN_REVIEW --> RETURNED: review rejected PROCESSED --> RETURNED: clawback classDef ok stroke-width:1px classDef bad stroke-width:1px classDef pending stroke-width:1px classDef hold stroke-width:1px classDef returned stroke-width:1px classDef neutral stroke-width:1px class PROCESSING pending class IN_REVIEW hold class PROCESSED ok class RETURNED returned ``` | Status | Meaning | | - | - | | REQUIRES_CONFIRMATION | Created and priced. Waiting for you to confirm or cancel | | ACCEPTED | You confirmed. Funds are not debited yet | | PROCESSING | Funds are debited and the payment is on its way | | IN_REVIEW | A compliance or partner check paused the payout. Funds stay debited | | PROCESSED | The payment network confirmed it sent the money. The payment can still be returned | | RETURNED | The payment failed on the network, a review rejected it, or it was clawed back after settling | | FAILED | The payout failed before any money was sent | | CANCELLED | You cancelled it before confirming | | EXPIRED | The quote lapsed before you confirmed | A payout ends in CANCELLED, EXPIRED, FAILED, PROCESSED, or RETURNED. **1. (Optional) Choose the financial account** List the balances that can fund a payout in a given `receiveCurrency`. Skip this if you already know the `finacc_` id or aren't specifying a financial account. An empty list means you're enabled for the currency but hold no balance that can fund it. A `403` PAYOUT_CURRENCY_NOT_ENABLED means you're not enabled for that currency at all, and a `404` FINANCIAL_ACCOUNT_NOT_FOUND means your organization holds no financial account. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl "https://api.openfx.com/v3/common/financial-accounts?receiveCurrency=EUR" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" ``` **2. Create the payout** With [`type: "INLINE"`](/v3/api-reference/payments/payouts/create-payout), one request prices and creates the payout. Send the `pytadd_` to credit, either `sendAmount` or `receiveAmount` (not both), the `receiveCurrency`, a `sender` if the currency requires one, and a `purpose` if the currency requires one. Optionally, include the `finacc_` to debit, as this example does. [Supported payout currencies](#supported-payout-currencies) lists which. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payouts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "type": "INLINE", "financialAccountId": "finacc_AmKC5dMVXUbiAW8VzKBfqz", "receiver": { "payoutAddressId": "pytadd_PbDQ126YUAbkNrNX6XbGL" }, "receiveAmount": "1000.00", "receiveCurrency": "EUR" }' ``` This example funds a EUR payout from a USD balance, which is converted at the quoted rate. It names no `sender`, because a EUR payout refuses one. The payout starts in REQUIRES_CONFIRMATION, and `confirmations[]` lists what you need to accept. The price holds for `quoteForSeconds` (60 seconds unless you ask for longer). If you confirm after `fxRates.expiresAt`, the payout moves to EXPIRED. **You can also get the price first.** [Create a payout quote](/v3/api-reference/payments/payouts/create-payout-quote) moves no money and returns a `pytqte_` id, with the rate locked until `fxRates.expiresAt`. Then create the payout with `type: "FROM_QUOTE"` and that `quoteId`. Use this when someone needs to see the price before the payout exists, for example in an approval step. If a required capability is missing or not ACTIVE, you get `409` CAPABILITY_NOT_ACTIVE. If the financial account you name can't fund a payout in this `receiveCurrency`, you get `409` QUOTE_FUNDING_ACCOUNT_UNAVAILABLE. If it can't cover the payout, you get `409` INSUFFICIENT_FUNDS. If the shortfall shows up a moment later, the payout is still created, but it goes straight to FAILED. **3. Read the pricing, then confirm or cancel** Check `fxRates`, `fees`, and `confirmations[]` in the create response. Which confirmations appear depends on the payout. [Confirm the payout](/v3/api-reference/payments/payouts/confirm-payout) to accept every entry in `confirmations[]` at once and move it to ACCEPTED. You can't accept entries one at a time. To decline, [cancel the payout](/v3/api-reference/payments/payouts/cancel-payout). You can only cancel before confirming, so no money has moved. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/payments/payouts/pyt_9P3Gs3GSn4hMdHQ22Evi5f/confirm \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" ``` If the payout is no longer waiting for confirmation (it expired, or was already confirmed or cancelled), you get `409` PAYOUT_CONFIRMATION_NOT_ALLOWED or `409` PAYOUT_CANCELLATION_NOT_ALLOWED. After ACCEPTED, OpenFX handles the rest. Each status change above has a webhook event: see [Payout webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created). For statuses with more than one origin, `data.previousStatus` tells you where the payout came from. ## Trace a payout with the receiving bank `settlementTraceId` carries the reference the receiving side uses for the payment. Its `status` starts PENDING and moves to AVAILABLE, or to UNSUPPORTED where the rail issues no reference. It runs on its own clock, so it can still read PENDING after the payout reaches PROCESSED. When it is AVAILABLE, `key` names the kind of reference and `value` holds it. The rail decides the `key`: | Rail | `key` | Reference | | - | - | - | | SEPA | END_TO_END_IDENTIFIER | The scheme's end-to-end identifier | | SWIFT | UNIQUE_END_TO_END_TRANSACTION_REFERENCE | The UETR, which follows the payment through every bank | | SPEI | TRACKING_KEY | The clave de rastreo | | AE_LOCAL | None | `status` reads UNSUPPORTED | | FPS | None | `status` reads UNSUPPORTED | ## Verifications and checks The recipient is checked in two places, and each check answers a different question. **On the payout address, at setup.** A name match runs when you create the address, wherever the payment scheme offers one, and `verifications[]` shows its latest result. An address that isn't ACTIVE can't receive payouts. **On the payout, before any money moves.** Each entry in `confirmations[]` is something you accept by confirming. A QUOTE entry covers the rate and fees. An `AccountHolderNameConfirmation` shows the name check. On a SEPA or GBP payout, the check runs again **unless the address's latest result is MATCH**, which the payout then reuses. On other rails with a name check, the payout reuses the address's result. A reused result keeps its original `verifiedAt`, so it can predate the payout. `NameMatchResult` lists every possible outcome. NO_MATCH rejects a payout *address*, and a check at payout that returns it refuses the payout with `409` ACCOUNT_HOLDER_MISMATCH. BANK_ACCOUNT_NOT_FOUND rejects the address too: no usable account exists at the details you sent, so the fix is a new address with corrected account details, not a corrected name. A check at payout that returns it refuses the payout with `409` PAYOUT_ADDRESS_BANK_ACCOUNT_NOT_FOUND. Either refusal records the payout FAILED with no `confirmations[]`, returns no `pyt_` id, and spends the quote: retrying that quote fails with `409` QUOTE_ALREADY_CONSUMED, so quote again. Any other result is your call: confirming accepts the name as it is, and cancelling declines it. A check that gets no answer returns UNAVAILABLE. A check that has not returned yet is PENDING, which refuses the payout with `409` ACCOUNT_HOLDER_MISMATCH on SEPA and on GBP. ACCOUNT_HOLDER_MISMATCH can also arrive after you confirm. The receiving bank runs its own check at settlement, whatever you accepted. If the name doesn't match, the payout moves to FAILED with that code on `data.failure`. ## Common mistakes * **Paying before the capability is ACTIVE.** You can create an address while the capability is PENDING, but the payout itself needs it ACTIVE. Otherwise it fails with `409` CAPABILITY_NOT_ACTIVE. * **Confirming after the price expires.** `fxRates.expiresAt` is the deadline. After it, confirming fails with `409` QUOTE_EXPIRED, or with `409` PAYOUT_CONFIRMATION_NOT_ALLOWED once the payout has moved to EXPIRED. * **Treating PROCESSED as final.** The payment can still be returned, which you'll see as `payments.payout.returned` with `data.previousStatus: "PROCESSED"`. * **Expecting to confirm past a NO_MATCH.** A name check at payout that returns it refuses the payout with `409` ACCOUNT_HOLDER_MISMATCH. Create a new payout address in the name the account is held in. * **Ignoring `data.previousStatus` on `payments.payout.processing`, `.failed`, and `.returned`.** Each of these events can fire for more than one reason. Check `previousStatus` to know which. ## Archiving does not stop a payout in flight Archiving an account or payout address only blocks *new* payouts to it. A payout that's already ACCEPTED, PROCESSING, or IN_REVIEW carries on to the end. Archiving doesn't cancel or redirect it. ## What's next > [card] [Payouts in EUR](/v3/eur-payout-integration) > > Paying euro accounts over SEPA or SWIFT. > [card] [Payouts to Mexico](/v3/mxn-payout-integration) > > Paying Mexican bank accounts over SPEI. > [card] [Payouts to Colombia](/v3/cop-payout-integration) > > Paying Colombian bank accounts and Bre-B keys. > [card] [Payouts to the UAE](/v3/aed-payout-integration) > > Paying UAE bank accounts by IBAN. > [card] [Payouts to the UK](/v3/gbp-payout-integration) > > Paying UK bank accounts over Faster Payments. > [card] [Account model](/v3/account-model) > > How accounts, capabilities, and addresses change status. > [card] [Payment Webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Every payout, account, and address event. # Quickstart Source: https://docs.openfx.com/v3/quickstart Get from zero to your first executed trade in under 5 minutes. This page takes you from an empty terminal to an executed v3 trade. By the end you'll have minted a JWT, listed available currency pairs, selected USD → USDC, quoted a 1000 USD conversion, executed it, and seen the resulting USDC reflected in your balances. Every example chains into the next: the IDs returned in one step are the inputs to the next. ## Before you start * An OpenFX API key: generate one from the [dashboard](https://app.openfx.com/api-keys) and download the JSON file (contains `kid` and `privateKey`). See [Authentication](/v3/authentication) for the file format and how to sign tokens. * Node.js, Python, or any HTTP client (cURL works fine) * About 5 minutes > [!TIP] > > **Coming from v2?** The high-level flow is unchanged: pairs → quote → trade → > balances. The wire contract changes materially: URL prefix, response envelope, > amount types, quote request shape, pagination, and error handling. ## 1. Mint a JWT bearer token Every API call to `/v3/*` uses a fresh JWT and `X-Request-Signature`: an `Authorization: Bearer ` header **and** an ES256 signature over the request. JWTs are **ES256-signed, single-use, and expire 60 seconds after issuance**. Mint both together, per request, with the `signRequest` helper. See [Mint a JWT and sign the request](/v3/authentication#mint-a-jwt-and-sign-the-request) for the implementation in Node, Python, Java, C++, and Go. > [!WARNING] > > **The cURL snippets below show the wire shape, not a request the API will > accept as-is.** Every request needs a fresh JWT in `Authorization` and a > matching `X-Request-Signature`, and cURL alone can't compute an ES256 > signature. Copy-pasting one verbatim returns `401` > AUTH_TOKEN_INVALID. For a request the API > accepts, call `signRequest` from > [Authentication](/v3/authentication#mint-a-jwt-and-sign-the-request), or run > [Putting it together](#putting-it-together) below. ```bash theme={"theme":{"light":"poimandres","dark":"poimandres"}} # Illustrative only; see the warning above. In real code, call signRequest # per request instead of exporting one token and signature for the whole session. export OPENFX_JWT="" export OPENFX_SIGNATURE="" ``` > [!TIP] > > JWTs are single-use (server-enforced nonce uniqueness) and have a 60-second > TTL. Copy-pasting one twice is rejected with `401` AUTH_TOKEN_INVALID > (`details.reason: REPLAYED`). Re-mint between every example below. See > [Authentication](/v3/authentication) for the helper and signing flow. > [!TIP] > > **The `$OPENFX_JWT` and `$OPENFX_SIGNATURE` env vars below are reused across steps for readability. Production code mints and signs per request.** The linear walkthrough (pairs → quote → trade → balances) reads more naturally with one exported token, but any sequence that includes user think-time, retries, polling, or pagination must mint a fresh JWT *and* a fresh `X-Request-Signature` per HTTP call. The canonical pattern is in [Rate limiting → Handling rate limits pattern](/v3/rate-limiting#handling-rate-limits-pattern); every retry/poll/pagination sample elsewhere in v3 takes a `signRequest({ method, url, body }) => { headers, body }` parameter rather than a captured token. [Putting it together](#putting-it-together) below shows the real per-call version, in every supported language. ## 2. List available currency pairs Call [`GET /v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs) (authenticated, no body) to list the currency pairs available to your organization. This also confirms that your key, signing, and network connection work. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl https://api.openfx.com/v3/fx/pairs \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -D headers.txt # `headers.txt` now contains X-Trace-Id and the RateLimit-* headers. ``` A successful response contains the complete bounded list of `Pair` resources nested under `data.pairs`. The actual response wraps the object below in `data`; the `PairList` shape itself is: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "pairs": [ { "buyCurrency": "USDC", "sellCurrency": "USD", "minTradeAmount": "100", "maxTradeAmount": "100000000" }, { "buyCurrency": "USD", "sellCurrency": "USDC", "minTradeAmount": "100", "maxTradeAmount": "10000000" } ] } ``` > [!TIP] > > Every response carries `X-Trace-Id` and `RateLimit-*` in the headers. Capture > `X-Trace-Id` on every response (success too) so support can reconstruct the > request later. See [Metadata & tracing](/v3/metadata-and-tracing). ## 3. Select a currency pair Select an entry from `data.pairs` that matches the direction you want to trade. `sellCurrency` is the currency you spend; `buyCurrency` is the currency you receive. Each pair is listed in both directions, with limits denominated in that entry's `sellCurrency`. For this walkthrough, use the entry with `sellCurrency: "USD"` and `buyCurrency: "USDC"`. The next step sells `"1000.00"` USD, which is within the example entry's `minTradeAmount` and `maxTradeAmount`. Check the limits in your own response before requesting a quote. The [complete examples below](#putting-it-together) follow the same flow: list pairs, then quote 1000 USD → USDC, execute the trade, and read balances. If USD → USDC isn't in your response, select an available pair and use its currencies in the quote instead. > [!TIP] > > **Want steps for your corridor?** Open [Blueprints](/v3/blueprints?from=USD\&to=USDC\&funding=exposure), > select the currencies you're converting, and choose your funding and settlement > options. Blueprints populates the integration steps and request and response > examples for that corridor. Use your API's pair list to confirm availability > and trade-size limits. ## 4. Quote a trade `POST /v3/fx/quotes` returns a price guaranteed until `expiresAt` (default 3 seconds). Quotes are a separate step from execution so you can show the user a rate, get confirmation, and execute without surprising them on the price. Give the request its own `Idempotency-Key` header: a client-generated string that lets you safely retry the call. Generate one UUID v4 per logical operation. See [Idempotency](/v3/idempotency). Use the `buyCurrency` and `sellCurrency` from the pair you selected in step 3. Pick which side of the trade you want to anchor: supply **`sellAmount`** if you want to spend an exact amount, or **`buyAmount`** if you need to receive an exact amount. Supply exactly one. The server computes the other side at the quoted rate. This example anchors the sell side (1000 USD out). ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/fx/quotes \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "buyCurrency": "USDC", "sellCurrency": "USD", "sellAmount": "1000.00" }' ``` A successful response wraps the `Quote` in `data`. The `Quote` resource itself is: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "object": "quote", "id": "qte_3FfGK34vwMvVFDedyb2nkf", "buyCurrency": "USDC", "sellCurrency": "USD", "sellAmount": "1000.00", "quoteAmount": "999.50", "rate": "0.999500000000", "settlementWindow": "T0", "expiresAt": "2026-04-28T10:00:03.000Z", "createdAt": "2026-04-28T10:00:00.000Z" } ``` Keep the `id`; you'll pass it to the next step. `sellAmount` is exact (\$1000.00) and `quoteAmount` is the server-computed counter-leg. Notice both amounts are **strings**, not JSON numbers; see [Amounts](/v3/amounts). ## 5. Execute the trade Submit the quote ID to `POST /v3/fx/trades` before `expiresAt` (about 3 seconds from the quote's `createdAt`); after that, the call returns `409` QUOTE_EXPIRED and you go back to step 4 for a fresh price. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/fx/trades \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "quoteId": "qte_3FfGK34vwMvVFDedyb2nkf" }' ``` A successful response wraps the `Trade` in `data`, with `status: "EXECUTED"`. The `Trade` resource itself is: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "object": "trade", "id": "tde_5W7guYdHT24JFnRQrZN9y8", "quoteId": "qte_3FfGK34vwMvVFDedyb2nkf", "status": "EXECUTED", "buyCurrency": "USDC", "sellCurrency": "USD", "sellAmount": "1000", "executedAmount": "999.50", "rate": "0.999500000000", "clientReferenceId": null, "createdAt": "2026-04-28T10:00:00.000Z", "settlementWindow": "T0", "settlementStartTime": null } ``` > [!WARNING] > > **One `Idempotency-Key` per logical operation.** The quote and the trade are > two operations, so generate two keys. Reusing a key for a different trade (same > endpoint, different body) returns `422` IDEMPOTENCY_MISMATCH. > Keys are scoped per endpoint, so reusing one across the quote and the trade is > safe but confusing. See [Idempotency](/v3/idempotency). ## 6. Check your balance Read your balances to confirm the USDC purchased by the trade: `GET /v3/fx/balances` returns a `Balance` per currency, plus an `aggregate` block with your org-wide net equity. The USDC you just bought should show up in `withdrawableBalance`. Trade execution doesn't return balances; fetch them separately. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl https://api.openfx.com/v3/fx/balances \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" ``` The response wraps this in `data`; the `BalancesData` object itself is: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "aggregate": { "currency": "USD", "withdrawableBalance": "4999.50" }, "balances": [ { "currency": "USD", "withdrawableBalance": "4000.00", "totalBalance": "4150.00" }, { "currency": "USDC", "withdrawableBalance": "999.500000", "totalBalance": "999.500000" } ] } ``` Assuming a starting USD balance of `5150.00`, the trade above debited `1000.00` USD and credited `999.50` USDC, leaving `4150.00` USD total. In this example, `aggregate.withdrawableBalance` is the sum of the two `withdrawableBalance` rows (`4000.00` + `999.50`), with USDC counted at 1 USD. Your own balances will differ. That's the full round-trip: pairs → quote → trade → balances. The same shape and headers apply to every other v3 endpoint. ## Putting it together The complete round-trip below, real `signRequest` and all, mints a fresh JWT and signature per call with no reused `jwt` symbol: ```javascript Node theme={"theme":{"light":"poimandres","dark":"poimandres"}} // The full quickstart round-trip: pairs -> quote -> trade -> balances — the // pattern from /v3/quickstart. signRequest is the real helper from // /v3/authentication — adjust this path if you've copied it somewhere else. const { randomUUID } = require("node:crypto"); const { signRequest } = require("../../authentication/node/sign-request"); const BASE_URL = "https://api.openfx.com/v3/fx"; // Builds the POST /v3/fx/quotes body. Supply exactly one of sellAmount or // buyAmount to anchor that side. Kept separate from the network call so // it's testable without a real request. function buildQuoteBody({ buyCurrency, sellCurrency, sellAmount, buyAmount }) { const body = { buyCurrency, sellCurrency }; if (sellAmount !== undefined) body.sellAmount = sellAmount; if (buyAmount !== undefined) body.buyAmount = buyAmount; return body; } // Builds the POST /v3/fx/trades body. Kept separate from the network call // so it's testable without a real request. function buildTradeBody(quoteId) { return { quoteId }; } async function signedFetch(method, url, { idempotencyKey, body } = {}) { const bodyStr = body ? JSON.stringify(body) : ""; const { headers } = signRequest({ method, url, body: bodyStr }); if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey; const res = await fetch(url, { method, headers, body: body ? bodyStr : undefined, }); const json = await res.json(); return { res, data: json.data }; } async function listPairs() { const { data } = await signedFetch("GET", `${BASE_URL}/pairs`); return data.pairs; } // A new Idempotency-Key per logical operation. Reusing one for a different // trade returns 422 IDEMPOTENCY_MISMATCH. async function quote(params) { const { data } = await signedFetch("POST", `${BASE_URL}/quotes`, { idempotencyKey: randomUUID(), body: buildQuoteBody(params), }); return data; } async function executeTrade(quoteId) { const { data } = await signedFetch("POST", `${BASE_URL}/trades`, { idempotencyKey: randomUUID(), body: buildTradeBody(quoteId), }); return data; } async function getBalances() { const { data } = await signedFetch("GET", `${BASE_URL}/balances`); return data; } async function quickstart() { const pairs = await listPairs(); console.log({ step: "pairs", count: pairs.length }); const quoted = await quote({ buyCurrency: "USDC", sellCurrency: "USD", sellAmount: "1000.00", }); console.log({ step: "quote", quoteId: quoted.id }); const trade = await executeTrade(quoted.id); console.log({ step: "trade", tradeId: trade.id, status: trade.status }); const balances = await getBalances(); console.log({ step: "balances", balances }); } module.exports = { buildQuoteBody, buildTradeBody, listPairs, quote, executeTrade, getBalances, quickstart, }; if (require.main === module) { quickstart().catch((err) => { console.error("Error:", err.message); process.exitCode = 1; }); } ``` ```python Python theme={"theme":{"light":"poimandres","dark":"poimandres"}} """The full quickstart round-trip: pairs -> quote -> trade -> balances — the pattern from /v3/quickstart.""" import json import os import sys import uuid # sign_request is the real helper from /v3/authentication — adjust this path # if you've copied it somewhere else in your own project. sys.path.insert( 0, os.path.join(os.path.dirname(__file__), "..", "..", "authentication", "python") ) from sign_request import sign_request # noqa: E402 import requests # noqa: E402 BASE_URL = "https://api.openfx.com/v3/fx" def build_quote_body(buy_currency, sell_currency, sell_amount=None, buy_amount=None): """Builds the POST /v3/fx/quotes body. Supply exactly one of sell_amount or buy_amount to anchor that side. Kept separate from the network call so it's testable without a real request.""" body = {"buyCurrency": buy_currency, "sellCurrency": sell_currency} if sell_amount is not None: body["sellAmount"] = sell_amount if buy_amount is not None: body["buyAmount"] = buy_amount return body def build_trade_body(quote_id): """Builds the POST /v3/fx/trades body. Kept separate from the network call so it's testable without a real request.""" return {"quoteId": quote_id} def signed_request(method, url, idempotency_key=None, body=None): body_bytes = json.dumps(body).encode("utf-8") if body is not None else b"" headers, _ = sign_request(method, url, body_bytes) if idempotency_key: headers["Idempotency-Key"] = idempotency_key res = requests.request(method, url, headers=headers, data=body_bytes if body else None) return res.json()["data"] def list_pairs(): return signed_request("GET", f"{BASE_URL}/pairs")["pairs"] def quote(buy_currency, sell_currency, sell_amount=None, buy_amount=None): # A new Idempotency-Key per logical operation. Reusing one for a # different trade returns 422 IDEMPOTENCY_MISMATCH. return signed_request( "POST", f"{BASE_URL}/quotes", idempotency_key=str(uuid.uuid4()), body=build_quote_body(buy_currency, sell_currency, sell_amount, buy_amount), ) def execute_trade(quote_id): return signed_request( "POST", f"{BASE_URL}/trades", idempotency_key=str(uuid.uuid4()), body=build_trade_body(quote_id), ) def get_balances(): return signed_request("GET", f"{BASE_URL}/balances") def quickstart(): pairs = list_pairs() print({"step": "pairs", "count": len(pairs)}) quoted = quote("USDC", "USD", sell_amount="1000.00") print({"step": "quote", "quoteId": quoted["id"]}) trade = execute_trade(quoted["id"]) print({"step": "trade", "tradeId": trade["id"], "status": trade["status"]}) balances = get_balances() print({"step": "balances", "balances": balances}) if __name__ == "__main__": quickstart() ``` ```java Java theme={"theme":{"light":"poimandres","dark":"poimandres"}} // The full quickstart round-trip: pairs -> quote -> trade -> balances — the // pattern from /v3/quickstart. Uses only the built-in JDK APIs — no // external dependency, so JSON handling below is intentionally minimal // (a flat object serializer and single-field extractors), not a general // JSON parser. import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Quickstart { static final String BASE_URL = "https://api.openfx.com/v3/fx"; // Builds the POST /v3/fx/quotes body. Supply exactly one of sellAmount // or buyAmount to anchor that side. Kept separate from the network call // so it's testable without a real request. static Map buildQuoteBody(String buyCurrency, String sellCurrency, String sellAmount, String buyAmount) { Map body = new LinkedHashMap<>(); body.put("buyCurrency", buyCurrency); body.put("sellCurrency", sellCurrency); if (sellAmount != null) body.put("sellAmount", sellAmount); if (buyAmount != null) body.put("buyAmount", buyAmount); return body; } // Builds the POST /v3/fx/trades body. Kept separate from the network // call so it's testable without a real request. static Map buildTradeBody(String quoteId) { Map body = new LinkedHashMap<>(); body.put("quoteId", quoteId); return body; } // Escapes a string for embedding in a JSON string literal. Sufficient // for this page's field values; not a general JSON serializer. static String escapeJson(String value) { StringBuilder out = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); switch (c) { case '"': out.append("\\\""); break; case '\\': out.append("\\\\"); break; case '\n': out.append("\\n"); break; case '\r': out.append("\\r"); break; case '\t': out.append("\\t"); break; default: if (c < 0x20) out.append(String.format("\\u%04x", (int) c)); else out.append(c); } } return out.toString(); } // Serializes a flat string-valued map to a JSON object. Sufficient for // this page's request bodies; not a general JSON serializer. static String toJsonObject(Map fields) { StringBuilder json = new StringBuilder("{"); boolean first = true; for (Map.Entry entry : fields.entrySet()) { if (!first) json.append(","); first = false; json.append("\"").append(entry.getKey()).append("\":\"").append(escapeJson(entry.getValue())).append("\""); } return json.append("}").toString(); } // Extracts one top-level string field from a JSON object by regex. // Sufficient for this page's response shapes; not a general JSON parser. static String extractField(String json, String field) { Matcher m = Pattern.compile("\"" + field + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json); return m.find() ? m.group(1) : null; } static String signedRequest(String method, String url, String idempotencyKey, String body) throws Exception { byte[] bodyBytes = body != null ? body.getBytes(StandardCharsets.UTF_8) : new byte[0]; // SignRequest is the real helper from /v3/authentication, compiled // on the classpath alongside this file — see that page's example. Map headers = SignRequest.signRequest(method, url, bodyBytes); if (idempotencyKey != null) headers.put("Idempotency-Key", idempotencyKey); HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection(); conn.setRequestMethod(method); for (Map.Entry h : headers.entrySet()) { conn.setRequestProperty(h.getKey(), h.getValue()); } if (body != null) { conn.setDoOutput(true); conn.getOutputStream().write(bodyBytes); } int status = conn.getResponseCode(); InputStream responseStream = status < 400 ? conn.getInputStream() : conn.getErrorStream(); // Reads the full response body. extractField below does minimal // single-field extraction from it, not a general JSON parser. return responseStream == null ? "" : new String(responseStream.readAllBytes(), StandardCharsets.UTF_8); } static String listPairs() throws Exception { return signedRequest("GET", BASE_URL + "/pairs", null, null); } // A new Idempotency-Key per logical operation. Reusing one for a // different trade returns 422 IDEMPOTENCY_MISMATCH. static String quote(String buyCurrency, String sellCurrency, String sellAmount, String buyAmount) throws Exception { String body = toJsonObject(buildQuoteBody(buyCurrency, sellCurrency, sellAmount, buyAmount)); return signedRequest("POST", BASE_URL + "/quotes", UUID.randomUUID().toString(), body); } static String executeTrade(String quoteId) throws Exception { String body = toJsonObject(buildTradeBody(quoteId)); return signedRequest("POST", BASE_URL + "/trades", UUID.randomUUID().toString(), body); } static String getBalances() throws Exception { return signedRequest("GET", BASE_URL + "/balances", null, null); } public static void main(String[] args) throws Exception { listPairs(); System.out.println("step=pairs"); String quoteResponse = quote("USDC", "USD", "1000.00", null); String quoteId = extractField(quoteResponse, "id"); if (quoteId == null) throw new RuntimeException("Quote response missing id: " + quoteResponse); System.out.println("step=quote quoteId=" + quoteId); String tradeResponse = executeTrade(quoteId); System.out.println("step=trade tradeId=" + extractField(tradeResponse, "id") + " status=" + extractField(tradeResponse, "status")); getBalances(); System.out.println("step=balances"); } } ``` ```cpp C++ theme={"theme":{"light":"poimandres","dark":"poimandres"}} // The full quickstart round-trip: pairs -> quote -> trade -> balances — the // pattern from /v3/quickstart. Requires OpenSSL and libcurl. No JSON // library was added, so JSON handling below is intentionally minimal (a // flat object serializer and single-field extractors), not a general // JSON parser. #include #include #include #include #include #include #include #include // Matches the definition in ../../authentication/cpp/sign_request.cpp, // compiled together with this file — see that file for the real // implementation of signRequest. struct SignedRequest { std::string authHeader; std::string sigHeader; }; SignedRequest signRequest(const std::string& method, const std::string& urlPath, const std::string& query, const std::string& body); static const std::string BASE_URL = "https://api.openfx.com/v3/fx"; // Builds the POST /v3/fx/quotes body. Supply exactly one of sellAmount or // buyAmount to anchor that side. Kept separate from the network call so // it's testable without a real request. std::map buildQuoteBody(const std::string& buyCurrency, const std::string& sellCurrency, std::optional sellAmount, std::optional buyAmount) { std::map body{{"buyCurrency", buyCurrency}, {"sellCurrency", sellCurrency}}; if (sellAmount) body["sellAmount"] = *sellAmount; if (buyAmount) body["buyAmount"] = *buyAmount; return body; } // Builds the POST /v3/fx/trades body. Kept separate from the network call // so it's testable without a real request. std::map buildTradeBody(const std::string& quoteId) { return {{"quoteId", quoteId}}; } // Escapes a string for embedding in a JSON string literal. Sufficient for // this page's field values; not a general JSON serializer. std::string escapeJson(const std::string& value) { std::ostringstream out; for (unsigned char c : value) { switch (c) { case '"': out << "\\\""; break; case '\\': out << "\\\\"; break; case '\n': out << "\\n"; break; case '\r': out << "\\r"; break; case '\t': out << "\\t"; break; default: if (c < 0x20) out << "\\u" << std::hex << std::setfill('0') << std::setw(4) << (int)c << std::dec; else out << (char)c; } } return out.str(); } // Serializes a flat string-valued map to a JSON object. Sufficient for // this page's request bodies; not a general JSON serializer. std::string toJsonObject(const std::map& fields) { std::ostringstream json; json << "{"; bool first = true; for (const auto& [key, value] : fields) { if (!first) json << ","; first = false; json << "\"" << key << "\":\"" << escapeJson(value) << "\""; } json << "}"; return json.str(); } // Generates a random per-call idempotency key. Not RFC 4122 UUID format — // idempotency keys only need to be unique client-generated strings — but // uses the same RAND_bytes source as the JWT nonce in sign_request.cpp. std::string randomIdempotencyKey() { unsigned char bytes[16]; RAND_bytes(bytes, sizeof(bytes)); std::ostringstream hex; for (unsigned char b : bytes) hex << std::hex << std::setfill('0') << std::setw(2) << (int)b; return hex.str(); } // Extracts one top-level string field from a JSON object with a naive scan. // Sufficient for this page's response shapes; not a general JSON parser. std::optional extractField(const std::string& json, const std::string& field) { std::string needle = "\"" + field + "\":\""; size_t start = json.find(needle); if (start == std::string::npos) return std::nullopt; start += needle.size(); size_t end = json.find('"', start); if (end == std::string::npos) return std::nullopt; return json.substr(start, end - start); } static size_t writeToString(char* data, size_t size, size_t nmemb, void* userp) { static_cast(userp)->append(data, size * nmemb); return size * nmemb; } std::string signedRequest(const std::string& method, const std::string& path, const std::string& idempotencyKey, const std::string& body) { std::string url = BASE_URL + path; SignedRequest req = signRequest(method, "/v3/fx" + path, "", body); CURL* curl = curl_easy_init(); curl_slist* headers = nullptr; headers = curl_slist_append(headers, ("Authorization: " + req.authHeader).c_str()); headers = curl_slist_append(headers, ("X-Request-Signature: " + req.sigHeader).c_str()); if (!idempotencyKey.empty()) headers = curl_slist_append(headers, ("Idempotency-Key: " + idempotencyKey).c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); if (!body.empty()) curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str()); std::string responseBody; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeToString); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseBody); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); // Returns the raw response body. extractField above does minimal // single-field extraction from it, not a general JSON parser. return responseBody; } std::string listPairs() { return signedRequest("GET", "/pairs", "", ""); } // A new Idempotency-Key per logical operation. Reusing one for a different // trade returns 422 IDEMPOTENCY_MISMATCH. std::string quote(const std::string& buyCurrency, const std::string& sellCurrency, std::optional sellAmount, std::optional buyAmount) { std::string body = toJsonObject(buildQuoteBody(buyCurrency, sellCurrency, sellAmount, buyAmount)); return signedRequest("POST", "/quotes", randomIdempotencyKey(), body); } std::string executeTrade(const std::string& quoteId) { std::string body = toJsonObject(buildTradeBody(quoteId)); return signedRequest("POST", "/trades", randomIdempotencyKey(), body); } std::string getBalances() { return signedRequest("GET", "/balances", "", ""); } #ifndef QUICKSTART_NO_MAIN #include int main() { try { listPairs(); std::cout << "step=pairs" << std::endl; std::string quoteResponse = quote("USDC", "USD", "1000.00", std::nullopt); std::optional quoteIdOpt = extractField(quoteResponse, "id"); if (!quoteIdOpt) throw std::runtime_error("Quote response missing id: " + quoteResponse); std::string quoteId = *quoteIdOpt; std::cout << "step=quote quoteId=" << quoteId << std::endl; std::string tradeResponse = executeTrade(quoteId); std::cout << "step=trade tradeId=" << extractField(tradeResponse, "id").value_or("") << " status=" << extractField(tradeResponse, "status").value_or("") << std::endl; getBalances(); std::cout << "step=balances" << std::endl; return 0; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } #endif ``` ```go Go theme={"theme":{"light":"poimandres","dark":"poimandres"}} // The full quickstart round-trip: pairs -> quote -> trade -> balances — the // pattern from /v3/quickstart. package main import ( "bytes" "crypto/rand" "encoding/json" "fmt" "net/http" // auth is the real signRequest helper from /v3/authentication — see // go.mod's replace directive if you've copied it somewhere else. auth "openfx-v3-authentication-example" ) const baseURL = "https://api.openfx.com/v3/fx" type SignerFunc func(method, url string, body []byte) (*auth.SignedRequest, error) var apiClient = &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return fmt.Errorf("API redirects are not allowed") }, } type QuoteBody struct { BuyCurrency string `json:"buyCurrency"` SellCurrency string `json:"sellCurrency"` SellAmount string `json:"sellAmount,omitempty"` BuyAmount string `json:"buyAmount,omitempty"` } type TradeBody struct { QuoteID string `json:"quoteId"` } type apiEnvelope struct { Data json.RawMessage `json:"data"` } type Quote struct { ID string `json:"id"` } type Trade struct { ID string `json:"id"` Status string `json:"status"` } type PairList struct { Pairs []json.RawMessage `json:"pairs"` } // Builds the POST /v3/fx/quotes body. Supply exactly one of sellAmount or // buyAmount to anchor that side. Kept separate from the network call so // it's testable without a real request. func buildQuoteBody(buyCurrency, sellCurrency, sellAmount, buyAmount string) QuoteBody { return QuoteBody{BuyCurrency: buyCurrency, SellCurrency: sellCurrency, SellAmount: sellAmount, BuyAmount: buyAmount} } // Builds the POST /v3/fx/trades body. Kept separate from the network call // so it's testable without a real request. func buildTradeBody(quoteID string) TradeBody { return TradeBody{QuoteID: quoteID} } func newIdempotencyKey() (string, error) { b := make([]byte, 16) if _, err := rand.Read(b); err != nil { return "", err } b[6] = (b[6] & 0x0f) | 0x40 // version 4 b[8] = (b[8] & 0x3f) | 0x80 // variant 10 return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil } func signedRequest(signer SignerFunc, method, path, idempotencyKey string, body []byte) (json.RawMessage, error) { switch method + " " + path { case "GET /pairs", "GET /balances", "POST /quotes", "POST /trades": default: return nil, fmt.Errorf("unsupported quickstart request: %s %s", method, path) } url := baseURL + path signed, err := signer(method, url, body) if err != nil { return nil, err } req, err := http.NewRequest(method, url, bytes.NewReader(body)) if err != nil { return nil, err } for k, v := range signed.Headers { req.Header.Set(k, v) } if idempotencyKey != "" { req.Header.Set("Idempotency-Key", idempotencyKey) } res, err := apiClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() var envelope apiEnvelope if err := json.NewDecoder(res.Body).Decode(&envelope); err != nil { return nil, err } return envelope.Data, nil } func listPairs() (*PairList, error) { data, err := signedRequest(auth.SignRequest, "GET", "/pairs", "", nil) if err != nil { return nil, err } var pairs PairList if err := json.Unmarshal(data, &pairs); err != nil { return nil, err } return &pairs, nil } // A new Idempotency-Key per logical operation. Reusing one for a different // trade returns 422 IDEMPOTENCY_MISMATCH. func quote(buyCurrency, sellCurrency, sellAmount, buyAmount string) (*Quote, error) { body, err := json.Marshal(buildQuoteBody(buyCurrency, sellCurrency, sellAmount, buyAmount)) if err != nil { return nil, err } key, err := newIdempotencyKey() if err != nil { return nil, err } data, err := signedRequest(auth.SignRequest, "POST", "/quotes", key, body) if err != nil { return nil, err } var q Quote if err := json.Unmarshal(data, &q); err != nil { return nil, err } return &q, nil } func executeTrade(quoteID string) (*Trade, error) { body, err := json.Marshal(buildTradeBody(quoteID)) if err != nil { return nil, err } key, err := newIdempotencyKey() if err != nil { return nil, err } data, err := signedRequest(auth.SignRequest, "POST", "/trades", key, body) if err != nil { return nil, err } var t Trade if err := json.Unmarshal(data, &t); err != nil { return nil, err } return &t, nil } func getBalances() (json.RawMessage, error) { return signedRequest(auth.SignRequest, "GET", "/balances", "", nil) } func main() { pairs, err := listPairs() if err != nil { fmt.Println("Error:", err) return } fmt.Println("step=pairs count=", len(pairs.Pairs)) q, err := quote("USDC", "USD", "1000.00", "") if err != nil { fmt.Println("Error:", err) return } fmt.Println("step=quote quoteId=", q.ID) t, err := executeTrade(q.ID) if err != nil { fmt.Println("Error:", err) return } fmt.Println("step=trade tradeId=", t.ID, "status=", t.Status) if _, err := getBalances(); err != nil { fmt.Println("Error:", err) return } fmt.Println("step=balances") } ``` ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} #!/usr/bin/env bash # The full quickstart round-trip: pairs -> quote -> trade -> balances — the # pattern from /v3/quickstart. Illustrative only: cURL can't compute the # ES256 request signature itself, so $OPENFX_JWT/$OPENFX_SIGNATURE below are # placeholders — get real values from signRequest, in any supported # language, via /v3/authentication#mint-a-jwt-and-sign-the-request. Mint a # fresh pair per call; never reuse one across requests. X-App-Mode is hard-coded to SANDBOX below. To target Live, use a Live API # key (mint the JWT from it) and set X-App-Mode to LIVE. set -euo pipefail BASE_URL="https://api.openfx.com/v3/fx" # Extracts one top-level string field from a JSON response by pattern match. # Sufficient for this script's response shapes; not a general JSON parser. extract_field() { echo "$1" | grep -o "\"$2\":\"[^\"]*\"" | head -1 | sed -E "s/.*:\"([^\"]*)\"/\1/" } # 1. List pairs. export OPENFX_JWT="" export OPENFX_SIGNATURE="" curl "$BASE_URL/pairs" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: SANDBOX" # 2. Quote 1000 USD -> USDC. A new Idempotency-Key per logical operation. # Reusing one for a different trade returns 422 IDEMPOTENCY_MISMATCH. export OPENFX_JWT="" export OPENFX_SIGNATURE="" QUOTE_RESPONSE=$(curl -s -X POST "$BASE_URL/quotes" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: SANDBOX" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "buyCurrency": "USDC", "sellCurrency": "USD", "sellAmount": "1000.00" }') QUOTE_ID=$(extract_field "$QUOTE_RESPONSE" "id") # 3. Execute the trade against the quote. export OPENFX_JWT="" export OPENFX_SIGNATURE="" TRADE_RESPONSE=$(curl -s -X POST "$BASE_URL/trades" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: SANDBOX" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "quoteId": "'"$QUOTE_ID"'" }') echo "trade status: $(extract_field "$TRADE_RESPONSE" "status")" # 4. Check the resulting balances. export OPENFX_JWT="" export OPENFX_SIGNATURE="" curl "$BASE_URL/balances" \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: SANDBOX" ``` ## What's next > [card] [Resource IDs](/v3/resource-ids) > > Readable, typed-prefix ID format, stability guarantees, and cross-resource > references. > [card] [Errors](/v3/errors) > > Typed error codes, retryable flags, and the catch-and-branch pattern for > your next 5xx. > [card] [Settlement models](/v3/settlement-models) > > Deposits, withdrawals, and the unified fiat + stablecoin endpoint. > [card] [API reference](/v3/api-reference/trade/create-quote) > > Every endpoint, every field, every response shape. > [card] [Live checklist](/v3/live-checklist) > > Pre-launch checklist, key rotation, IP allowlisting. # Quotes Source: https://docs.openfx.com/v3/quotes Atomic FX trades: discover supported pairs, quote a rate, execute the trade against the quote. OpenFX trading is a quote-then-execute model. You request a quote (a rate locked in for 3 seconds by default), then execute a trade against that quote. Execution is atomic: it either succeeds at the quoted rate or it fails. The same flow covers every conversion: fiat to fiat, fiat to stablecoin, stablecoin to stablecoin. > [!NOTE] > > Splitting quote and trade forces deterministic execution: the rate you saw is > the rate that executes, or the trade fails; execution never silently > re-prices. After QUOTE_EXPIRED, request a fresh > quote and submit the trade with a new `Idempotency-Key`. After > TRADE_EXECUTION_FAILED, call > `GET /v3/fx/trades/{id}` with `error.details.resourceId` first. If the > trade exists, continue tracking it. If the lookup returns `404` > TRADE_NOT_FOUND, request a fresh quote and > submit the trade with a new key. See [Trade > recovery](/v3/errors#retrying-trade-execution-failed). ## The trading flow ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% sequenceDiagram participant Client participant OpenFX Client->>+OpenFX: GET /v3/fx/pairs OpenFX-->>-Client: List of tradable pairs Client->>+OpenFX: POST /v3/fx/quotes
(Idempotency-Key) OpenFX-->>-Client: Quote
{ id, buyAmount/sellAmount, quoteAmount, expiresAt } Note over Client,OpenFX: Quote is valid for 3s by default Client->>+OpenFX: POST /v3/fx/trades
(quoteId · NEW Idempotency-Key) OpenFX-->>-Client: Trade (status: EXECUTED) Client->>+OpenFX: GET /v3/fx/balances OpenFX-->>-Client: Updated balances ``` ## Endpoints | Path | Description | Idempotency-Key | | - | - | - | | [`GET /v3/fx/pairs`](/v3/api-reference/trade/list-currency-pairs) | List all tradable currency pairs with min/max amounts | — | | [`POST /v3/fx/quotes`](/v3/api-reference/trade/create-quote) | Lock in an exchange rate for a few seconds | Required, 30-min TTL | | [`GET /v3/fx/quotes/{id}`](/v3/api-reference/trade/get-quote-by-id) | Look up a single quote (status) | — | | [`POST /v3/fx/trades`](/v3/api-reference/trade/execute-trade) | Execute against a quote | Required, 24-hr TTL | | [`GET /v3/fx/trades`](/v3/api-reference/trade/list-trades) | Paginated list of trades, newest first | — | | [`GET /v3/fx/trades/{id}`](/v3/api-reference/trade/get-trade) | Look up a single trade | — | | [`POST /v3/fx/trades/{id}/settle`](/v3/api-reference/trade/settle-trade) | Finalize a manual-settlement trade once its window opens | Required, 24-hr TTL | | [`POST /v3/fx/trades/{id}/reverse-quote`](/v3/api-reference/trade/generate-reverse-quote) | Preview the differential for unwinding a trade | Required, 30-min TTL | | [`POST /v3/fx/trades/{id}/reverse`](/v3/api-reference/trade/reverse-trade) | Execute a reversal against a reverse quote | Required, 24-hr TTL | ## Quote lifecycle Quotes are **short-lived**: 3 seconds by default. You can extend via the `quoteForSeconds` request parameter. > [!NOTE] > > **`quoteForSeconds` accepts a closed set of standard durations:** 3, 15, > 30, 45, 60 seconds. > [!NOTE] > > **Longer holds are priced higher.** Quote holds longer than 15 seconds are priced higher than shorter holds, because the quoted rate reflects the market volatility OpenFX is exposed to while the quote remains open. The rate in the quote response is the rate you can execute at for the full hold. The reverse-quote endpoint (`POST /v3/fx/trades/{id}/reverse-quote`) defaults `quoteForSeconds` to 15 seconds. It can return TRADE_NOT_FOUND or TRADE_NOT_REVERSIBLE; `POST /v3/fx/trades/{id}/reverse` can also return QUOTE_NOT_FOUND, QUOTE_EXPIRED, QUOTE_ALREADY_CONSUMED, and TRADE_INSUFFICIENT_BALANCE. The quote is binding only if you execute `POST /v3/fx/trades` before `expiresAt`. Once expired, executing returns `409` QUOTE_EXPIRED; request a new quote and execute against the new `id`. ## Retrieving a quote You can fetch a previously-created quote by ID for **2 days from its `createdAt`**. The endpoint reads from durable storage, not the create-call's idempotency cache, so the quote stays retrievable long after the 30-minute idempotency TTL has expired. After 2 days, `GET /v3/fx/quotes/{id}` returns `404` QUOTE_NOT_FOUND, the same as an unknown ID. ### Quote status `GET /v3/fx/quotes/{id}` includes a `status` field not present on the `POST /v3/fx/quotes` create response: | Status | Meaning | Trade execution | | - | - | - | | ACTIVE | Unconsumed and within the validity window | Will succeed (subject to balance + compliance) | | EXPIRED | Unconsumed and past `expiresAt` | Returns `409` QUOTE_EXPIRED; re-quote and retry | | CONSUMED | A trade has executed against this quote | Returns `409` QUOTE_ALREADY_CONSUMED; quotes are single-use | ## After execution The execute response returns the `Trade`. IMMEDIATE trades are already EXECUTED. A T0 trade is EXECUTED on an AUTO account and READY_TO_SETTLE on a MANUAL account. A T1 or T2 trade waits for its settlement window. The statuses, the settle and reverse actions, and the webhooks for each are on [Trades](/v3/trades). ## Common mistakes * **Expired quote (QUOTE_EXPIRED).** Quotes default to 3 seconds. Recover by re-quoting and retrying with a NEW idempotency key. * **Execution failed mid-flight (TRADE_EXECUTION_FAILED).** Call `GET /v3/fx/trades/{id}` first to check state before retrying. * **Idempotency key replay (IDEMPOTENCY_MISMATCH).** Reusing a key with a different request body returns `422` IDEMPOTENCY_MISMATCH. ## What's next > [card] [Trades](/v3/trades) > > Trade statuses, settlement windows, and the settle and reverse actions. > [card] [Settlement models](/v3/settlement-models) > > Netted vs Per-Trade settlement models, plus deposits and withdrawals. > [card] [Trade webhooks](/v3/webhooks/trades/trade-ready-to-settle) > > Push notifications for ready-to-settle, settled, and reversed trades. > [card] [Quickstart](/v3/quickstart) > > Worked end-to-end: quote → trade → balance. > [card] [Idempotency](/v3/idempotency) > > Why both /quotes and /trades require keys. # Rate limiting Source: https://docs.openfx.com/v3/rate-limiting OpenFX exposes IETF-standard RateLimit-* headers on every response so you always know your cap and when it resets. Every response carries IETF-standard `RateLimit-*` headers so you know your cap and when the current window resets. The limit is **300 requests / 10-second window**, tracked as a separate bucket per org, per environment (LIVE or SANDBOX), with the same cap in both. All API keys under an org share the same environment bucket; creating more keys does not raise the limit. When you exceed it you get a `429`; wait `Retry-After` seconds, then retry. ## Rate-limit headers | Header | Type | Purpose | | - | - | - | | `RateLimit-Limit` | integer | Max requests allowed in the current window | | `RateLimit-Reset` | integer (seconds) | Duration until the current window resets, **not** an epoch timestamp | ```http theme={"theme":{"light":"poimandres","dark":"poimandres"}} HTTP/1.1 200 OK RateLimit-Limit: 300 RateLimit-Reset: 8 ``` > [!NOTE] > > **`RateLimit-Reset` is a duration, not a timestamp.** `RateLimit-Reset: 8` > means "the window resets in 8 seconds from now." Compute your wait as > `RateLimit-Reset * 1000` milliseconds from when you received the response, not > by comparing it against a clock. On a `429` or a `409` IDEMPOTENCY_IN_FLIGHT, > prefer the `Retry-After` header (also seconds), the more specific, > purpose-built signal for exactly when to retry. ## Default limits | Environment | Limit | | - | - | | LIVE | 300 requests / 10-second window | | SANDBOX | 300 requests / 10-second window | The limit is per org, per environment: bucketed by whichever `X-App-Mode` (LIVE or SANDBOX) the request used, shared across every API key under that org. LIVE and SANDBOX are separate buckets with the same cap; usage in one doesn't count against the other. ## Handling rate limits: pattern > [!WARNING] > > **Mint a fresh JWT *and* a fresh `X-Request-Signature` per attempt: do not > capture once.** JWTs are 60-second TTL and the signature is bound to the JWT's > `nonce` ([Authentication](/v3/authentication)). Retries across several > attempts can add up to more than 60s of wall-clock time. A captured JWT will > expire mid-loop and your next request returns `401` AUTH_TOKEN_EXPIRED (or a > `401` AUTH_TOKEN_INVALID with `details.reason: request_signature_invalid` if you > reused the signature). The pattern below takes a `signRequest` function that > mints both on each attempt. ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} // `signRequest({ method, url, body })` returns { headers, body } with a freshly minted JWT // AND a freshly computed X-Request-Signature each call. See the Authentication guide. async function callWithBackoff( { method, url, body }, signRequest, maxRetries = 5, ) { for (let attempt = 0; attempt < maxRetries; attempt++) { // Mint per attempt: JWT TTL is 60s; backoff loops can exceed that, and the // signature is bound to the JWT's nonce so capturing once is doubly broken. const signed = signRequest({ method, url, body }); const res = await fetch(url, { method, headers: signed.headers, body: signed.body, }); if (res.status !== 429) return res; // Rate limited: Retry-After and RateLimit-Reset are both a number of // seconds to wait, NOT an epoch timestamp. Number(null) is 0 (which // passes isFinite!), so check for a missing header explicitly rather // than letting Number() coerce it. Otherwise, a response with neither // header retries immediately instead of falling back to backoff. const waitHeader = res.headers.get("retry-after") ?? res.headers.get("ratelimit-reset"); const wait = waitHeader === null ? NaN : Number(waitHeader); const waitMs = Number.isFinite(wait) ? wait * 1000 : 1000 * (attempt + 1); // fall back to linear backoff await sleep(waitMs); } throw new Error("Rate limit retry budget exhausted"); } ``` ## When you hit the limit A 429 response uses the standard error envelope and includes a `Retry-After` header. Its `details` object is empty: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "error": { "code": "RATE_LIMIT_EXCEEDED", "type": "RATE_LIMITED", "message": "Rate limit exceeded. Retry after the indicated wait.", "retryStrategy": "WAIT_THEN_RETRY_SAME_KEY", "details": {} } } ``` Headers on a 429: ```http theme={"theme":{"light":"poimandres","dark":"poimandres"}} HTTP/1.1 429 Too Many Requests RateLimit-Limit: 300 RateLimit-Reset: 8 Retry-After: 8 X-Trace-Id: 4bf92f3577b34da6a3ce929d0e0e4736 X-Request-Timestamp: 2026-05-29T12:34:56.789Z ``` Compute your wait as `Retry-After * 1000` milliseconds (both `Retry-After` and `RateLimit-Reset` are a **duration** in seconds, not an epoch timestamp; prefer `Retry-After`, the more specific signal for exactly when to retry). The same `Retry-After` header is present on `409` IDEMPOTENCY_IN_FLIGHT too. See [Idempotency](/v3/idempotency). ## Need a higher rate limit? Email [support@mail.openfx.com](mailto:support@mail.openfx.com). Provide your org ID, whether you need it on LIVE or SANDBOX, and a sense of the burst pattern you need. ## Common mistakes * **Sleeping a fixed duration on 429 instead of waiting `Retry-After` seconds.** A hard-coded sleep either thrashes the limit or wastes throughput. Compute the wait from `Retry-After` (or `RateLimit-Reset` as a fallback). * **Treating `RateLimit-Reset` as an epoch timestamp.** It's a duration in seconds from the response, not a Unix timestamp: `RateLimit-Reset * 1000 - Date.now()` computes a nonsensical wait. Use `RateLimit-Reset * 1000` directly. * **Retrying a 429 indefinitely.** A single reset-wait is not a license to retry forever. Cap retry attempts; on exhaustion, surface the error to the caller. * **Capturing the JWT or signature outside the retry loop.** JWTs are 60s TTL and the `X-Request-Signature` is bound to the JWT's `nonce`; both must be re-minted per attempt. Pass a `signRequest` function so each attempt gets a fresh token AND a fresh signature. See the Warning above. * **Polling near the rate-limit ceiling.** A 300 req/10s ceiling and a 1-second poll across 30 background workers leaves zero headroom for actual user-driven requests. Pace well under the limit. * **Assuming a support-granted limit increase applies to both environments.** LIVE and SANDBOX are separate buckets; a higher ceiling granted on one doesn't carry over to the other. ## What's next > [card] [Metadata & tracing](/v3/metadata-and-tracing) > > X-Trace-Id on every response. > [card] [Idempotency](/v3/idempotency) > > In-flight requests and safe retries. # Resource IDs Source: https://docs.openfx.com/v3/resource-ids Every resource has a readable, typed ID: a resource-type prefix plus a Base58 encoding of the underlying UUID. Foreign-key fields like withdrawalAccountId and quoteId reference these IDs across resources. Every resource in v3 (`Quote`, `Trade`, `Deposit`, `Withdrawal`, `WithdrawalAccount`, `Account`, `FinancialAccount`, `PayoutAddress`, `PayoutQuote`, `Payout`, `AccountCapability`) carries an `id` that the server assigns at creation, plus an `object` field naming the resource type. IDs are **readable**: a lowercase 3-to-6-letter prefix identifies the resource type, followed by a Base58 encoding of the underlying 128-bit UUID. Two fields in v3 reference these IDs across resources: `quoteId` on a trade points at a `Quote.id`, and `withdrawalAccountId` on a withdrawal points at a `WithdrawalAccount.id`. > [!NOTE] > > **v3 emits readable IDs on every response.** Bare UUIDs never appear in a v3 > response body; the readable ID is the public identifier. For backward > compatibility, v3 **accepts** either a readable ID or a bare UUID v4 wherever > an ID is expected on input (path parameters, query parameters, and > request-body foreign keys); both decode to the same underlying record. New > integrations should use the readable form returned by the API. ## Format `_`: a lowercase 3-to-6-letter type prefix, an underscore, and the Base58 encoding of the resource's 128-bit UUID. | Resource | `object` | Prefix | Example | | - | - | - | - | | Quote | `quote` | `qte_` | `qte_3FfGK34vwMvVFDedyb2nkf` | | Trade | `trade` | `tde_` | `tde_5W7guYdHT24JFnRQrZN9y8` | | Deposit | `deposit` | `dpt_` | `dpt_EA9vbVngB76PmMibCiMNPb` | | Withdrawal | `withdrawal` | `wtd_` | `wtd_6SATV6VSUdBTttHWBmCYjD` | | Withdrawal account | `withdrawalAccount` | `wac_` | `wac_NDqQ9LmcUASpnHR6CTvdkk` | | Account | `account` | `acc_` | `acc_BMY3UenpGBn8ZQ8hio4BgE` | | Financial account | `financialAccount` | `finacc_` | `finacc_AmKC5dMVXUbiAW8VzKBfqz` | | Payout address | `payoutAddress` | `pytadd_` | `pytadd_PbDQ126YUAbkNrNX6XbGL` | | Payout quote | `payoutQuote` | `pytqte_` | `pytqte_5PKPvtstSbXf9BurnLJfLA` | | Payout | `payout` | `pyt_` | `pyt_9P3Gs3GSn4hMdHQ22Evi5f` | | Account capability | `accountCapability` | `cap_` | `cap_Ce3AJmAmDGcJgTmTqgFVZ` | | User | — | `usr_` | `usr_7m4VsfRw4pGrS76WYj5tnx` | `Pair` and `Balance` have no resource UUID. A pair is identified by its `(buyCurrency, sellCurrency)` combination, and a balance by `currency`, not by an `id` field. * The Base58 alphabet excludes `0`, `O`, `I`, and `l` to avoid visual ambiguity: `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`. * The encoded body is at most 22 characters and is **not a fixed length**: 21–22 characters for a typical random UUID, shorter only for near-zero values (the nil UUID encodes to 16 characters). * Regex pre-filter: `^[a-z]{3,6}_[1-9A-HJ-NP-Za-km-z]{1,22}$`. This is a loose shape check; the authoritative validation is a successful decode back to exactly 16 bytes. A value that matches the regex but doesn't decode to 16 bytes is rejected the same as a malformed ID. The payments operations are stricter: their specification pins each ID to its own prefix (for example `pyt_` or `acc_`) and a body of 21 or 22 characters, so a short body that passes the regex fails validation there. Use IDs exactly as the API returned them. * Base58 is case-sensitive. There is no case normalization: a mis-cased but otherwise well-formed ID decodes to a different value (or fails to decode) and is rejected. Encoding is a pure, stateless, reversible function of the UUID: the same UUID always produces the same readable ID, and two different UUIDs never collide. There's no database column or backfill involved; the readable ID is derived from the UUID on every response. Any ID that fails to decode, or whose prefix names a different resource type than the field expects, is rejected at the validation layer with `400` VALIDATION_QUERY_FAILED (query and body) or `400` VALIDATION_PATH_FAILED (path parameters). ## Stability * IDs are **permanent**. Once issued, the underlying UUID never changes and never gets reused, so its readable encoding doesn't either. * Safe to store as foreign keys in your database. Index the readable ID, the underlying UUID, or both, depending on what your queries need. * Safe to log in audit trails. IDs carry no PII: the prefix reveals only the resource type, and the body is an opaque, lossless encoding of the UUID. * Safe to share in support tickets and idempotency-key collision reports. The stability contract is the same contract that makes idempotency keys useful: if you persist a resource ID at write time and the network drops the response, that ID will still resolve to the same record on retry. ## Cross-resource references Some fields are foreign keys pointing at IDs on other resources. The table below lists every such reference in v3: | Field | On resource | Points to | Notes | | - | - | - | - | | `quoteId` | `TradeCreateRequest`, `Trade` | `Quote.id` | Required when executing a trade. Echoed back on the resulting `Trade`. | | `withdrawalAccountId` | `WithdrawalCreateRequest`, `Withdrawal` | `WithdrawalAccount.id` | The verified withdrawal account. Fiat or stablecoin is inferred from the account. | | `actorId` | `Withdrawal` | User (`usr_` prefix) | The actor that initiated the withdrawal. Masked to a fixed placeholder for internal OpenFX operators. Not independently fetchable; v3 has no `GET` for user records. | | `creatorId` | `WithdrawalAccount` | User (`usr_` prefix) | The user that created the withdrawal account. `null` only for legacy rows. Not independently fetchable. | | `financialAccountId` | `Payout`, `PayoutQuote` | `FinancialAccount.id` | The balance a payout is funded from. | | `receiver.accountId` | `Payout` | `Account.id` | Derived from `receiver.payoutAddressId`: the account that address belongs to. | | `receiver.payoutAddressId` | `Payout` | `PayoutAddress.id` | The payout address the funds are credited to. | | `accountId` | `PayoutAddress` | `Account.id` | The account the payout address belongs to. | Anything else that looks like an ID (a transaction hash, a currency code) is not a foreign key into another v3 resource. ## ID vs Idempotency-Key Two ID-shaped fields in v3 serve different purposes: | | Resource ID | Idempotency-Key | | - | - | - | | Generated by | Server | Client | | Lifetime | Permanent | TTL (30 min / 24 h / 7 days, per endpoint) | | Format | `_` (e.g. `wac_NDqQ9LmcUASpnHR6CTvdkk`) | Any string matching `^[a-zA-Z0-9_-]{1,255}$` | | Where it lives | Response body `id`, foreign-key fields | `Idempotency-Key` request header | | Purpose | Identify a record forever | De-duplicate a single write attempt | | Safe to log | Yes | Yes (but don't embed PII in them) | The two are complementary: you generate an idempotency key before the request, the server returns a resource ID in the response, and you persist both alongside each other. The idempotency key lets you safely retry the write; the resource ID lets you look up the result for the rest of time. See [Idempotency → Crash recovery](/v3/idempotency#crash-recovery) for the persist-both pattern. ## Common mistakes * **Treating IDs as transient.** They aren't. Persist them. * **Parsing or decoding the readable ID yourself.** The prefix tells you the resource type; don't try to derive anything else from the body. Treat the body as an opaque string, even though it happens to be reversible server-side. * **Reading the `id` from your own DB row instead of the API response on a write.** If you assigned an identifier locally and sent it as the request body, that's not the resource ID. The server generates its own. Always trust the response, not your draft. * **Confusing `quoteId` with `Idempotency-Key` on the trade execution call.** `quoteId` goes in the JSON body, `Idempotency-Key` goes in the header. They're unrelated. * **Storing only the readable ID and losing the ability to index efficiently.** Both the readable ID and its underlying UUID identify the same record. Store whichever shape fits your schema, or both. * **Assuming a hardcoded body length.** The encoded body is at most 22 characters but isn't fixed-width. Validate by prefix and successful decode, not by string length. ## What's next > [card] [Idempotency](/v3/idempotency) > > Client-generated keys vs server-generated IDs. > [card] [Pagination](/v3/pagination) > > Opaque cursors, distinct from resource IDs. Pass them back verbatim. > [card] [Errors](/v3/errors) > > When you'll see `*_NOT_FOUND` and how to handle it. # Settlement models Source: https://docs.openfx.com/v3/settlement-models Netted and Per-Trade settlement models, plus the balances, deposits, and withdrawals flows they share. Every OpenFX organization runs exactly one settlement model, an organization-level setting rather than a per-trade or per-request option. Both models coexist on the platform; neither replaces the other, and a trade's `settlementWindow` (IMMEDIATE, T0, T1, T2) is orthogonal to which one you're on. > [card] Netted Settlement > > The default. A trade settles on its own: at execution for IMMEDIATE/T0, automatically once the window opens for T1/T2. No client action, ever. An instant trade can settle against a short sell-side balance, and the shortfall counts against your [exposure limit](/v3/exposure). > [card] Per-Trade Settlement > > Opt-in. Except for IMMEDIATE trades, which are EXECUTED straight away, a trade reaches READY_TO_SETTLE and waits: you call [`settle`](/v3/api-reference/trade/settle-trade) to complete it at the locked rate, or [`reverse`](/v3/api-reference/trade/reverse-trade) to unwind it instead. Execution returns TRADE_INSUFFICIENT_BALANCE unless the sell-side balance covers the trade. The trade webhook payload (`fx.trade.*` events) reports the organization setting as `tradeSettlementMode`; the REST `Trade` resource doesn't include it. The values are AUTO for Netted Settlement and MANUAL for Per-Trade Settlement. ## Comparison | | Netted Settlement | Per-Trade Settlement | | - | - | - | | Client action after execution | None | Call `settle` or `reverse` | | Reachable trade states | `PENDING → EXECUTED`, or `PENDING → LOCKED → EXECUTED` | `PENDING → [LOCKED →] READY_TO_SETTLE → EXECUTED \| REVERSED`; IMMEDIATE: `PENDING → EXECUTED` | | Short sell-side balance | An instant trade settles into a negative balance, which counts against your exposure limit | Execution returns TRADE_INSUFFICIENT_BALANCE | | Unique endpoints | None | [`settle`](/v3/api-reference/trade/settle-trade), [`reverse-quote`](/v3/api-reference/trade/generate-reverse-quote), [`reverse`](/v3/api-reference/trade/reverse-trade) | | Trade webhooks | fx.trade.settled | fx.trade.ready_to_settle, fx.trade.settled, fx.trade.reversed | | Fits | OTC desks running their own book | PSPs and intermediaries settling per end-client obligation | ## Deposits and withdrawals Trade Settlement surfaces the three things you do with funds: receive (deposits), see (balances), send (withdrawals). Fiat and stablecoin share a single withdrawal endpoint; the rail is inferred from the verified withdrawal account. ## The fund-movement flow ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% sequenceDiagram participant Client participant OpenFX participant Bank as Bank or chain Bank->>+OpenFX: Fiat wire / on-chain deposit OpenFX-->>-Client: Webhook (deposit event) Client->>+OpenFX: GET /v3/fx/deposits OpenFX-->>-Client: Deposit list (newest first) Client->>+OpenFX: GET /v3/fx/balances OpenFX-->>-Client: Updated balances Client->>+OpenFX: POST /v3/fx/withdrawals
(withdrawalAccountId · withdrawalAmount · currency · NEW Idempotency-Key) OpenFX-->>-Client: Withdrawal (status: PENDING) Note over OpenFX,Bank: Settlement
(chain for stablecoin · rail for fiat) Client->>+OpenFX: GET /v3/fx/withdrawals/{id} OpenFX-->>-Client: Withdrawal (status: COMPLETED) ``` ## Endpoints | Path | Description | Idempotency-Key | | - | - | - | | [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances) | Per-currency `withdrawableBalance` / `totalBalance` | — | | [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits) | Paginated list of deposits, newest first | — | | [`GET /v3/fx/deposits/{id}`](/v3/api-reference/trade-settlement/get-deposit) | Look up a single deposit | — | | [`POST /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/create-withdrawal) | Initiate a fiat or stablecoin withdrawal | Required, **7-day TTL** | | [`GET /v3/fx/withdrawals/{id}`](/v3/api-reference/trade-settlement/get-withdrawal) | Look up a single withdrawal | — | | [`GET /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/list-withdrawals) | Paginated list (fiat + stablecoin together) | — | | [`GET /v3/fx/withdrawal-accounts`](/v3/api-reference/trade-settlement/list-withdrawal-accounts) | List withdrawal accounts in any status; filter with `verified` when needed | — | ## Balances [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances) returns an organization-wide `aggregate` and one row per currency, each with a `withdrawableBalance` and a `totalBalance`. [Balances](/v3/balances) explains every field and how they differ. For how the two balances change across a trade, see [Amounts](/v3/amounts#balance-lifecycle-available-vs-total). ## What's next > [card] [Quotes](/v3/quotes) > > Quote and execute FX trades, plus the full settle/reverse reference. > [card] [Trades](/v3/trades) > > Statuses and actions for a trade under either model. > [card] [Exposure](/v3/exposure) > > See how unsettled trades count against your organization's exposure limit, under either model. > [card] [Verified accounts](/v3/verified-accounts) > > Register first-party withdrawal destinations before going live. > [card] [Idempotency](/v3/idempotency) > > 7-day TTL on withdrawal keys; crash-safe retry pattern. # Settlement times Source: https://docs.openfx.com/v3/settlement-times Submission cut-offs per fiat rail. Withdrawals submitted after the cut-off are processed the next banking day. **What this is.** OpenFX submission cut-offs for fiat withdrawals, broken down by currency and rail. Use this page to figure out when a withdrawal needs to be in by, and which rail your withdrawal account targets. **When it matters.** Treasury operations, end-of-day reconciliation, batching withdrawals, or anywhere you need to know whether a submission will land "today" or roll to the next banking day. **What you'll learn.** Cut-off times per rail, the rail-to-account binding, and how the cut-off interacts with the [withdrawals](/v3/withdrawals). The rail a withdrawal travels through is bound to the verified withdrawal account and reported as `WithdrawalAccount.rail` (e.g. FEDWIRE, SWIFT, ACH, SEPA, PIX, SPEI, FPS; `null` for stablecoin accounts, which report the chain under `network` instead). The cut-off tables below are organized by display name, with the API `rail` value in the second column. CHAPS is a settlement route that OpenFX chooses, and there is no CHAPS value of `rail`, so its row shows an em dash. > [!WARNING] > > **This page is informational and not an SLA.** Submissions after the cut-off > are processed the next banking day. Receiving-bank processing can add > additional time: it depends on the receiving bank's hours, cut-offs, and > holidays, which are outside OpenFX's control. The cut-offs below describe > OpenFX's submission window only. ## How to read these tables * **Submission cut-off** is the latest time OpenFX will dispatch a withdrawal to the rail on the same banking day. Submissions after this cut-off are queued and dispatched on the next banking day. * **24/7** means there is no OpenFX cut-off: submissions are dispatched continuously, including weekends and holidays, unless a row says otherwise. * **Notes** call out per-rail constraints (transaction-size thresholds, holiday exclusions, etc.). ## Fiat rails by currency > [accordion] USD: Fedwire, SWIFT > > | Rail | `rail` | Submission cut-off | Notes | > | - | - | - | - | > | Fedwire | FEDWIRE | 4:30 PM ET (Mon–Fri) | US banking days only | > | SWIFT | SWIFT | 5:00 PM ET (Mon–Fri) | Counterparty bank determines onward routing time | > [accordion] EUR: SEPA, SEPA Instant, SWIFT > > | Rail | `rail` | Submission cut-off | Notes | > | - | - | - | - | > | SEPA | SEPA | 12:30 PM London time (Mon–Fri) | | > | SEPA Instant | SEPA | 24/7 | Under €1M per transaction | > | SWIFT | SWIFT | 9:30 AM London time (Mon–Fri) | Counterparty bank determines onward routing time | > [accordion] GBP: FPS, CHAPS, SWIFT > > | Rail | `rail` | Submission cut-off | Notes | > | - | - | - | - | > | FPS (domestic) | FPS | 24/7 | Under £1M per transaction | > | CHAPS | — | 4:00 PM London time (Mon–Fri) | Used for higher-value or scheme-restricted transfers | > | SWIFT | SWIFT | 4:00 PM London time (Mon–Fri) | Counterparty bank determines onward routing time | > [accordion] MXN: SPEI > > | Rail | `rail` | Submission cut-off | Notes | > | - | - | - | - | > | SPEI | SPEI | 24/7 | | > [accordion] AED: UAEFTS, SWIFT > > | Rail | `rail` | Submission cut-off | Notes | > | - | - | - | - | > | UAEFTS | UAEFTS | 24/7 | Under AED 50,000 | > | UAEFTS | UAEFTS | 4:00 PM GST (Mon–Fri) | AED 50,000 and above | > | SWIFT | SWIFT | 10:30 AM GST (Mon–Fri) | Counterparty bank determines onward routing time | > [accordion] AUD: NPP > > | Rail | `rail` | Submission cut-off | Notes | > | - | - | - | - | > | NPP | NPP | 24/7 | | > [accordion] BRL: PIX > > | Rail | `rail` | Submission cut-off | Notes | > | - | - | - | - | > | PIX | PIX | 24/7 | | ## Stablecoin rails Stablecoin withdrawals settle on-chain in minutes rather than against banking-hour cut-offs. Confirmation count and network congestion drive the wall-clock time. See [Supported networks](/v3/supported-networks) for the per-stablecoin chain matrix. > [!NOTE] > > The required confirmation threshold varies by network; the prose below > describes the practical wall-clock impact rather than fixing a per-network > number. > [accordion] EVM chains (Ethereum, Polygon, Arbitrum, Base, Optimism, Avalanche, BSC) > > Submission is 24/7. Settlement window is typically 1–5 minutes once OpenFX > broadcasts the transaction; the exact time depends on network congestion and > OpenFX's required confirmation count per chain. Gas spikes on Ethereum can > push confirmation past 10 minutes. > [accordion] Solana > > Submission is 24/7. Settlement typically completes within seconds of OpenFX > broadcasting the transaction. Network-level outages are rare but reflected > as an unsettled status until the cluster recovers. > [accordion] Tron > > Submission is 24/7. Settlement typically completes within 1–3 minutes once > OpenFX broadcasts the transaction, after the required confirmation count. > Stays unsettled until the confirmation threshold is reached. > [accordion] Aptos > > Submission is 24/7. Settlement typically completes within seconds to a > minute of OpenFX broadcasting the transaction. Stays unsettled until the > network finalizes the transaction. > [!TIP] > > **You don't pick a rail on the request.** The rail is bound to the [verified > withdrawal account](/v3/verified-accounts). Pull `GET > /v3/fx/withdrawal-accounts` to see which `withdrawalAccountId` targets which > rail; the same `currency` (e.g. USD) can map to either Fedwire or SWIFT > depending on how the account was set up. ## What's next > [card] [Withdrawals](/v3/withdrawals) > > State machine + polling pattern. > [card] [Supported networks](/v3/supported-networks) > > Stablecoin × chain matrix for crypto withdrawals. > [card] [Settlement models](/v3/settlement-models) > > The full deposit / balance / withdrawal model. > [card] [Idempotency](/v3/idempotency) > > 7-day TTL on withdrawal keys. # Trades Source: https://docs.openfx.com/v3/trades The trade state machine from execution to settlement or reversal: statuses, settlement windows, the settle and reverse actions, and the webhooks that report each change. A trade moves money between two of your currency balances at the rate locked in its quote. This page covers what happens after you [execute a trade](/v3/api-reference/trade/execute-trade): the statuses it passes through, what moves it forward, and the two actions you can take on it. How you request a rate and execute against it is on [Quotes](/v3/quotes). > [!NOTE] > > Funds move when a trade reaches EXECUTED, not > when you create it. A trade created with a T1 or > T2 window waits, and on a per-trade settlement > account it then waits for you. Read `status` before you assume a balance has > changed. ## Endpoints | Path | Description | Idempotency-Key | | - | - | - | | [`GET /v3/fx/trades/{id}`](/v3/api-reference/trade/get-trade) | Read a trade's current `status` | — | | [`GET /v3/fx/trades`](/v3/api-reference/trade/list-trades) | List trades, newest first | — | | [`POST /v3/fx/trades/{id}/settle`](/v3/api-reference/trade/settle-trade) | Finalize a manually settled trade | Required, 24-hr TTL | | [`POST /v3/fx/trades/{id}/reverse-quote`](/v3/api-reference/trade/generate-reverse-quote) | Preview the cost of unwinding a trade | Required, 30-min TTL | | [`POST /v3/fx/trades/{id}/reverse`](/v3/api-reference/trade/reverse-trade) | Unwind a trade against a reverse quote | Required, 24-hr TTL | ## State machine ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% stateDiagram-v2 direction TB [*] --> PENDING: POST /v3/fx/trades PENDING --> EXECUTED: IMMEDIATE, or T0 auto-settled PENDING --> LOCKED: T1 or T2 LOCKED --> EXECUTED: Window opens, auto-settled PENDING --> READY_TO_SETTLE: T0, manual settlement LOCKED --> READY_TO_SETTLE: Window opens, manual settlement READY_TO_SETTLE --> EXECUTED: POST .../settle READY_TO_SETTLE --> REVERSED: POST .../reverse EXECUTED --> [*] REVERSED --> [*] classDef ok stroke-width:1px classDef bad stroke-width:1px classDef pending stroke-width:1px classDef hold stroke-width:1px classDef returned stroke-width:1px classDef neutral stroke-width:1px class PENDING pending class LOCKED neutral class READY_TO_SETTLE hold class EXECUTED ok class REVERSED bad ``` `Trade.status` is a closed enum, and a trade ends in EXECUTED or REVERSED. | Status | Meaning | What moves it forward | | - | - | - | | PENDING | Created, funds not yet moved | OpenFX, immediately on execution | | LOCKED | A T1 or T2 trade before its settlement window opens | OpenFX, when the window opens | | READY_TO_SETTLE | A manually settled trade is awaiting settlement: from creation for a T0 trade, or once the window opens for T1 or T2 | You: [settle](#settle-a-trade) or [reverse](#reverse-a-trade) it | | EXECUTED | Funds have moved. Terminal | Nothing; the trade is complete | | REVERSED | A READY_TO_SETTLE trade was unwound. Terminal | Nothing; the reversal is its own trade | ## Settlement window Every trade carries a `settlementWindow` that you choose on the [quote request](/v3/api-reference/trade/create-quote): IMMEDIATE, T0, T1, or T2. It defaults to T0. > [!NOTE] > > In the live environment, T1 and T2 are currently available only for pairs of EUR or MXN against USD, USDC, or USDT, in either direction. For example, EUR/USD, USDC/EUR, MXN/USDT, and USD/MXN. The sandbox accepts all pairs. If you need T1 or T2 for another pair, reach out to your Customer Success representative or to [support@mail.openfx.com](mailto:support@mail.openfx.com). * IMMEDIATE trades settle synchronously, so the execute response already reads EXECUTED. * T0 trades are not future-dated. The window opens at execution. On an AUTO account the execute response already reads EXECUTED. On a MANUAL account it reads READY_TO_SETTLE until you settle or reverse the trade. * T1 and T2 trades are future-dated. They sit in LOCKED until the window opens: 24 market hours after execution for T1, and 48 for T2. Once a window opens, it stays open for 24 market hours: T0 from execution, T1 from 24 to 48 market hours after execution, and T2 from 48 to 72. The rate locks at execution for every window. The windows differ only in when they open. If you miss the window, the trade stays settleable at the locked rate, and the settlement terms of the trade apply. Contact your OpenFX account manager for those terms. Window timing runs on market hours. The clock follows the FX market week, which opens Sunday 5:00 PM and closes Friday 5:00 PM New York time. Hours while the market is closed, and major market holidays, do not count. A trade placed while the market is closed keeps its time of day and starts counting when the market reopens, so a T1 trade placed Friday morning opens on Monday. Do not compute window timing in your own code. Watch the trade `status` and the [trade webhooks](/v3/webhooks/trades/trade-ready-to-settle) instead. What happens at settlement depends on your organization's settlement model, an account-level setting rather than a request option. The `tradeSettlementMode` field holds it. | Mode | Model | At settlement | | - | - | - | | AUTO | Netted | The trade settles on its own and reaches EXECUTED. You take no action | | MANUAL | Per-trade | The trade reaches READY_TO_SETTLE and waits for you | IMMEDIATE trades never reach READY_TO_SETTLE, on either model, because they are already EXECUTED when the execute call returns. You can't settle or reverse them. On an AUTO account, an IMMEDIATE or T0 trade settles at execution even when your sell-side balance is short, and the shortfall counts against your [exposure limit](/v3/exposure). On a MANUAL account, execution returns TRADE_INSUFFICIENT_BALANCE unless the sell-side balance covers the trade, in every window. The models are compared on [Settlement models](/v3/settlement-models). ## Settle a trade Settling applies only to a trade in READY_TO_SETTLE on a MANUAL account. It completes the trade at the locked rate and populates `settledAt` and `settlementStartTime`. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/fx/trades/tde_5W7guYdHT24JFnRQrZN9y8/settle \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{}' ``` A successful response wraps a `TradeSettlement` in `data`. The trade is now EXECUTED: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "object": "trade", "id": "tde_5W7guYdHT24JFnRQrZN9y8", "quoteId": "qte_TmHeAhdFLes63uGgDjcJRx", "buyCurrency": "USDC", "sellCurrency": "USD", "sellAmount": "1000", "executedAmount": "999.25", "rate": "0.999250000000", "status": "EXECUTED", "clientReferenceId": "order-123", "createdAt": "2026-07-13T10:00:00.000Z", "settlementWindow": "T0", "settledAt": "2026-07-13T10:02:00.000Z", "settlementStartTime": "2026-07-13T10:00:30.000Z" } ``` | Error | Cause | | - | - | | `409` TRADE_NOT_MANUAL | The account settles automatically, so there is nothing to settle | | `409` TRADE_NOT_SETTLEABLE | The trade is already settled, not yet executed, or reversed. Read the trade, then decide | | `409` TRADE_ALREADY_SETTLED | The trade has already been settled | ## Reverse a trade A reversal unwinds a trade in READY_TO_SETTLE instead of settling it. It takes two calls, so you see the cost before you commit. **1. Generate a reverse quote** [`POST /v3/fx/trades/{id}/reverse-quote`](/v3/api-reference/trade/generate-reverse-quote) returns a time-limited quote. `quoteForSeconds` takes the same closed set of durations as a trade quote: 3, 15, 30, 45, or 60. As with trade quotes, holds longer than 15 seconds are priced higher to account for market volatility. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/fx/trades/tde_5W7guYdHT24JFnRQrZN9y8/reverse-quote \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "quoteForSeconds": 30 }' ``` Read `reversalDetails` before you act. `direction` says whether the reversal would DEBIT or CREDIT your balance, and `differentialAmount` is the unsigned magnitude in `currency`. ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "object": "quote", "id": "qte_TmHeAhdFLes63uGgDjcJRx", "buyCurrency": "USD", "sellCurrency": "USDC", "quoteAmount": "122.93850769", "rate": "1.00000000000", "createdAt": "2026-07-13T10:00:00.000Z", "expiresAt": "2026-07-13T10:00:30.000Z", "reversalDetails": { "direction": "DEBIT", "differentialAmount": "0.75", "currency": "USD" }, "buyAmount": "122.93850769" } ``` **2. Execute the reversal** [`POST /v3/fx/trades/{id}/reverse`](/v3/api-reference/trade/reverse-trade) names the reverse quote's `id` as `quoteId`. Send it before `expiresAt`. An optional `clientReferenceId` labels the reversal. ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/fx/trades/tde_5W7guYdHT24JFnRQrZN9y8/reverse \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "quoteId": "qte_TmHeAhdFLes63uGgDjcJRx", "clientReferenceId": "order-123-reversal" }' ``` The response is a new trade, created already EXECUTED. Its `originalTradeId` points at the trade it unwound, and the original trade reads REVERSED. ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "object": "trade", "id": "tde_8XvH7fKH8hcFyopFF2PFas", "quoteId": "qte_TmHeAhdFLes63uGgDjcJRx", "buyCurrency": "USD", "sellCurrency": "USDC", "buyAmount": "999.25", "executedAmount": "999.25", "rate": "1.00000000000", "status": "EXECUTED", "clientReferenceId": "order-123-reversal", "createdAt": "2026-07-13T10:00:00.000Z", "settlementWindow": "T0", "settlementStartTime": null, "originalTradeId": "tde_5W7guYdHT24JFnRQrZN9y8", "reversalDetails": { "direction": "CREDIT", "differentialAmount": "0.75", "currency": "USD" } } ``` A trade that is outside its reversal window, or already reversed or settled, returns `409` TRADE_NOT_REVERSIBLE. ## Track a trade Trade webhooks report each transition, so you don't need to poll. The three events map one-to-one onto the statuses a trade reaches under your own action or OpenFX's. | Webhook | Fires when | `data.status` | | - | - | - | | [fx.trade.ready_to_settle](/v3/webhooks/trades/trade-ready-to-settle) | A future-dated, manually settled trade reaches its window and awaits settle | READY_TO_SETTLE | | [fx.trade.settled](/v3/webhooks/trades/trade-settled) | A trade reaches EXECUTED, immediately or once settled | EXECUTED | | [fx.trade.reversed](/v3/webhooks/trades/trade-reversed) | A READY_TO_SETTLE trade is unwound | REVERSED | An AUTO account only receives fx.trade.settled. A MANUAL account can receive all three. The webhook `data` is close to the `Trade` resource but not identical. It adds `tradeSettlementMode` and `settledAt`, and on fx.trade.reversed it adds `reversalTradeId` and `reversalDetails`. `settledAt` is `null` on a reversal, because a reversal only ever unwinds a trade that was never settled. [Webhooks setup](/v3/webhooks/setup) covers delivery and signature verification. If you can't receive webhooks yet, poll [`GET /v3/fx/trades/{id}`](/v3/api-reference/trade/get-trade) and read `status`. ## Effect on balances and exposure A trade changes your [balances](/v3/balances) when it reaches EXECUTED. Read [`GET /v3/fx/balances`](/v3/api-reference/trade-settlement/list-balances) afterward; the trade response does not carry the balance impact. Before then, an open trade counts against your exposure limit. A LOCKED trade counts as `settlableLater` exposure and a READY_TO_SETTLE trade as `settlableNow`. See [Exposure](/v3/exposure#settlable-now-vs-settlable-later). ## Common mistakes * **Expecting EXECUTED from a future-dated trade.** A T1 or T2 trade returns before its window opens, so its funds have not moved. * **Calling settle on an automatic account.** It returns `409` TRADE_NOT_MANUAL. Netted accounts never settle by hand. * **Letting a reverse quote lapse.** The reversal must reach `POST /v3/fx/trades/{id}/reverse` before `expiresAt`; generate a new reverse quote with a new idempotency key. * **Reading the reversal as the original.** The reversal is a separate trade with its own `id`. Match it to the original through `originalTradeId`, or `reversalTradeId` on the webhook. * **Retrying a failed execution blind.** After TRADE_EXECUTION_FAILED, call `GET /v3/fx/trades/{id}` to check state first. ## What's next > [card] [Settlement models](/v3/settlement-models) > > Netted and per-trade settlement, side by side. > [card] [Balances](/v3/balances) > > What changes in each currency when a trade executes. > [card] [Trade webhooks](/v3/webhooks/trades/trade-ready-to-settle) > > Ready-to-settle, settled, and reversed events. > [card] [Exposure](/v3/exposure) > > Exposure-limit usage from trades that have not settled. # Verified accounts Source: https://docs.openfx.com/v3/verified-accounts Pre-configure your bank accounts and stablecoin wallets so withdrawals only need an `withdrawalAccountId` and a `withdrawalAmount`. A verified withdrawal account is a pre-approved bank account or stablecoin wallet that outgoing funds can settle to: fiat on a specific rail, or stablecoin on a specific chain. Every [`POST /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/create-withdrawal) call references one via `withdrawalAccountId`. The currency and rail or chain are bound to the withdrawal account at creation time, so the withdrawal call itself stays minimal. > [!WARNING] > > **Verified accounts are managed in the dashboard.** Creation, edits, and > removal happen in the [OpenFX dashboard](https://app.openfx.com). Your > integration **reads** the resulting accounts via the API and references them > by `id` on withdrawal requests. ## Why verify * **Risk.** Withdrawal accounts are reviewed before they go live, so a compromised JWT can't send funds to a wallet you've never approved. * **Simplicity.** Withdrawals don't need bank details, beneficiary names, IBANs, or chain identifiers on every call. That's all pinned to the account record. * **Auditability.** Every dispatched withdrawal traces back to a specific `withdrawalAccountId`, which traces back to the human who approved it. > [!NOTE] > > **Each verified account = one address × one network × one asset.** If you want to withdraw USDC **and** USDT to the same Ethereum address, you must add **two** records: one per `(address, network, asset)` tuple. Likewise, the same address on Ethereum mainnet vs Polygon is two separate records. > > **Why the constraint exists.** Customers funded via exchanges often don't control the same nominal address across all chains, and some exchanges issue different deposit addresses per token even on the same chain. Forcing an explicit per-tuple add prevents a withdrawal landing at an address that doesn't actually receive the asset on that chain: a class of permanent loss. If you self-custody and the same address works for every chain × asset, you still add each tuple explicitly. ## Add an account (dashboard) **1. Sign in to the dashboard** Go to [your accounts](https://app.openfx.com/your-accounts/accounts) if you have admin access. Withdrawal account management is gated to admins. **2. Pick an account type** **Fiat bank account** (API `assetType: "FIAT"`) for a wire, SEPA, SPEI, or similar rail, or **stablecoin wallet** (API `assetType: "CRYPTO"`) for an on-chain account. **3. Enter the account details** **For fiat**: currency, beneficiary name, account number / IBAN, routing number / BIC, and the rail you want OpenFX to dispatch over. The selectable rails depend on the currency (e.g. USD shows Fedwire and SWIFT; EUR shows SEPA, SEPA Instant, and SWIFT). **For stablecoin**: token (USDC, USDT, EURC), the chain (one of the [supported networks](/v3/supported-networks)), and the wallet address. The address must match the chain's format. Solana addresses are not interchangeable with Ethereum addresses. **4. Attach supporting documents** Upload up to **3 files, 10 MB each**. For fiat accounts, attach bank statements or beneficiary-ownership documents. For stablecoin wallets, attach proof of address control (signed message, exchange screenshot, or similar). Documents stay in the dashboard. The API never returns them. **5. Submit for review** Every submission passes a two-step gate before going live: * **Compliance**: AML screening, plus on-chain TRM screening for stablecoin wallets. * **Ops**: bank-detail validation and beneficiary-ownership review. Both gates must clear before the account becomes active. The listing on [`GET /v3/fx/withdrawal-accounts`](/v3/api-reference/trade-settlement/list-withdrawal-accounts) includes accounts in every status (PENDING, ACTIVE, ARCHIVED, REJECTED, DEACTIVATED, ADDITIONAL_ACTION_NEEDED) by default; pass `?status=ACTIVE` (or filter client-side) based on your flow. Only ACTIVE accounts accept withdrawals. Submitting against any other status returns an error. > [!NOTE] > > `GET /v3/fx/withdrawal-accounts` supports `?status=` (plus `?assetType=`, `?currency=`, `?network=`, `?rail=`, and `?verified=`) as server-side filters. Filter to ACTIVE (via the query parameter or client-side) before posting withdrawals. > [!NOTE] > > **Duplicates are rejected at submission.** Two records with the same rail, > currency, and account number (or wallet address) cannot coexist. If a > withdrawal account is already on file, edit the existing record instead of > resubmitting. ## Read accounts via the API Once approved, accounts appear on [`GET /v3/fx/withdrawal-accounts`](/v3/api-reference/trade-settlement/list-withdrawal-accounts). ```javascript Node theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Reads verified withdrawal accounts and picks the right one for a // withdrawal — the pattern from /v3/verified-accounts#read-accounts-via-the-api. // signRequest is the real helper from /v3/authentication — adjust this path // if you've copied it somewhere else in your own project. const { signRequest } = require("../../authentication/node/sign-request"); // Picks the crypto withdrawal account for a currency + chain. Kept separate // from the network call so it's testable without a real request. function findAccount(accounts, currency, network) { return accounts.find((a) => a.currency === currency && a.network === network); } async function listAccounts() { const url = "https://api.openfx.com/v3/fx/withdrawal-accounts"; const { headers } = signRequest({ method: "GET", url }); const res = await fetch(url, { headers }); const { data } = await res.json(); return data; } module.exports = { findAccount, listAccounts }; if (require.main === module) { listAccounts() .then((accounts) => { const usdcOnSolana = findAccount(accounts, "USDC", "SOLANA"); console.log(usdcOnSolana); }) .catch((err) => { console.error("Error:", err.message); process.exitCode = 1; }); } ``` ```python Python theme={"theme":{"light":"poimandres","dark":"poimandres"}} """Reads verified withdrawal accounts and picks the right one for a withdrawal — the pattern from /v3/verified-accounts#read-accounts-via-the-api.""" import os import sys # sign_request is the real helper from /v3/authentication — adjust this path # if you've copied it somewhere else in your own project. sys.path.insert( 0, os.path.join(os.path.dirname(__file__), "..", "..", "authentication", "python") ) from sign_request import sign_request # noqa: E402 import requests # noqa: E402 def find_account(accounts, currency, network): """Picks the crypto withdrawal account for a currency + chain. Kept separate from the network call so it's testable without a real request.""" return next((a for a in accounts if a["currency"] == currency and a["network"] == network), None) def list_accounts(): url = "https://api.openfx.com/v3/fx/withdrawal-accounts" headers, _ = sign_request("GET", url) res = requests.get(url, headers=headers) return res.json()["data"] if __name__ == "__main__": accounts = list_accounts() print(find_account(accounts, "USDC", "SOLANA")) ``` ```java Java theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Reads verified withdrawal accounts and picks the right one for a // withdrawal — the pattern from // /v3/verified-accounts#read-accounts-via-the-api. import java.net.HttpURLConnection; import java.net.URI; import java.util.List; import java.util.Map; public class FindAccount { static class Account { final String id; final String currency; final String network; Account(String id, String currency, String network) { this.id = id; this.currency = currency; this.network = network; } } // Picks the crypto withdrawal account for a currency + chain. Kept // separate from the network call so it's testable without a real request. static Account findAccount(List accounts, String currency, String network) { for (Account a : accounts) { if (a.currency.equals(currency) && a.network.equals(network)) return a; } return null; } static List listAccounts() throws Exception { String url = "https://api.openfx.com/v3/fx/withdrawal-accounts"; // SignRequest is the real helper from /v3/authentication, compiled // on the classpath alongside this file — see that page's example. Map headers = SignRequest.signRequest("GET", url, new byte[0]); HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection(); conn.setRequestMethod("GET"); for (Map.Entry h : headers.entrySet()) { conn.setRequestProperty(h.getKey(), h.getValue()); } conn.getResponseCode(); // A real implementation would parse the JSON response body's `data` // array here. return List.of(); } public static void main(String[] args) throws Exception { List accounts = listAccounts(); System.out.println(findAccount(accounts, "USDC", "SOLANA")); } } ``` ```cpp C++ theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Reads verified withdrawal accounts and picks the right one for a // withdrawal — the pattern from // /v3/verified-accounts#read-accounts-via-the-api. Requires // OpenSSL and libcurl. #include #include #include #include // Matches the definition in ../../authentication/cpp/sign_request.cpp, // compiled together with this file — see that file for the real // implementation of signRequest. struct SignedRequest { std::string authHeader; std::string sigHeader; }; SignedRequest signRequest(const std::string& method, const std::string& urlPath, const std::string& query, const std::string& body); struct Account { std::string id; std::string currency; std::string network; }; // Picks the crypto withdrawal account for a currency + chain. Kept separate // from the network call so it's testable without a real request. std::optional findAccount(const std::vector& accounts, const std::string& currency, const std::string& network) { for (const auto& a : accounts) { if (a.currency == currency && a.network == network) return a; } return std::nullopt; } static size_t discard(char*, size_t s, size_t n, void*) { return s * n; } std::vector listAccounts() { std::string url = "https://api.openfx.com/v3/fx/withdrawal-accounts"; SignedRequest req = signRequest("GET", "/v3/fx/withdrawal-accounts", "", ""); CURL* curl = curl_easy_init(); curl_slist* headers = nullptr; headers = curl_slist_append(headers, ("Authorization: " + req.authHeader).c_str()); headers = curl_slist_append(headers, ("X-Request-Signature: " + req.sigHeader).c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, discard); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); // A real implementation would parse the JSON response body's `data` // array here. return {}; } #ifndef FIND_ACCOUNT_NO_MAIN #include int main() { try { auto accounts = listAccounts(); auto account = findAccount(accounts, "USDC", "SOLANA"); std::cout << (account ? account->id : "not found") << std::endl; return 0; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } #endif ``` ```go Go theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Reads verified withdrawal accounts and picks the right one for a // withdrawal — the pattern from // /v3/verified-accounts#read-accounts-via-the-api. package main import ( "encoding/json" "fmt" "net/http" // auth is the real signRequest helper from /v3/authentication — see // go.mod's replace directive if you've copied it somewhere else. auth "openfx-v3-authentication-example" ) type Account struct { ID string `json:"id"` Currency string `json:"currency"` Network string `json:"network"` } // Picks the crypto withdrawal account for a currency + chain. Kept separate // from the network call so it's testable without a real request. func findAccount(accounts []Account, currency, network string) *Account { for _, a := range accounts { if a.Currency == currency && a.Network == network { return &a } } return nil } func listAccounts() ([]Account, error) { url := "https://api.openfx.com/v3/fx/withdrawal-accounts" signed, err := auth.SignRequest("GET", url, nil) if err != nil { return nil, err } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, v := range signed.Headers { req.Header.Set(k, v) } res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() var envelope struct { Data []Account `json:"data"` } if err := json.NewDecoder(res.Body).Decode(&envelope); err != nil { return nil, err } return envelope.Data, nil } func main() { accounts, err := listAccounts() if err != nil { fmt.Println("Error:", err) return } fmt.Println(findAccount(accounts, "USDC", "SOLANA")) } ``` ```bash cURL theme={"theme":{"light":"poimandres","dark":"poimandres"}} #!/usr/bin/env bash # Reads verified withdrawal accounts and picks the right one for a # withdrawal — the pattern from # /v3/verified-accounts#read-accounts-via-the-api. Illustrative # only: cURL can't compute the ES256 request signature itself, so # $OPENFX_JWT/$OPENFX_SIGNATURE below are placeholders — get real values # from signRequest, in any supported language, via /v3/authentication. # X-App-Mode is hard-coded to SANDBOX below. To target Live, use a Live API # key (mint the JWT from it) and set X-App-Mode to LIVE. set -euo pipefail export OPENFX_JWT="" export OPENFX_SIGNATURE="" ACCOUNTS=$(curl -s https://api.openfx.com/v3/fx/withdrawal-accounts \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "X-App-Mode: SANDBOX") # Picks the crypto withdrawal account for a currency + chain. Filtering an # array by two fields needs real JSON parsing, unlike the single-field # extraction elsewhere in these examples. This is the one place these # scripts use jq (https://jqlang.org), not a hand-rolled pattern match. echo "$ACCOUNTS" | jq '.data[] | select(.currency == "USDC" and .network == "SOLANA")' ``` A typical response, with a fiat row and a stablecoin row, looks like: ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "data": [ { "object": "withdrawalAccount", "id": "wac_NDqQ9LmcUASpnHR6CTvdkk", "assetType": "FIAT", "network": null, "rail": "FEDWIRE", "displayName": "Acme USD Reserves", "currency": "USD", "status": "ACTIVE", "verified": true, "creatorId": "usr_7m4VsfRw4pGrS76WYj5tnx", "destination": { "accountName": "Acme Reserves LLC", "accountNumber": "1234564321", "bankName": "JPMorgan Chase", "routingNumber": "021000021" }, "createdAt": "2026-05-19T10:00:00.000Z", "updatedAt": "2026-05-19T10:00:00.000Z" }, { "object": "withdrawalAccount", "id": "wac_7yE2Xr4vTqK9mB3sN6pW1", "assetType": "CRYPTO", "network": "SOLANA", "rail": null, "displayName": "Treasury USDC wallet", "currency": "USDC", "status": "ACTIVE", "verified": true, "creatorId": "usr_7m4VsfRw4pGrS76WYj5tnx", "destination": { "address": "5xZ8KqM3vN9pT4hR2bF7jL1wA6cD8eY5sU3xZ0q9Pn" }, "createdAt": "2026-05-19T10:00:00.000Z", "updatedAt": "2026-05-19T10:00:00.000Z" } ], "pagination": { "limit": 100, "hasNext": false, "nextCursor": null, "hasPrev": false, "prevCursor": null } } ``` Crypto accounts carry `network` (the chain, e.g. SOLANA) with a `null` `rail`; fiat accounts carry `rail` (one of SWIFT, FEDWIRE, FPS, or another local rail) with a `null` `network`. `network` determines the shape of `destination` for crypto (`destination.address`); `rail` does for fiat (`destination.accountName` / `accountNumber` / `bankName`, plus rail-specific fields like `swiftCode`, `routingNumber`, or `ukSortCode`). See the `WithdrawalAccount` schema in the [API reference](/v3/api-reference/trade-settlement/list-withdrawal-accounts) for the full per-rail shape. > [!TIP] > > **Cache the account list, not the JWT.** Account membership changes on the > order of days; tokens change every 60 seconds (and every request also carries > a fresh `X-Request-Signature`). Pull `withdrawal_accounts` once at startup (or > once per request when you need fresh state); don't ride a stale cache across > new dashboard approvals. ## Use the `withdrawalAccountId` on a withdrawal ```bash theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl -X POST https://api.openfx.com/v3/fx/withdrawals \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "withdrawalAccountId": "a2c7d4f1-3b18-4f6a-9c35-2e8a1b4d9f02", "withdrawalAmount": "1000.00", "currency": "USDC" }' ``` The `currency` on the withdrawal must match the account's `currency`. The chain (for stablecoin) or rail (for fiat) is **not** on the request. Both are inferred from `withdrawalAccountId`. ## Lifecycle and changes * **Locked fields.** Once an account is ACTIVE, the account number (or wallet address), rail or chain, and currency are locked. Changing any of them means creating a new account and re-running the two-step review. * **Editable fields.** The **display name** (and a dashboard memo) can be edited without re-verification. The API returns the latest `displayName` on the next read. * **Archiving.** Archive an account from the dashboard; the `id` stops accepting withdrawals immediately once `status` reads ARCHIVED. In-flight withdrawals against a now-archived account complete normally. * **Unarchiving.** Unarchive the same `id` to bring it back; the UUID is stable, so no new account or `id` is created. The dashboard is the **source of truth** for submission status, document history, and review-gate outcomes. The API returns the full account details nested under `destination` on the ACTIVE record; document attachments live in the dashboard. ## Common mistakes * **Verifying a Polygon address and assuming USDC is fungible across chains.** A USDC withdrawal initiated against a Polygon `withdrawalAccountId` will only ever settle on Polygon. There is no cross-chain bridge inside OpenFX. See [Supported networks](/v3/supported-networks). * **Picking the wrong rail for a fiat withdrawal account.** Fedwire vs SWIFT, or FPS vs SWIFT: these have different cut-offs, fee profiles, and value limits. The rail is fixed at account creation; pick it deliberately. CHAPS is a settlement route that OpenFX chooses, not a rail you select. See [Settlement times](/v3/settlement-times). * **Polling the API for full review status.** The API surfaces a `status` (PENDING, ACTIVE, ARCHIVED, REJECTED, DEACTIVATED, ADDITIONAL_ACTION_NEEDED) but does not expose document follow-up state, reviewer notes, or rejection reasons. For full review status, check the dashboard. ## What's next > [card] [Settlement models](/v3/settlement-models) > > How balances, deposits, and withdrawals interact. > [card] [Settlement times](/v3/settlement-times) > > Per-rail cut-offs for fiat withdrawal accounts. > [card] [Supported networks](/v3/supported-networks) > > Per-chain support for stablecoin withdrawal accounts. > [card] [Webhooks setup](/v3/webhooks/setup) > > Receive `withdrawals` events for your withdrawal accounts. # Webhook authentication Source: https://docs.openfx.com/v3/webhooks/authentication Timestamped HMAC-SHA256 signatures in `X-OpenFX-Signature`. Verify every event server-side with a constant-time comparison and a replay window. Every webhook delivery is signed with **HMAC-SHA256** over a timestamp-prefixed payload, using your organization's webhook signing secret. The signature is delivered in the `X-OpenFX-Signature` header, alongside the timestamp it was computed with. Verify both the signature and the timestamp's age on every event before trusting the payload. ## Signature header format The `X-OpenFX-Signature` header carries two comma-separated `key=value` fields: `t`, the Unix timestamp (seconds) the signature was computed at, and `v1`, the hex-encoded HMAC-SHA256 digest: ```http theme={"theme":{"light":"poimandres","dark":"poimandres"}} X-OpenFX-Signature: t=,v1= ``` ```text theme={"theme":{"light":"poimandres","dark":"poimandres"}} signed_payload = "{timestamp}.{raw_body}" v1 = hex(HMAC_SHA256(signed_payload, signing_secret)) ``` The timestamp is concatenated with the raw body using a literal `.` separator before hashing. Including it in the signed payload (not just alongside it) means an attacker who captures a valid delivery can't replay it later with a different `t`. The timestamp is authenticated, not just present. Each delivery also carries an **`X-Trace-Id`** header containing an opaque trace identifier. Include this value when contacting support to help correlate deliveries in our logs. ## How verification works **1. Capture the raw request body** Read the body as the exact bytes you received it. Do **not** parse-then-reserialize JSON. Whitespace and key ordering matter, and a re-serialized body will not match the signature. **2. Parse the signature header** Split `X-OpenFX-Signature` on `,` and each part on `=` to recover `t` and `v1`. Reject the delivery if either field is missing. **3. Reject stale timestamps** Reject if `|now - t| > 300` seconds (5 minutes). This bounds how long a captured delivery remains replayable, so clock drift beyond a few minutes between your server and OpenFX will start rejecting legitimate deliveries. Keep your server clock synced (NTP). **4. Compute the expected HMAC** Run `HMAC_SHA256("{t}.{raw_body}", signing_secret)` and hex-encode the digest. The signing secret is the value labeled `Signing key` in your dashboard webhook settings. **5. Compare in constant time** Compare your computed digest against `v1` using a **constant-time** comparator. Naive `==` / `===` comparison is timing-attack-vulnerable. **6. Reject on mismatch** Respond with `401 Unauthorized` (or `400 Bad Request`) and do **not** call your handler. Never trust the payload before both the timestamp and signature check succeed. ## Verification samples ```javascript Node theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Verifies the timestamped HMAC-SHA256 signature OpenFX attaches to every // webhook delivery in X-OpenFX-Signature, per the pattern from // /v3/webhooks/authentication#how-verification-works. const crypto = require("node:crypto"); const TOLERANCE_SECONDS = 300; // Mints the signature OpenFX's server would attach: t=, // v1= over "{timestamp}.{raw_body}". Only used here to produce a // realistic round-trip demo. You never compute this yourself against real // deliveries, only verify what you received. function signPayload( rawBody, signingSecret, timestamp = Math.floor(Date.now() / 1000), ) { const hmac = crypto .createHmac("sha256", signingSecret) .update(`${timestamp}.${rawBody}`) .digest("hex"); return `t=${timestamp},v1=${hmac}`; } // Splits "t=,v1=" into { timestamp, hmac }, or null if either field // is missing. function parseSignatureHeader(signatureHeader) { const fields = Object.fromEntries( (signatureHeader || "") .split(",") .map((part) => part.split("=")) .filter(([key, value]) => key && value), ); if (!fields.t || !fields.v1) return null; return { timestamp: Number(fields.t), hmac: fields.v1 }; } // Verifies a delivery: reject a stale timestamp, then recompute the HMAC // over "{timestamp}.{raw_body}" and compare it against v1 in constant time. function isValidSignature( rawBody, signatureHeader, signingSecret, now = Math.floor(Date.now() / 1000), ) { const parsed = parseSignatureHeader(signatureHeader); if (!parsed) return false; const { timestamp, hmac } = parsed; if ( !Number.isFinite(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS ) { return false; } const expected = crypto .createHmac("sha256", signingSecret) .update(`${timestamp}.${rawBody}`) .digest("hex"); // Constant-time comparison. Buffer lengths must match. const a = Buffer.from(hmac); const b = Buffer.from(expected); return a.length === b.length && crypto.timingSafeEqual(a, b); } module.exports = { signPayload, isValidSignature }; if (require.main === module) { const signingSecret = "docs_demo_secret"; const rawBody = JSON.stringify({ id: "evt_123", type: "deposits" }); const signature = signPayload(rawBody, signingSecret); console.log("X-OpenFX-Signature:", signature); console.log("valid:", isValidSignature(rawBody, signature, signingSecret)); } ``` ```python Python theme={"theme":{"light":"poimandres","dark":"poimandres"}} """Verifies the timestamped HMAC-SHA256 signature OpenFX attaches to every webhook delivery in X-OpenFX-Signature, per the pattern from /v3/webhooks/authentication#how-verification-works.""" import hashlib import hmac import time TOLERANCE_SECONDS = 300 def sign_payload(raw_body: str, signing_secret: str, timestamp: int = None) -> str: """Mints the signature OpenFX's server would attach: t=, v1= over "{timestamp}.{raw_body}". Only used here to produce a realistic round-trip demo. You never compute this yourself against real deliveries, only verify what you received.""" if timestamp is None: timestamp = int(time.time()) signed_payload = f"{timestamp}.{raw_body}" digest = hmac.new(signing_secret.encode("utf-8"), signed_payload.encode("utf-8"), hashlib.sha256).hexdigest() return f"t={timestamp},v1={digest}" def _parse_signature_header(signature_header: str): """Splits "t=,v1=" into (timestamp, hmac), or None if either field is missing.""" fields = {} for part in (signature_header or "").split(","): if "=" not in part: continue key, _, value = part.partition("=") if key and value: fields[key] = value if "t" not in fields or "v1" not in fields: return None try: return int(fields["t"]), fields["v1"] except ValueError: return None def is_valid_signature( raw_body: str, signature_header: str, signing_secret: str, now: int = None ) -> bool: """Verifies a delivery: reject a stale timestamp, then recompute the HMAC over "{timestamp}.{raw_body}" and compare it against v1 in constant time.""" if now is None: now = int(time.time()) parsed = _parse_signature_header(signature_header) if parsed is None: return False timestamp, received_hmac = parsed if abs(now - timestamp) > TOLERANCE_SECONDS: return False signed_payload = f"{timestamp}.{raw_body}" expected = hmac.new(signing_secret.encode("utf-8"), signed_payload.encode("utf-8"), hashlib.sha256).hexdigest() # Constant-time comparison return hmac.compare_digest(received_hmac, expected) if __name__ == "__main__": import json signing_secret = "docs_demo_secret" raw_body = json.dumps({"id": "evt_123", "type": "deposits"}) signature = sign_payload(raw_body, signing_secret) print("X-OpenFX-Signature:", signature) print("valid:", is_valid_signature(raw_body, signature, signing_secret)) ``` ```java Java theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Verifies the timestamped HMAC-SHA256 signature OpenFX attaches to every // webhook delivery in X-OpenFX-Signature, per the pattern from // /v3/webhooks/authentication#how-verification-works. Uses only the // built-in JDK APIs, no external dependency. import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.HexFormat; import java.util.Map; public class VerifySignature { static final long TOLERANCE_SECONDS = 300; // Mints the signature OpenFX's server would attach: t=, // v1= over "{timestamp}.{raw_body}". Only used here to // produce a realistic round-trip demo. You never compute this // yourself against real deliveries, only verify what you received. static String signPayload(String rawBody, String signingSecret, long timestamp) throws Exception { String hmacHex = hmacHex(timestamp + "." + rawBody, signingSecret); return "t=" + timestamp + ",v1=" + hmacHex; } static String signPayload(String rawBody, String signingSecret) throws Exception { return signPayload(rawBody, signingSecret, System.currentTimeMillis() / 1000); } static String hmacHex(String message, String signingSecret) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(signingSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] hmacBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8)); return HexFormat.of().formatHex(hmacBytes); } // Splits "t=,v1=" into its fields, or null if either is missing. static Map parseSignatureHeader(String signatureHeader) { if (signatureHeader == null) return null; Map fields = new java.util.HashMap<>(); for (String part : signatureHeader.split(",")) { String[] kv = part.split("=", 2); if (kv.length == 2 && !kv[0].isEmpty() && !kv[1].isEmpty()) { fields.put(kv[0], kv[1]); } } if (!fields.containsKey("t") || !fields.containsKey("v1")) return null; return fields; } // Verifies a delivery: reject a stale timestamp, then recompute the // HMAC over "{timestamp}.{raw_body}" and compare it against v1 in // constant time. static boolean isValidSignature(String rawBody, String signatureHeader, String signingSecret, long now) throws Exception { Map parsed = parseSignatureHeader(signatureHeader); if (parsed == null) return false; long timestamp; try { timestamp = Long.parseLong(parsed.get("t")); } catch (NumberFormatException e) { return false; } if (Math.abs(now - timestamp) > TOLERANCE_SECONDS) return false; String expected = hmacHex(timestamp + "." + rawBody, signingSecret); // MessageDigest.isEqual is constant-time return MessageDigest.isEqual( parsed.get("v1").getBytes(StandardCharsets.UTF_8), expected.getBytes(StandardCharsets.UTF_8)); } static boolean isValidSignature(String rawBody, String signatureHeader, String signingSecret) throws Exception { return isValidSignature(rawBody, signatureHeader, signingSecret, System.currentTimeMillis() / 1000); } public static void main(String[] args) throws Exception { String signingSecret = "docs_demo_secret"; String rawBody = "{\"id\":\"evt_123\",\"type\":\"deposits\"}"; String signature = signPayload(rawBody, signingSecret); System.out.println("X-OpenFX-Signature: " + signature); System.out.println("valid: " + isValidSignature(rawBody, signature, signingSecret)); } } ``` ```cpp C++ theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Verifies the timestamped HMAC-SHA256 signature OpenFX attaches to every // webhook delivery in X-OpenFX-Signature, per the pattern from // /v3/webhooks/authentication#how-verification-works. Requires OpenSSL. #include #include #include #include #include #include namespace { constexpr long long kToleranceSeconds = 300; std::string hmacHex(const std::string& message, const std::string& signingSecret) { unsigned char digest[EVP_MAX_MD_SIZE]; unsigned int digestLen = 0; HMAC(EVP_sha256(), signingSecret.data(), static_cast(signingSecret.size()), reinterpret_cast(message.data()), message.size(), digest, &digestLen); static const char* kHex = "0123456789abcdef"; std::string hex(digestLen * 2, '0'); for (unsigned int i = 0; i < digestLen; i++) { hex[2 * i] = kHex[(digest[i] >> 4) & 0xF]; hex[2 * i + 1] = kHex[digest[i] & 0xF]; } return hex; } } // namespace // Mints the signature OpenFX's server would attach: t=, // v1= over "{timestamp}.{raw_body}". Only used here to produce a // realistic round-trip demo. You never compute this yourself against real // deliveries, only verify what you received. std::string signPayload(const std::string& rawBody, const std::string& signingSecret, long long timestamp) { std::string signedPayload = std::to_string(timestamp) + "." + rawBody; return "t=" + std::to_string(timestamp) + ",v1=" + hmacHex(signedPayload, signingSecret); } // Constant-time comparison avoids leaking timing information about // where two strings first differ. static bool constantTimeEquals(const std::string& a, const std::string& b) { if (a.size() != b.size()) return false; unsigned char diff = 0; for (size_t i = 0; i < a.size(); i++) diff |= static_cast(a[i]) ^ static_cast(b[i]); return diff == 0; } // Splits "t=,v1=" into its fields. Returns false if either field is // missing or the timestamp doesn't parse. static bool parseSignatureHeader(const std::string& signatureHeader, long long& timestamp, std::string& hmac) { std::string t, v1; std::stringstream stream(signatureHeader); std::string part; while (std::getline(stream, part, ',')) { size_t eq = part.find('='); if (eq == std::string::npos || eq == 0 || eq == part.size() - 1) continue; std::string key = part.substr(0, eq); std::string value = part.substr(eq + 1); if (key == "t") t = value; if (key == "v1") v1 = value; } if (t.empty() || v1.empty()) return false; char* end = nullptr; timestamp = std::strtoll(t.c_str(), &end, 10); if (end == t.c_str() || *end != '\0') return false; hmac = v1; return true; } // Verifies a delivery: reject a stale timestamp, then recompute the HMAC // over "{timestamp}.{raw_body}" and compare it against v1 in constant time. bool isValidSignature(const std::string& rawBody, const std::string& signatureHeader, const std::string& signingSecret, long long now) { long long timestamp = 0; std::string receivedHmac; if (!parseSignatureHeader(signatureHeader, timestamp, receivedHmac)) return false; long long diff = now - timestamp; if (diff > kToleranceSeconds || diff < -kToleranceSeconds) return false; std::string signedPayload = std::to_string(timestamp) + "." + rawBody; std::string expected = hmacHex(signedPayload, signingSecret); return constantTimeEquals(receivedHmac, expected); } #ifndef VERIFY_SIGNATURE_NO_MAIN #include #include int main() { std::string signingSecret = "docs_demo_secret"; std::string rawBody = R"({"id":"evt_123","type":"deposits"})"; long long now = static_cast(std::time(nullptr)); std::string signature = signPayload(rawBody, signingSecret, now); std::cout << "X-OpenFX-Signature: " << signature << std::endl; std::cout << "valid: " << (isValidSignature(rawBody, signature, signingSecret, now) ? "true" : "false") << std::endl; return 0; } #endif ``` ```go Go theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Verifies the timestamped HMAC-SHA256 signature OpenFX attaches to every // webhook delivery in X-OpenFX-Signature, per the pattern from // /v3/webhooks/authentication#how-verification-works. package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "strconv" "strings" "time" ) const toleranceSeconds = 300 // Mints the signature OpenFX's server would attach: t=, // v1= over "{timestamp}.{raw_body}". Only used here to produce a // realistic round-trip demo. You never compute this yourself against real // deliveries, only verify what you received. func signPayload(rawBody, signingSecret string, timestamp int64) string { signedPayload := fmt.Sprintf("%d.%s", timestamp, rawBody) mac := hmac.New(sha256.New, []byte(signingSecret)) mac.Write([]byte(signedPayload)) return fmt.Sprintf("t=%d,v1=%s", timestamp, hex.EncodeToString(mac.Sum(nil))) } // parseSignatureHeader splits "t=,v1=" into its fields. ok is false // if either field is missing or the timestamp doesn't parse. func parseSignatureHeader(signatureHeader string) (timestamp int64, hmacHex string, ok bool) { fields := map[string]string{} for _, part := range strings.Split(signatureHeader, ",") { key, value, found := strings.Cut(part, "=") if found && key != "" && value != "" { fields[key] = value } } t, hasT := fields["t"] v1, hasV1 := fields["v1"] if !hasT || !hasV1 { return 0, "", false } parsed, err := strconv.ParseInt(t, 10, 64) if err != nil { return 0, "", false } return parsed, v1, true } // Verifies a delivery: reject a stale timestamp, then recompute the HMAC // over "{timestamp}.{raw_body}" and compare it against v1 in constant time. func isValidSignature(rawBody, signatureHeader, signingSecret string, now int64) bool { timestamp, receivedHmac, ok := parseSignatureHeader(signatureHeader) if !ok { return false } if diff := now - timestamp; diff > toleranceSeconds || diff < -toleranceSeconds { return false } signedPayload := fmt.Sprintf("%d.%s", timestamp, rawBody) mac := hmac.New(sha256.New, []byte(signingSecret)) mac.Write([]byte(signedPayload)) expected := hex.EncodeToString(mac.Sum(nil)) // hmac.Equal is constant-time return hmac.Equal([]byte(receivedHmac), []byte(expected)) } func main() { signingSecret := "docs_demo_secret" rawBody := `{"id":"evt_123","type":"deposits"}` now := time.Now().Unix() signature := signPayload(rawBody, signingSecret, now) fmt.Println("X-OpenFX-Signature:", signature) fmt.Println("valid:", isValidSignature(rawBody, signature, signingSecret, now)) } ``` > [!NOTE] > > **Reading the raw body:** every framework that does JSON body parsing before your handler runs is a footgun. In Express, use `express.raw({ type: 'application/json' })`; in Flask, `request.get_data()` before any `.get_json()`; in Go, read `r.Body` before the framework consumes it. The raw bytes are not optional. ## Where the signing key comes from * **Live:** download from the dashboard webhook settings. * **Sandbox:** download separately from the Sandbox dashboard. * **Rotation:** generate the new key, deploy your verifier to accept both old and new for at least one delivery cycle (allowing in-flight deliveries to clear), then revoke the old. Treat the key like a Live credential: store in a secrets manager, never check into source. > [!WARNING] > > **Sandbox and Live signing keys are different.** A handler using the wrong > environment's key will reject every event. Wire the key from environment-aware > config, not a hard-coded constant. ## Additional delivery headers | Header | Description | | - | - | | `X-OpenFX-Signature` | `t=,v1=`: a hex-encoded HMAC-SHA256 of `{timestamp}.{raw_body}`, plus the timestamp it covers. Verify both the timestamp's age and the signature on every delivery. | | `X-OpenFX-Webhook-Version` | Webhook payload contract version, currently `v3`. Lets your handler branch if the envelope shape changes in a future major version. | | `X-Trace-Id` | Opaque trace identifier for this delivery. Include when contacting support for delivery-level debugging. | | `Content-Type` | Always `application/json`. | ## Common mistakes * **Parsing then re-serializing the body before computing the HMAC.** Whitespace and key ordering differ; the signature will never match. Capture the raw bytes first. * **Using `==` / `===` for comparison.** Timing-attack-vulnerable. Use `crypto.timingSafeEqual` (Node), `hmac.compare_digest` (Python), `hmac.Equal` (Go), `MessageDigest.isEqual` (Java), a manually constant-time byte comparison (C++, which has no built-in one). * **Hex vs base64 decoding.** The `v1` value is **hex-encoded**; do not base64-decode it. * **Hashing the raw body alone.** The signed payload is `{timestamp}.{raw_body}`, not the raw body by itself. Reusing the pre-timestamp formula produces a digest that never matches `v1`. * **Skipping the timestamp check.** Verifying `v1` without checking `|now - t| > 300` accepts a captured delivery replayed at any point in the future. Both checks are required. * **Confusing the API key with the webhook signing secret.** They are two different secrets, both downloadable from the dashboard. The webhook signing secret does not appear in any API request. It only signs deliveries to you. * **Trusting payload contents before signature verification.** Reject unsigned or mis-signed events with a 401 before reading any field of the body. * **Assuming signature verification also dedups redeliveries.** It doesn't. Each retry carries a fresh timestamp, so it produces its own valid signature rather than repeating the original. Dedup on the event `id` separately; see [Common mistakes](/v3/webhooks/setup#common-mistakes) on the setup page. ## What's next > [card] [Deposit webhooks](/v3/webhooks/deposits/deposit-completed) > > Event shape for fiat and stablecoin deposits. > [card] [Withdrawal webhooks](/v3/webhooks/withdrawals/withdrawal-completed) > > Event shape for withdrawals, including the typed `settlement` receipt on > completed wires. > [card] [Payout webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Event shape for payout status changes. > [card] [Deposits](/v3/deposits) > > How deposits transition from pending to completed. > [card] [Withdrawals](/v3/withdrawals) > > How withdrawals move from PENDING to COMPLETED or CANCELLED. # Deposit completed Source: https://docs.openfx.com/v3/webhooks/deposits/deposit-completed api-reference/openapi-v3.json webhook fx.deposit.completed A fiat or stablecoin deposit reaches `COMPLETED` and is credited to your balance. # Account activated Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-activated api-reference/openapi-v3-payments.json webhook common.account.activated Root `status` `PENDING` → `ACTIVE`: the account is in good standing, so a payout may now name it as `receiver` or as `sender`. # Account archived Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-archived api-reference/openapi-v3-payments.json webhook common.account.archived Client soft-archived the account via POST .../archive; `data.archivedAt` is now set. # Account capability activated Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-capability-activated api-reference/openapi-v3-payments.json webhook common.account.capability_activated One capability moved `PENDING` → `ACTIVE`, so it may now back its activity; `data.capability` names which capability. # Account capability rejected Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-capability-rejected api-reference/openapi-v3-payments.json webhook common.account.capability_rejected A setup act was declined, moving the capability to `REJECTED`; `data.capability` names which capability, and the remedy is to request a replacement capability. # Account capability requires information Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-capability-requires-information api-reference/openapi-v3-payments.json webhook common.account.capability_requires_information OpenFX has requested information for one capability's setup, moving it to `REQUIRES_INFORMATION`; it cannot back its activity while that stands, and `data.capability` names which capability. # Account created Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-created api-reference/openapi-v3-payments.json webhook common.account.created The account now exists via POST /v3/common/accounts; `data.status` reports its root standing as it stood when the event was emitted, ordinarily `PENDING`. # Account rejected Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-rejected api-reference/openapi-v3-payments.json webhook common.account.rejected Root `status` → `REJECTED`: OpenFX's judgment went against the account, so it can no longer be paid, named as `sender`, or given new payout addresses, and the remedy is a replacement account. # Account requires information Source: https://docs.openfx.com/v3/webhooks/payments/accounts-webhooks/account-requires-information api-reference/openapi-v3-payments.json webhook common.account.requires_information Root `status` → `REQUIRES_INFORMATION`: OpenFX has asked for information about the account, which travels through your operational channel rather than the API, and a payout is blocked exactly as under `PENDING` while it stands. # Payout address activated Source: https://docs.openfx.com/v3/webhooks/payments/addresses-webhooks/payout-address-activated api-reference/openapi-v3-payments.json webhook payments.payout_address.activated Readiness `status` `PENDING` → `ACTIVE`, every setup act returned and none of them blocks. # Payout address archived Source: https://docs.openfx.com/v3/webhooks/payments/addresses-webhooks/payout-address-archived api-reference/openapi-v3-payments.json webhook payments.payout_address.archived Client soft-archived the address via POST .../archive; `data.archivedAt` is now set. # Payout address created Source: https://docs.openfx.com/v3/webhooks/payments/addresses-webhooks/payout-address-created api-reference/openapi-v3-payments.json webhook payments.payout_address.created Payout address created via POST /v3/payments/payout-addresses; `data.previousStatus` is null and `data.status` reports the rollup as it stood at emit, ordinarily `PENDING`. # Payout address rejected Source: https://docs.openfx.com/v3/webhooks/payments/addresses-webhooks/payout-address-rejected api-reference/openapi-v3-payments.json webhook payments.payout_address.rejected Readiness `status` `PENDING` → `REJECTED`, a setup act returned a blocking result. # Payout address requires information Source: https://docs.openfx.com/v3/webhooks/payments/addresses-webhooks/payout-address-requires-information api-reference/openapi-v3-payments.json webhook payments.payout_address.requires_information Readiness `status` → `REQUIRES_INFORMATION`: OpenFX has requested information the address's setup needs, through your operational channel, so it cannot back payouts while that stands. # Payout address verification resolved Source: https://docs.openfx.com/v3/webhooks/payments/addresses-webhooks/payout-address-verification-resolved api-reference/openapi-v3-payments.json webhook payments.payout_address.verification_resolved An act in `data.verifications` resolved. # Payout accepted Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-accepted api-reference/openapi-v3-payments.json webhook payments.payout.accepted `REQUIRES_CONFIRMATION` → `ACCEPTED`: every entry in `confirmations[]` stands acknowledged, ordinarily via POST .../confirm; funds not yet debited. # Payout cancelled Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-cancelled api-reference/openapi-v3-payments.json webhook payments.payout.cancelled `REQUIRES_CONFIRMATION` → `CANCELLED` via POST .../cancel. # Payout created Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-created api-reference/openapi-v3-payments.json webhook payments.payout.created Payout created via POST /v3/payments/payouts; `data.status` reports where it stood at emit, ordinarily `REQUIRES_CONFIRMATION`. # Payout expired Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-expired api-reference/openapi-v3-payments.json webhook payments.payout.expired `REQUIRES_CONFIRMATION` → `EXPIRED`, the applied quote expired before confirmation. # Payout failed Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-failed api-reference/openapi-v3-payments.json webhook payments.payout.failed `REQUIRES_CONFIRMATION` → `FAILED` (a pre-confirm failure) or `ACCEPTED` → `FAILED` (settlement failed after acceptance), each before funds reached the rail; read `data.previousStatus` for the origin. # Payout in review Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-in-review api-reference/openapi-v3-payments.json webhook payments.payout.in_review `PROCESSING` → `IN_REVIEW` (manual/compliance hold); funds remain debited. # Payout processed Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-processed api-reference/openapi-v3-payments.json webhook payments.payout.processed `PROCESSING` → `PROCESSED` (settled). # Payout processing Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-processing api-reference/openapi-v3-payments.json webhook payments.payout.processing `ACCEPTED` → `PROCESSING` (funds debited) or `IN_REVIEW` → `PROCESSING` (review resolved favorably), disambiguate via `data.previousStatus`. # Payout returned Source: https://docs.openfx.com/v3/webhooks/payments/payouts-webhooks/payout-returned api-reference/openapi-v3-payments.json webhook payments.payout.returned `PROCESSING`, `IN_REVIEW`, or `PROCESSED` → `RETURNED` (any post-debit unwind), see `data.return`. # Webhooks setup Source: https://docs.openfx.com/v3/webhooks/setup Register an HTTPS endpoint, store the signing secret, verify every event, and stop polling. Webhooks turn OpenFX resource lifecycles from a polling problem into a push-driven one. OpenFX delivers signed HTTP POSTs to an HTTPS endpoint you control the moment an event reaches a meaningful state. This page walks you from "no endpoint" to "events are verified and processed". If you only need the signature-verification reference, jump to [Webhook authentication](/v3/webhooks/authentication). This page is the operational setup around that. ## Prerequisites * A publicly reachable **HTTPS** endpoint (no plain HTTP: signatures protect integrity, TLS protects in-transit confidentiality) * An admin user in the [OpenFX dashboard](https://app.openfx.com) * A handler that can hold a small amount of state (deduplication of replayed events) ## Step 1: Register your endpoint **1. Open the dashboard** Sign in to [app.openfx.com/webhooks](https://app.openfx.com/webhooks), your organization's **Webhooks** settings. **2. Add a webhook URL** Enter your HTTPS URL. The dashboard supports one webhook URL per environment (Live and Sandbox have separate registrations; see [Environments](/v3/environments)). **3. Subscribe to event types** Every event type name follows a dot-namespaced, lowercase `{product}.{resource}.{action}` convention (`fx.` for FX), so you can route on a whole family by prefix (e.g. `fx.withdrawal.*`) or on individual event types (e.g. fx.deposit.completed). See [Deposit webhooks](/v3/webhooks/deposits/deposit-completed), [Withdrawal webhooks](/v3/webhooks/withdrawals/withdrawal-completed), and [Trade webhooks](/v3/webhooks/trades/trade-ready-to-settle) for the exact event types each resource emits. Payments and account events use the same envelope and signature. Their event types start with `payments.payout.`, `payments.payout_address.`, and `common.account.`. See [Payout webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) and the account and payout address pages beside them. Subscribe to whichever events your integration needs; if in doubt, subscribe to everything. **4. Copy the signing key** The dashboard generates a separate signing key for Live and for Sandbox. Store it as `OPENFX_WEBHOOK_SIGNING_KEY` in your secrets manager. **Treat it like a database password**: anyone with it can mint events that pass signature verification. > [!WARNING] > > **Sandbox and Live signing keys are different.** A handler that uses the Live > signing key to validate Sandbox events will reject every one. Wire the key > from environment-aware config, not a hard-coded constant. ## Step 2: Build the handler Minimum viable handler: read the raw body, verify the signature, deduplicate by event `id`, dispatch. ```javascript Node / Express theme={"theme":{"light":"poimandres","dark":"poimandres"}} import crypto from "node:crypto"; import express from "express"; const app = express(); const TOLERANCE_SECONDS = 300; // IMPORTANT: read the raw body. JSON re-serialization breaks signatures. app.post( "/webhooks/openfx", express.raw({ type: "application/json" }), async (req, res) => { const sigHeader = req.header("x-openfx-signature"); const fields = Object.fromEntries( (sigHeader || "") .split(",") .map((part) => part.split("=")) .filter(([key, value]) => key && value), ); if (!fields.t || !fields.v1) { return res.status(401).end(); } const timestamp = Number(fields.t); const now = Math.floor(Date.now() / 1000); if ( !Number.isFinite(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS ) { return res.status(401).end(); } const expected = crypto .createHmac("sha256", process.env.OPENFX_WEBHOOK_SIGNING_KEY) .update(`${timestamp}.${req.body}`) .digest("hex"); const a = Buffer.from(fields.v1); const b = Buffer.from(expected); // timingSafeEqual throws on length mismatch; guard first. if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) { return res.status(401).end(); } const event = JSON.parse(req.body.toString("utf8")); // Idempotent processing: events can be redelivered. Dedupe by event id. if (await store.alreadyProcessed(event.id)) { return res.status(200).end(); } // event.type is the resource noun, e.g. "deposits" or "withdrawals" // event.eventType is the product-prefixed action, e.g. "fx.deposit.completed" // event.data is the single resource object. await dispatch(event); await store.markProcessed(event.id); res.status(200).end(); }, ); ``` ```python Python / Flask theme={"theme":{"light":"poimandres","dark":"poimandres"}} import hashlib, hmac, os, time from flask import Flask, request app = Flask(__name__) TOLERANCE_SECONDS = 300 @app.post('/webhooks/openfx') def openfx_webhook(): sig_header = request.headers.get('x-openfx-signature', '') fields = {} for part in sig_header.split(','): if '=' not in part: continue key, _, value = part.partition('=') if key and value: fields[key] = value if 't' not in fields or 'v1' not in fields: return '', 401 try: timestamp = int(fields['t']) except ValueError: return '', 401 if abs(time.time() - timestamp) > TOLERANCE_SECONDS: return '', 401 raw_body = request.get_data() signed_payload = f"{timestamp}.".encode('utf-8') + raw_body expected = hmac.new( os.environ['OPENFX_WEBHOOK_SIGNING_KEY'].encode(), signed_payload, hashlib.sha256, ).hexdigest() if not hmac.compare_digest(fields['v1'], expected): return '', 401 event = request.get_json(force=True) # Dedupe by event id if store.already_processed(event['id']): return '', 200 dispatch(event) store.mark_processed(event['id']) return '', 200 ``` The signature-verification half of this is covered in full in [Webhook authentication](/v3/webhooks/authentication), including additional language samples. ## Step 3: Acknowledge fast, process async Return `2xx` within a few seconds. Long-running processing (database writes, downstream API calls, sending the user an email) belongs on a queue: ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} // Inside the handler: await queue.enqueue("process-openfx-event", event); res.status(200).end(); ``` OpenFX retries deliveries that don't ack with `2xx`. The combination of "ack fast" + "process via queue" + "deduplicate by event `id`" makes retries safe. ## Step 4: Test in Sandbox The fastest path to a working integration is to fire events from Sandbox before going to Live: 1. Use your Sandbox API key (`sandbox_`-prefixed), which is bound to the Sandbox environment. If you send `X-App-Mode`, set it to SANDBOX; omitting it also selects Sandbox. 2. Trigger a Sandbox deposit or withdrawal yourself from Sandbox mode in the dashboard. Sandbox doesn't move real money, so there's no amount to worry about. 3. Verify your handler receives the signed event and returns `2xx`. 4. Check the dashboard's delivery log for the event. Trade webhooks (fx.trade.ready_to_settle, fx.trade.settled, fx.trade.reversed) are delivered only to Live webhooks. Sandbox trades never emit them, so you can't exercise a trade handler in Sandbox. See [Environments](/v3/environments) for the Sandbox-vs-Live split. ## Event envelope shape Every webhook delivery uses these top-level routing fields. This abbreviated shape collapses `data` to an empty object and omits the required Deposit or Withdrawal fields; use the complete, schema-checked event examples on the payload pages when implementing a handler. ```json theme={"theme":{"light":"poimandres","dark":"poimandres"}} { "id": "evt_7m4VsfRw4pGrS76WYj5tnx", "type": "deposits", "eventType": "fx.deposit.completed", "createdAt": "2026-04-28T08:32:50.618Z", "data": {} } ``` | Field | Type | Notes | | - | - | - | | `id` | string (readable ID, `evt_` prefix) | Unique per event. Use for server-side deduplication: dedupe on `id` before processing. | | `type` | string | Resource noun the event concerns: deposits, withdrawals, or trades. Use it to route by resource family. | | `eventType` | string | Dot-namespaced, product-prefixed action name: fx.deposit.completed, fx.withdrawal.completed, or fx.trade.ready_to_settle/fx.trade.settled/fx.trade.reversed. Match by prefix (e.g. `fx.withdrawal.*`) if you want to route on the product tag alone. | | `createdAt` | string (RFC 3339, ms, UTC) | When OpenFX built and dispatched this delivery, e.g. `2026-04-28T08:32:50.618Z`. Not when the underlying deposit or withdrawal happened. | | `data` | object | The single resource this event concerns, close to but not identical to its v3 REST shape. See the payload pages linked below for the exact fields. | Field names are `camelCase`; monetary amounts are strings (e.g. `"1000.00"`); timestamps are RFC 3339 with millisecond precision and a trailing `Z`. This matches the v3 REST API conventions exactly, deposit, withdrawal, and trade settlement events alike. The field-level reference is in: * [Deposit webhooks](/v3/webhooks/deposits/deposit-completed) * [Withdrawal webhooks](/v3/webhooks/withdrawals/withdrawal-completed) * [Trade webhooks](/v3/webhooks/trades/trade-ready-to-settle) * [Payout webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) ## Polling fallback Webhooks are the primary delivery channel, but if your handler is briefly unreachable, OpenFX retries. As a defense-in-depth, periodically reconcile against the read endpoints: * [`GET /v3/fx/deposits`](/v3/api-reference/trade-settlement/list-deposits) for missed deposit events; pair with [Deposits](/v3/deposits) for the state model and reconcilable fields * [`GET /v3/fx/withdrawals`](/v3/api-reference/trade-settlement/list-withdrawals) for missed withdrawal events; use the [adaptive-backoff pattern](/v3/withdrawals#fallback-polling-pattern-with-adaptive-backoff) on the [Withdrawals](/v3/withdrawals) page so a slow rail doesn't burn your rate-limit budget Lists are newest-first. Use [cursor pagination](/v3/pagination): read the first page, follow `pagination.nextCursor` toward older records, and stop when you reach a record you've already processed. Don't poll continuously: a slow reconciliation sweep every few minutes is enough. ## Common mistakes * **Parsing the body before verifying.** JSON re-serialization changes whitespace and key order, which changes the HMAC digest. Always verify against the **raw** request body. * **String comparison on signatures.** Use a constant-time comparison (`crypto.timingSafeEqual`, `hmac.compare_digest`). Standard `===` leaks timing. * **Not deduplicating by event `id`.** A handler that 500s on the first delivery and 200s on the redelivery will receive the same event twice. Store `event.id` server-side and short-circuit duplicates. **Retain event IDs for at least 48 hours.** OpenFX retries failed deliveries on a backoff curve within that window; older IDs can be safely purged. * **Long-running work before acking.** A 30-second database write turns into a webhook timeout, which turns into a retry, which lands you with three copies of the same work in flight. Ack first, process async. * **Mixing Sandbox and Live signing keys.** Wire the key from environment config, not a constant. ## What's next > [card] [Webhook authentication](/v3/webhooks/authentication) > > Signature scheme + verification code samples. > [card] [Deposit webhooks](/v3/webhooks/deposits/deposit-completed) > > Event shape for fiat and stablecoin deposits. > [card] [Withdrawal webhooks](/v3/webhooks/withdrawals/withdrawal-completed) > > Event shape for withdrawal completion. > [card] [Trade webhooks](/v3/webhooks/trades/trade-ready-to-settle) > > Event shape for ready-to-settle, settled, and reversed trades. > [card] [Payout webhooks](/v3/webhooks/payments/payouts-webhooks/payout-created) > > Event shape for payout status changes. > [card] [Verified accounts](/v3/verified-accounts) > > Pre-configure withdrawal accounts the webhooks will report on. # Trade ready to settle Source: https://docs.openfx.com/v3/webhooks/trades/trade-ready-to-settle api-reference/openapi-v3.json webhook fx.trade.ready_to_settle A manually settled trade becomes ready to settle, at execution for `T0` or when the window opens for `T1`/`T2`, and awaits `POST .../settle`. # Trade reversed Source: https://docs.openfx.com/v3/webhooks/trades/trade-reversed api-reference/openapi-v3.json webhook fx.trade.reversed `POST .../reverse` unwinds a `READY_TO_SETTLE` trade. # Trade settled Source: https://docs.openfx.com/v3/webhooks/trades/trade-settled api-reference/openapi-v3.json webhook fx.trade.settled A trade reaches `EXECUTED`: at execution for `IMMEDIATE` and auto-settled `T0` trades, or once a `T1`/`T2` or manually settled trade settles. # Withdrawal completed Source: https://docs.openfx.com/v3/webhooks/withdrawals/withdrawal-completed api-reference/openapi-v3.json webhook fx.withdrawal.completed A fiat or stablecoin withdrawal reaches `COMPLETED` and settles to the destination account. # Withdrawals Source: https://docs.openfx.com/v3/withdrawals Settlement windows per rail, and how to track the time between submission and settlement: webhooks first, adaptive polling as a fallback. Withdrawals don't complete instantly. The transition timing depends on the rail: seconds-to-minutes for stablecoins, hours-to-days for fiat. Use this page to know how long settlement typically takes, and how to poll without burning rate-limit budget waiting on a fiat wire. ## State machine ```mermaid theme={"theme":{"light":"poimandres","dark":"poimandres"}} %%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, system-ui, sans-serif','fontSize':'13px'}}}%% stateDiagram-v2 direction TB [*] --> PENDING: POST /v3/fx/withdrawals PENDING --> COMPLETED: Funds left OpenFX PENDING --> CANCELLED: Withdrawal doesn't go through COMPLETED --> [*] CANCELLED --> [*] classDef ok stroke-width:1px classDef bad stroke-width:1px classDef pending stroke-width:1px classDef hold stroke-width:1px classDef returned stroke-width:1px classDef neutral stroke-width:1px class PENDING pending class COMPLETED ok class CANCELLED bad ``` `Withdrawal.status` is a closed enum. | Status | Meaning | | - | - | | PENDING | Created. Funds have not left OpenFX yet | | COMPLETED | Funds have left OpenFX. Final | | CANCELLED | The withdrawal didn't go through. Final | ## Where money goes The rail is bound to the verified withdrawal account. You don't pick it on the request. * **Fiat withdrawals.** See [Settlement times](/v3/settlement-times) for the submission cut-off per currency and rail. * **Stablecoin withdrawals.** See [Supported networks](/v3/supported-networks) for the per-stablecoin chain matrix. ## Fallback: polling pattern with adaptive backoff > [!TIP] > > **Polling is a fallback.** Where possible, prefer receiving webhook events over polling for terminal status. If you can't yet receive webhooks, don't poll every 5 seconds for fiat; you'll burn rate-limit budget waiting on a rail whose settlement spans banking hours. This sample waits about 20 minutes in total (the delays sum to 1,215 seconds), which suits stablecoin withdrawals and fiat withdrawals that settle within the same banking window. A fiat withdrawal can take hours to days, so when the schedule runs out, stop polling and rely on webhooks or a later check instead of treating the error as a failure. ```javascript theme={"theme":{"light":"poimandres","dark":"poimandres"}} async function waitForWithdrawal(withdrawalId, signRequest) { const delays = [ 5_000, 10_000, 20_000, 40_000, 80_000, 160_000, 300_000, 300_000, 300_000, ]; const url = `https://api.openfx.com/v3/fx/withdrawals/${withdrawalId}`; for (let i = 0; i <= delays.length; i++) { const signed = signRequest({ method: "GET", url }); const res = await fetch(url, { headers: signed.headers }); const w = await res.json(); if (w.data?.status === "COMPLETED") return w; if (w.data?.status === "CANCELLED") { throw new Error(`Withdrawal ${withdrawalId} was CANCELLED.`); } // Sleep only between polls, never after the last one. if (i < delays.length) { await new Promise((r) => setTimeout(r, delays[i])); } } throw new Error( "Withdrawal not COMPLETED after backoff exhausted; consider webhook delivery.", ); } ``` ## When a withdrawal is stuck ### Step 1: read the trace ID Every response carries `X-Trace-Id`; include it if you escalate to OpenFX support. ### Step 2: re-fetch the resource ```bash theme={"theme":{"light":"poimandres","dark":"poimandres"}} curl https://api.openfx.com/v3/fx/withdrawals/ \ -H "Authorization: Bearer $OPENFX_JWT" \ -H "X-Request-Signature: $OPENFX_SIGNATURE" ``` ### Step 3: check the estimated completion time Read `estimatedCompletionAt` on the withdrawal. It's the time the withdrawal is expected to settle, so a withdrawal that is still PENDING before that time isn't stuck. It's `null` when there's no estimate yet. ### Step 4: match the state against the rail clock Not-yet-settled past the rail cut-off is the most common cause of "stuck." Common cases: * **Fiat USD via Fedwire:** submissions after 4:30 PM ET batch the next business day. * **Fiat EUR via SEPA:** submissions after 12:30 PM London time batch the next business day. * **Stablecoin on Ethereum:** network congestion can delay confirmation 10+ minutes. ## Common mistakes * **Fixed-interval polling at 5s.** Fine for the first minute; wasteful for a fiat withdrawal that spans banking hours. * **Polling without an upper bound.** Always have a "give up and alert" condition. ## What's next > [card] [Settlement models](/v3/settlement-models) > > The full deposit / balance / withdrawal model. > [card] [Errors](/v3/errors) > > Recovery patterns for rejected withdrawals. > [card] [Idempotency](/v3/idempotency) > > 7-day TTL on withdrawal keys. > [card] [Withdrawal webhooks](/v3/webhooks/withdrawals/withdrawal-completed) > > Receive a push notification when a withdrawal completes instead of polling.