# ELK OTC API documentation

## Base URLs

- Sandbox: https://api.elkcrypto.com/sandbox
- Production: https://api.elkcrypto.com


---

<a id="quickstart"></a>

# Quickstart

Request the product catalogue and a sandbox quote using curl and Python 3.

## Before you start

Ask your onboarding contact for an activated sandbox key, its expiry, approved outbound IPs, and product permissions. You need curl and Python 3 on a trusted backend machine.

| Environment | Base URL | Credentials |
| --- | --- | --- |
| Sandbox | `https://api.elkcrypto.com/sandbox` | Activated sandbox key |
| Production | `https://api.elkcrypto.com` | Separate key after approval |

Append `/v1/...` to the base URL. The sandbox progress URL intentionally contains both prefixes: `/sandbox/v1/sandbox/progress`.

## 1. Store your key privately

Run the following blocks in the same shell. Enter your key at the prompt; the script saves it in a private header file.

```sh
mkdir -m 700 elk-sandbox
cd elk-sandbox
umask 077
python3 - <<'PY'
import getpass, os
key = getpass.getpass('Sandbox API key: ')
if not key or any(c.isspace() for c in key):
    raise SystemExit('Invalid key input')
fd = os.open('auth.headers', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as output:
    output.write('Authorization: Bearer ' + key + '\n')
PY
BASE_URL=https://api.elkcrypto.com/sandbox
```

Exclude `auth.headers` from version control.

## 2. Discover eligible products

```sh
curl --connect-timeout 5 --max-time 10 \
  --header @auth.headers --dump-header catalogue.headers \
  --output catalogue.json --write-out 'HTTP %{http_code}\n' \
  "$BASE_URL/v1/catalogue?limit=50"
```

A successful response is HTTP 200 with `records` and `next_after_id`. Pass `next_after_id` as `after_id` for subsequent pages until the response cursor is `null`.

## 3. Request a quote

The sandbox supports `USDT/USD` in `OTC-SPOT`. A buy acquires USDT and pays USD. All quantities are decimal **strings**, not JSON numbers.

```sh
python3 - <<'PY'
import json, uuid
operation = {
    'idempotency_key': str(uuid.uuid4()),
    'path': '/v1/get_quote',
    'body': {'symbol': 'USDT/USD', 'market': 'OTC-SPOT',
             'side': 'buy', 'quantity': '1000'},
}
with open('quote-operation.json', 'x') as output:
    json.dump(operation, output)
with open('quote-request.json', 'x') as output:
    json.dump(operation['body'], output)
PY
QUOTE_ID=$(python3 -c 'import json; print(json.load(open("quote-operation.json"))["idempotency_key"])')
curl --connect-timeout 5 --max-time 10 \
  --header @auth.headers --header 'Content-Type: application/json' \
  --header "Idempotency-Key: $QUOTE_ID" \
  --data-binary @quote-request.json \
  --dump-header quote.headers --output quote.json \
  --write-out 'HTTP %{http_code}\n' "$BASE_URL/v1/get_quote"
```

A successful response is HTTP 200 with `quote_id`, `price`, `pay`, `receive`, and `expires_at`. The fixed sandbox buy price is `1.001`: quantity `1000` pays `1001` USD and receives `1000` USDT.

The script saves the request and UUID in `quote-operation.json`. To retry, reuse that UUID and request body. Sandbox quotes expire after at most 30 seconds; use the response `expires_at` value.

## Next steps

- [Integration guide](#integration-guide): request IDs, retries, and amounts.
- [Sandbox certification](#client-certification): acceptance and test scenarios.
- [API reference](#api-reference) and [OpenAPI specification](#openapi-contract).


---

<a id="integration-guide"></a>

# Integration guide

## Request sequence

1. Read available products with `GET /v1/catalogue`.
2. Request a quote with `POST /v1/get_quote`.
3. Submit its `quote_id` to `POST /v1/accept` before `expires_at`.
4. Read the result using `GET /v1/orders/{order_id}`.

A new order has status `pending`. After review, its status becomes `filled` or
`cancelled`. These are terminal states. Quote expiry does not change an accepted
order's status.

## Request identifiers

| Identifier | Source | Use |
| --- | --- | --- |
| `Idempotency-Key` | Client-generated UUID | Identify a POST operation and its retries |
| `quote_id` | Quote response | Select the quote to accept |
| `order_id` | Acceptance response | Read an order |
| `X-Request-ID` | Client or API | Trace one HTTP request |

Use distinct operation UUIDs for quote and acceptance requests. Save each UUID
and request body before sending. Retries use the same UUID and body, including
after a timeout or process restart. Record the response and order ID when available.
A changed body with the same UUID returns `409 idempotency_conflict`.

Idempotency is scoped to the account and operation. A rotated, valid key for the
same account can retry an existing operation. Replay requires current read access.
See [idempotency and recovery](#idempotency-and-recovery).

## Retry handling

| Response | Action |
| --- | --- |
| HTTP 200 | Save the response; use `expires_at` for quotes and `status` for orders |
| Timeout, disconnect, or non-JSON gateway error | Retry the original UUID and body with bounded backoff |
| HTTP 429 | Honor `Retry-After` when present; otherwise use exponential backoff with jitter |
| HTTP 503 | Retry the original UUID and body within a bounded retry budget |
| HTTP 400 / 415 | Correct the request or headers |
| HTTP 401 / 403 | Check key validity, environment, outbound IP, and permissions |
| `idempotency_conflict` | Check the saved UUID and request body |
| `quote_already_accepted` | Recover the order using the original acceptance UUID |
| `quote_expired` | Request a new quote after resolving any pending acceptance |
| `insufficient_funds` / `insufficient_credit` | Check available balances or credit |

If an acceptance remains unresolved after the retry budget, retain its UUID and
request for support reconciliation rather than submitting a replacement operation.
See the [error reference](#errors) for response codes.

## Amounts

Quantities, prices, and amounts are decimal strings. Use a decimal library for
calculations and preserve strings when serializing JSON.

`buy` acquires base and pays quote; `sell` delivers base and receives quote. The
response `pay` and `receive` fields are the complete exchange amounts at the
quoted price. Quote amounts are positive;
balance amounts can be signed. Product minimums, quantity steps, and ticks apply.

## Pagination and account reads

- `GET /v1/catalogue`: use `limit` (1–200; default 50) and the returned
  `next_after_id` as the next request's `after_id`.
- `GET /v1/orders`: returns up to 50 records, newest first. Pass `next_after_id`
  as `after_id` until it is `null`.
- `GET /v1/orders/{order_id}`: returns a single order. The compatibility
  `trade_id` has the same value as `order_id`.
- `GET /v1/balances`: returns balances, holds, and available credit. A zero credit
  limit permits funded orders only.
- `GET /v1/heartbeat`: returns API and account-authority connectivity checks.
  Poll every 15 seconds with a bounded timeout and backoff after failures.

## Production access

Complete the ten [sandbox scenarios](#client-certification), then request a
production key. Confirm approved products, outbound IPs, key expiry, and rate
limits with support. Keep sandbox and production keys and operation records separate.

## Support

Provide the environment, UTC request time, HTTP status, error code, operation UUID,
quote/order ID, and response `X-Request-ID`. Exclude bearer keys and Authorization
headers.


---

<a id="api-reference"></a>

# Customer API reference

**Contract version: 0.1.0.** The [OpenAPI 3.1 specification](#openapi-contract) is the
machine-readable wire contract. These endpoints issue customer-specific Spot
quotes and book accepted quotes.

## Environments and onboarding

| Environment | Base URL | Purpose |
| --- | --- | --- |
| Sandbox | `https://api.elkcrypto.com/sandbox` | Synthetic accounts, fixed USDT/USD prices, test bookings only |
| Production | `https://api.elkcrypto.com`, once support confirms activation | Approved accounts and deployment-configured indicative pricing |

Obtain an environment-specific API key, expiry, approved egress IPs and
product limits from support. `GET /v1/catalogue` lists eligible products
and pricing availability. It accepts optional `limit` (1–200,
default 50) and exclusive UUID `after_id`; unknown or repeated query parameters
reject. No body or idempotency key is required. Use `next_after_id` until null.
Complete [sandbox certification](#client-certification) before requesting
production credentials. Use a separate key for each environment.

## Transport and authentication

- Use HTTPS with certificate and hostname verification enabled. Follow any
  connection instructions supplied with your sandbox access details.
- Requests with an `Origin` header are rejected. Send requests from your server.
- Send `Authorization: Bearer <your-api-key>`. The opaque key is not a JWT and
  requires no signature calculation. The server derives the account and
  counterparty from it; never send account IDs in customer requests.
- Your actual egress IP (including NAT) must be on the key's allowlist. Do not
  send `Forwarded` or `X-Forwarded-For` yourself. Ask support to approve changed IPs.
- Keys expire and can be revoked. Support issues and rotates keys through a
  separate process. Keep secrets out of URLs, logs, screenshots and reports.
- Quote and acceptance requests use POST with JSON and no query parameters. JSON fields are case-sensitive;
  duplicate or unknown fields are rejected. Compressed request bodies are not
  supported. Do not send `Content-Encoding`.

### Headers

| Header | Required | Value |
| --- | --- | --- |
| `Authorization` | Yes | `Bearer <key>` |
| `Content-Type` | POST only | `application/json` (also accepts `application/json; charset=utf-8`) |
| `Idempotency-Key` | POST only | Client-generated canonical 36-character UUID; one per new operation |
| `X-Request-ID` | No | Tracing UUID; server generates one if absent |

Duplicate semantic headers and malformed UUID metadata are rejected. Save
`X-Request-ID` from the response for support; it is **not** an idempotency key.
Native API responses are JSON with `Cache-Control: no-store` and `X-Request-ID`.
An ingress proxy may return HTML or an empty body on its own failures, so always
check HTTP status and content type before parsing JSON.

## Sandbox progress

`GET https://api.elkcrypto.com/sandbox/v1/sandbox/progress` returns the authenticated
key's automatic certification status: `checklist_version`, `key_id`, `account_id`,
`passed_checks`, `missing_checks`, `completed`, `first_observed_at`, `completed_at`,
`expires_at_ms` and `revoked_at_ms`. Times are UTC timestamps (or null before an
observation/completion); key expiry and revocation are epoch milliseconds.

Use the same bearer authentication and approved source IP. Send no body or query
parameters; no `Idempotency-Key` or `Content-Type` is needed. No other key's
progress can be requested. This endpoint is absent in production (HTTP 404).
See the [sandbox guide](#client-certification) for the ten scenarios and examples.

## Amounts, direction and time

- `symbol` is uppercase `BASE/QUOTE`, e.g. `USDT/USD`.
- `buy` means you acquire base and pay quote; `sell` means you deliver base and
  receive quote. `quantity` is base units. `price` is quote units per base.
- All amounts are **positive decimal strings**, never JSON numbers. Use decimal
  arithmetic, not binary floating point. Maximum: 20 integer digits, 18 fractional
  digits and 39 characters overall. No signs, exponent notation, whitespace or
  integer leading zeros. Product quantity steps, minimums and ticks also apply.
- Equivalent decimals normalize (`"1000.0"` equals `"1000"`). Response amounts
  have no trailing fractional zeros. Unsupported precision/range is rejected,
  not silently rounded.
- `pay` and `receive` are the complete, final exchange amounts at the quoted
  price. Use them directly without adding charges or making deductions.
- Timestamps are UTC ISO 8601 with exactly milliseconds, e.g.
  `2026-10-13T12:00:00.000Z`. Expiry is exclusive; equality is expired. The server's
  database clock is authoritative, including time spent waiting for locks.

## GET /v1/heartbeat

Check API and current account-authority reachability using the same bearer key
and approved source IP. Requires an active enrolled account, `ViewQuotes`, and
current KYC for linked desk clients. Send no body, query parameters or
`Content-Encoding`; neither `Content-Type` nor `Idempotency-Key` is needed.

A successful response contains `status: "ok"`, a UTC millisecond `as_of`
timestamp, and `checks: {"api":"ok","account_authority":"ok"}`. Responses
are not cached. Invalid/expired/revoked keys return 401; denied account/IP/read
access returns 403; unavailable authority returns 503.

Poll every 15 seconds with a bounded timeout. Use backoff and jitter after failures.

## GET /v1/balances

Read current balances, holds and available credit. Use your bearer key and
approved source IP; send no body, account/client ID or query parameters. Neither
`Content-Type` nor `Idempotency-Key` is needed. Requires an active linked API
account, current desk KYC and `ViewQuotes`.

```json
{
  "schema_version": 2,
  "source": "desk_journal",
  "as_of": "2026-10-30T12:00:00.000Z",
  "balances": [
    {"asset": "BTC", "balance": "0.5", "on_hold": "0.1", "available": "0.4"},
    {"asset": "USD", "balance": "20", "on_hold": "20", "available": "0"}
  ],
  "credit": {
    "currency": "USD",
    "basis": "asset_deficits_v1",
    "limit": "100",
    "outstanding": "0",
    "on_hold": "5",
    "available": "95"
  }
}
```

Balances are **signed decimal strings**. Negative amounts represent amounts owed.
USD is included even when its balance is zero.

Available credit is `limit − outstanding − on_hold`.
An unset/zero limit permits funded orders only: **no borrowing**, not unlimited
credit. Existing negative asset positions consume credit, using fresh desk USD
marks for crypto. Other positive assets are not automatically pledged as collateral.
Pending orders reserve their pay-asset funds first, then credit for any shortfall;
asset `on_hold` is the funded portion, while credit `on_hold` is the borrowing
portion (plus any funded hold no longer backed by the current balance). Crypto
credit holds are revalued with desk marks. `available` can be negative following
market moves, ledger changes or a reduced credit limit; new orders are blocked
while over limit.

Legacy schema version 1 omits hold fields and uses `desk_total_owed` for credit.
`as_of` is the observation timestamp. Unavailable balance data returns
`503 service_unavailable`; unlinked accounts or missing read permission return 403.

## POST /v1/get_quote

Request a new quote or replay the original successful result.

```json
{
  "symbol": "USDT/USD",
  "market": "OTC-SPOT",
  "side": "buy",
  "quantity": "1000"
}
```

| Field | Required | Meaning |
| --- | --- | --- |
| `symbol` | Yes | Eligible uppercase pair; distinct base and quote |
| `market` | No | Eligible uppercase market; omission and `null` are equivalent. Required if the pair is ambiguous (`market_required`) |
| `side` | Yes | `buy` or `sell`, from your perspective |
| `quantity` | Yes | Exact decimal string, gross base units |

A fresh request needs an active enrolled account, allowed IP, `ViewQuotes`,
`SubmitRfq`, market permission, and product/all-underlying eligibility. The server
resolves identity, economics and expiry. Do not send your own price or expiry.
Production prices depend on availability and approved client markups; they are
not the sandbox's fixed prices.

**HTTP 200 response — illustrative sandbox buy:**

```json
{
  "quote_id": "22222222-2222-4222-8222-222222222222",
  "symbol": "USDT/USD",
  "market": "OTC-SPOT",
  "side": "buy",
  "price": "1.001",
  "pay": {"asset": "USD", "amount": "1001"},
  "receive": {"asset": "USDT", "amount": "1000"},
  "issued_at": "2026-10-13T12:00:00.000Z",
  "expires_at": "2026-10-13T12:00:30.000Z"
}
```

`quote_id` is a server-generated UUIDv4 associated with your account.
Use `expires_at` to check expiry. Replays return the original price and expiry.

## POST /v1/accept

Accept a quote using `quote_id`. Use an acceptance operation UUID distinct from
the quote-request UUID.

```json
{"quote_id": "22222222-2222-4222-8222-222222222222"}
```

`quote_id` is the only allowed field. The server uses the original immutable terms;
it does not accept a replacement price, amount, counterparty or expiry.

A new acceptance requires current read eligibility, `AcceptTrade`, and sufficient
funds or credit for the pay amount. Each quote can be accepted once. Retrying the
original acceptance returns the same order.

Insufficient capacity returns HTTP **409** with `insufficient_funds` (funded-only
client) or `insufficient_credit`, plus a clear human-readable `message`. No booking
is created. Missing/stale financial authority or required USD marks returns
`503 funding_source_unavailable`. For a timeout or uncertain response, retry the
same `quote_id` and `Idempotency-Key`.

**HTTP 200 response — illustrative sandbox booking:**

```json
{
  "order_id": "33333333-3333-4333-8333-333333333333",
  "trade_id": "33333333-3333-4333-8333-333333333333",
  "status": "pending",
  "updated_at": "2026-10-13T12:00:02.000Z",
  "quote": {
    "quote_id": "22222222-2222-4222-8222-222222222222",
    "symbol": "USDT/USD",
    "market": "OTC-SPOT",
    "side": "buy",
    "price": "1.001",
    "pay": {"asset": "USD", "amount": "1001"},
    "receive": {"asset": "USDT", "amount": "1000"},
    "issued_at": "2026-10-13T12:00:00.000Z",
    "expires_at": "2026-10-13T12:00:30.000Z"
  },
  "accepted_at": "2026-10-13T12:00:02.000Z"
}
```

The embedded `quote` contains the original quoted terms. `accepted_at` is the
acceptance timestamp. Initial status is `pending`; after review it becomes
`filled` or `cancelled`. Both are terminal. Quote expiry does not change an
accepted order's status. Use current balances to check available capacity after
cancellation.

## GET /v1/orders and GET /v1/orders/{order_id}

Read your API order history or a single order using the same bearer key and approved
source IP. Send no body; neither `Content-Type` nor `Idempotency-Key` is needed.
Requires `ViewQuotes` and market access.

`GET /v1/orders` returns `{"records": [...], "next_after_id": null}`. Each record
has the acceptance shape above. Pages contain up to 50 records, newest first.
For another page, request `/v1/orders?after_id=<next_after_id>`. The cursor is opaque
and account-scoped. Other query parameters and caller-supplied account IDs are rejected.

`GET /v1/orders/{order_id}` returns one record. Missing and another account's IDs
both return `404 quote_not_found`. `order_id` and the compatibility `trade_id` are
the same identifier. `accepted_at` and quote terms never change; `updated_at` is
initially the acceptance time and later the terminal reporting transition time.

Repeating the original `POST /v1/accept` also returns the **current** order status,
not a frozen pending response. Its immutable booking identity and quote terms remain
unchanged, and retries never create another order.

## Idempotency and recovery

1. Generate a UUID for each new operation. **Persist it and the request body before
   sending.** Keep successful receipts durably, along with their operation UUIDs.
2. Retry an operation with the **same UUID and canonical body**. JSON property
   ordering and normalized decimal spelling do not change command identity.
3. A repeated successful command returns its original terms, even after expiry.
   Acceptance additionally reports the current order status.
   A changed body under the same scoped UUID returns `409 idempotency_conflict`.
4. Keys are scoped by account and operation, not bearer credential. Rotation to a
   different valid bearer key for the same account preserves recovery scope;
   revoked/expired credentials cannot authenticate.
5. Successful results are retained without key reuse. Only successful operations
   create receipts. Pricing may run more than once before a single result commits.
6. A timeout, disconnect or error does **not** prove an earlier attempt failed.
   Keep retrying the original command with bounded backoff, or contact support.
   **Never replace an uncertain acceptance with a new UUID or a new trade.**
7. Replay still requires current read eligibility. It does not require the
   original mutation permission (`SubmitRfq` / `AcceptTrade`). If read access is
   lost, stop automated trading and reconcile with support using retained IDs.

Honor `Retry-After` when supplied; otherwise use bounded exponential backoff with
jitter. Account-specific rate limits are available from support.

## Errors

Native API errors have this shape; branch on `code`, not the human-readable message:

```json
{
  "code": "pricing_unavailable",
  "message": "pricing_unavailable",
  "request_id": "77777777-7777-4777-8777-777777777777"
}
```

| HTTP | Code | Meaning / next step |
| --- | --- | --- |
| 400 | `invalid_request` | Invalid JSON, fields, metadata or product quantity. Check exact strings/schema |
| 400 | `market_required` | Specify an eligible market to disambiguate the symbol |
| 401 | `sandbox_key_on_production` | Sandbox-prefixed key sent to production; use `https://api.elkcrypto.com/sandbox/v1/...` |
| 401 | `unauthenticated` | Missing, invalid, expired or revoked bearer key; check environment and contact support |
| 403 | `permission_denied` | Wrong source IP, inactive account or missing current read/product/underlying/market eligibility; also browser Origin rejection |
| 403 | `action_unavailable` | Missing permission for a new quote or acceptance on a readable resource |
| 404 | `quote_not_found` | Missing or other-account quote; no ownership information is exposed |
| 409 | `idempotency_conflict` | Same scoped operation UUID with different canonical request |
| 409 | `quote_expired` | Quote was not accepted before its exclusive expiry |
| 409 | `quote_already_accepted` | Quote already booked under a different acceptance UUID; recover with the original UUID |
| 409 | `insufficient_funds` | Funded-only account cannot cover the immutable pay amount; no new booking is created by this rejection |
| 409 | `insufficient_credit` | Available funds and permitted credit cannot cover the immutable pay amount; resolve capacity |
| 413 | `request_too_large` | Body exceeds configured bounds; keep requests minimal. Ingress may return a non-JSON 413 |
| 415 | `unsupported_media_type` | Missing/unsupported Content-Type or Content-Encoding |
| 429 | `rate_limited` | Delay and retry the original command, honoring Retry-After if present |
| 503 | `pricing_unavailable` | Pricing absent, unavailable or timed out; do not invent prices |
| 503 | `quote_unavailable` | Invalid pricing result or changed authorization/product snapshot |
| 503 | `funding_source_unavailable` | Desk admission capability or required USD marks unavailable; preserve the original operation for recovery |
| 503 | `catalogue_unavailable` | Catalogue or authorization storage unavailable; back off before reading again |
| 503 | `service_unavailable` | Database/internal failure or request timeout; preserve original command identity |

Wrong HTTP methods return 405 with `Allow: POST` for quote/accept routes or
`Allow: GET` for read routes.
Unknown paths return 404 (ingress may return its own body). Use the authenticated
[heartbeat](#get-v1heartbeat) for connectivity checks.

### Wrong-environment keys

New sandbox keys start with `otc_sandbox_`. Production `/v1/get_quote` and
`/v1/accept` reject these with HTTP 401 `sandbox_key_on_production` and an
explanation directing you to `https://api.elkcrypto.com/sandbox/v1/...`.
The prefix is a diagnostic marker, not authorization: never alter it. Keys
are authenticated against separate databases and cannot grant cross-environment
access. Legacy unmarked sandbox keys receive generic `unauthenticated` on
production; replace them for the clearer diagnostic.

## Integration checklist

- Use a trusted HTTPS URL, secret storage and approved egress IPs.
- Implement decimal parsing, final pay/receive amounts and expiry handling.
- Journal operation UUIDs/body before sending; recover across process restarts.
- Parse HTTP status/content type and retain response request IDs.
- Reconcile unknown outcomes; never retry acceptance as a new trade.
- Complete the [sandbox scenarios](#exercise-error-responses)
  and check automatic progress. Production access is a separate approval.


---

<a id="client-certification"></a>

# Sandbox integration

Use **`https://api.elkcrypto.com/sandbox`** with the sandbox API key provided by your
onboarding contact. All customers use this base URL; your key identifies your
account. Sandbox keys do not work at `https://api.elkcrypto.com`, and production
keys do not work in the sandbox. Confirm your access is activated before testing.

The sandbox records your integration's progress automatically as it handles
requests. There is no results form to submit or manual checklist review. Once
all scenarios are recorded, your key is marked complete and staff can issue a
separate production key after the normal account approvals.

## What to call

| Action | Method and URL |
| --- | --- |
| Request or retry a quote | `POST https://api.elkcrypto.com/sandbox/v1/get_quote` |
| Accept or retry acceptance | `POST https://api.elkcrypto.com/sandbox/v1/accept` |
| Check your progress | `GET https://api.elkcrypto.com/sandbox/v1/sandbox/progress` |

Every request requires `Authorization: Bearer <your sandbox key>`. Your outbound
IP must be approved for that key. Newly issued sandbox keys start with
`otc_sandbox_`. Sending one to production `/v1/...` returns HTTP 401
`sandbox_key_on_production` with instructions to use `/sandbox/v1/...`.
Do not change or remove the key prefix. Legacy sandbox keys without this marker
still work in the sandbox, but production can only return generic
`unauthenticated` for them; ask for a replacement key for explicit diagnostics.
Keep HTTPS certificate and hostname verification
enabled. Never send your key in a URL, support ticket or log.

Every POST also requires `Content-Type: application/json` and an
`Idempotency-Key` containing a UUID. Use a fresh UUID for each new operation;
reuse the original UUID and body for a retry. Acceptance has its own UUID,
separate from the quote request. The progress GET needs neither a body nor an
idempotency key.

## Set up the examples

These examples use curl and Python 3. Save the key in a private header file so it
does not appear in shell history or the curl command line:

```sh
mkdir -m 700 sandbox-test
cd sandbox-test
umask 077
python3 - <<'PY'
import getpass, os
key = getpass.getpass('Sandbox API key: ')
if not key or any(c.isspace() for c in key):
    raise SystemExit('Invalid key input')
fd = os.open('auth.headers', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as output:
    output.write('Authorization: Bearer ' + key + '\n')
PY
BASE_URL=https://api.elkcrypto.com/sandbox
new_id() { python3 -c 'import uuid; print(uuid.uuid4())'; }
post() {
  curl --connect-timeout 5 --max-time 10 \
    --header @auth.headers --header 'Content-Type: application/json' \
    --header "Idempotency-Key: $2" --data-binary "@$3" \
    --dump-header "$4.headers" --output "$4.json" \
    --write-out 'HTTP %{http_code}\n' "$BASE_URL$1"
  python3 -m json.tool "$4.json"
}
```

Run the following blocks in that same shell. Keep request IDs and private receipts
when implementing retries in your own integration. Inspect HTTP status and JSON
`code`: an HTTP error does not necessarily make curl exit nonzero.

## Request buy and sell quotes

```sh
BUY_ID=$(new_id)
printf '%s\n' '{"symbol":"USDT/USD","market":"OTC-SPOT","side":"buy","quantity":"1000"}' > buy.json
post /v1/get_quote "$BUY_ID" buy.json buy-response
# Repeat the exact request to exercise quote replay.
post /v1/get_quote "$BUY_ID" buy.json buy-replay

SELL_ID=$(new_id)
printf '%s\n' '{"symbol":"USDT/USD","market":"OTC-SPOT","side":"sell","quantity":"1000"}' > sell.json
post /v1/get_quote "$SELL_ID" sell.json sell-response
```

Both return HTTP 200. Sandbox USDT/USD prices are fixed: buy `1.001`, sell `0.999`.
For quantity `1000`, buying pays `1001` USD and receives `1000` USDT; selling pays
`1000` USDT and receives `999` USD. Amounts are decimal strings.
The quantity step, minimum quantity and price tick are `0.0001`.

## Accept and retry

Quotes last at most 30 seconds. Run this promptly after obtaining the buy quote.
If it has expired, request a fresh buy quote with a new UUID first.

```sh
python3 - <<'PY'
import json
quote = json.load(open('buy-response.json'))
with open('accept.json', 'w') as output:
    json.dump({'quote_id': quote['quote_id']}, output)
PY
ACCEPT_ID=$(new_id)
post /v1/accept "$ACCEPT_ID" accept.json accepted
post /v1/accept "$ACCEPT_ID" accept.json accept-replay
# A different acceptance operation for the same quote must be rejected.
post /v1/accept "$(new_id)" accept.json duplicate-acceptance
```

The first two responses are HTTP 200 with the same `trade_id` and quote terms.
The last is HTTP 409 `quote_already_accepted`. After an uncertain acceptance,
retry the original UUID and body—even after expiry—rather than requesting a
replacement trade. See [recovery rules](#idempotency-and-recovery).

## Exercise error responses

Use the same POST helper and authentication. Each new operation gets a fresh UUID,
except for the deliberate idempotency-conflict test below.

| Check ID | Request and expected response |
| --- | --- |
| `buy_quote` | `POST /v1/get_quote`, `USDT/USD`, side `buy`, quantity `1000`: HTTP 200. |
| `sell_quote` | `POST /v1/get_quote`, `USDT/USD`, side `sell`, quantity `1000`: HTTP 200. |
| `accept_quote` | `POST /v1/accept` with an unexpired quote's `quote_id`: HTTP 200. |
| `quote_replay` | Repeat a successful quote request with its original UUID and body: HTTP 200, same receipt. |
| `accept_replay` | Repeat successful acceptance with its original UUID and body: HTTP 200, same trade ID. |
| `idempotency_conflict` | `POST /v1/get_quote` using `BUY_ID` again but quantity `2000`: HTTP 409 `idempotency_conflict`. |
| `duplicate_acceptance` | `POST /v1/accept` for an already accepted quote, with a new UUID: HTTP 409 `quote_already_accepted`. |
| `expired_quote` | Request a fresh quote, leave it unaccepted until after `expires_at`, then `POST /v1/accept`: HTTP 409 `quote_expired`. |
| `invalid_input` | `POST /v1/get_quote` with quantity `0`: HTTP 400 `invalid_request`. |
| `unsupported_pair` | `POST /v1/get_quote` with an unknown symbol such as `FOO/BAR`: HTTP 403 `permission_denied`. |

Use valid normal fields for each negative test except the field being tested.
No extra keys, accounts or permission grants are needed. Failed authentication
cannot be attributed to your key and does not count toward completion. HTTPS
verification remains your responsibility; the server cannot observe your client's
certificate-validation settings.

## View progress and move to production

```sh
curl --connect-timeout 5 --max-time 10 --header @auth.headers \
  "$BASE_URL/v1/sandbox/progress" --output progress.json
python3 -m json.tool progress.json
```

The response identifies your `key_id`, the `sandbox-auto-v1` checklist version,
`passed_checks`, `missing_checks`, and `completed`. When all ten checks are
recorded, `completed` becomes `true` and `completed_at` contains the completion
time. Passed checks remain recorded.

Progress is tracked per key; a replacement key starts fresh. Run the scenarios
through your integration. Retry availability errors with the original UUID and body.

Once complete, request production access from your onboarding contact. Use the
separate production key with **`https://api.elkcrypto.com`**. The progress endpoint
is sandbox-only.


---


## Guides

- [Quickstart](/docs/quickstart)
- [Integration guide](/docs/integration-guide)
- [API reference](/docs/api-reference)
- [Sandbox certification](/docs/client-certification)

## Endpoints

[Endpoint reference](/docs/endpoints) · [OpenAPI specification](/openapi.yaml)

## Markdown export

[Download the complete documentation](/llms-full.md), including all guides and the OpenAPI contract.


---


Request parameters, response schemas, and examples for each endpoint.

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/v1/catalogue` | [Read eligible products and centrally selected source capabilities](/docs/endpoints/catalogue) |
| GET | `/v1/sandbox/progress` | [Read automatic progress for the authenticated sandbox key](/docs/endpoints/sandbox_progress) |
| POST | `/v1/get_quote` | [Obtain a new caller-specific Spot quote or recover its original result](/docs/endpoints/get_quote) |
| POST | `/v1/accept` | [Book an owned quote exactly once or recover its original acceptance](/docs/endpoints/accept) |
| GET | `/v1/heartbeat` | [Check authenticated API and account-authority reachability](/docs/endpoints/heartbeat) |
| GET | `/v1/balances` | [Read the authenticated client's desk-owned balances and credit display](/docs/endpoints/balances) |
| GET | `/v1/orders` | [Read the authenticated account's API orders, newest first](/docs/endpoints/orders) |
| GET | `/v1/orders/{order_id}` | [Read an owned API order and its current reporting status](/docs/endpoints/order) |

[Download OpenAPI](/openapi.yaml) · [Complete documentation as Markdown](/llms-full.md)


---

# Endpoint details


---

## GET /v1/catalogue

Read eligible products and centrally selected source capabilities

Lists products available to your account, including quantity rules and pricing availability. Requires ViewQuotes and an approved source IP. Use limit and after_id for pagination. No request body is required.

---

## GET /v1/sandbox/progress

Read automatic progress for the authenticated sandbox key

Sandbox only. Records observed API scenarios automatically. No request body, query parameters or idempotency key. Production returns 404. Completion does not grant production access. Replaced keys start with fresh progress.

---

## POST /v1/get_quote

Obtain a new caller-specific Spot quote or recover its original result

Returns a quote for the requested symbol, side and quantity. Requires ViewQuotes, SubmitRfq and access to the requested product and market. Supply market when the symbol is available in multiple eligible markets. Retries with the same Idempotency-Key and body return the original quote, including its original price and expires_at. Replay requires read access.

---

## POST /v1/accept

Book an owned quote exactly once or recover its original acceptance

Accepts a quote by quote_id using its original terms. Requires ViewQuotes, AcceptTrade, product and market access, and sufficient funds or credit. The quote must be unexpired for a new acceptance. Use a distinct Idempotency-Key for acceptance; retries with that key and body return the existing order and its current status, including after quote expiry. Replay requires read access.

---

## GET /v1/heartbeat

Check authenticated API and account-authority reachability

Requires a valid key, approved source IP, active enrolled account, ViewQuotes and current KYC for linked desk clients. No body, query parameters or Content-Encoding is accepted. No Content-Type or Idempotency-Key is needed. Returns API and account-authority connectivity checks. Poll every 15 seconds; use backoff and jitter after failures.

---

## GET /v1/balances

Read the authenticated client's desk-owned balances and credit display

Returns asset balances, holds, available funds and USD credit. Requires a linked account, current KYC, an approved IP and ViewQuotes. Available credit equals limit minus outstanding exposure minus holds. A zero credit limit permits funded orders only. No request body is required.

---

## GET /v1/orders

Read the authenticated account's API orders, newest first

Returns up to 50 orders. No body, Content-Type or Idempotency-Key is needed. Requires ViewQuotes and market access. Results are scoped to your account.

---

## GET /v1/orders/{order_id}

Read an owned API order and its current reporting status



---

<a id="openapi-contract"></a>

# OpenAPI contract

````yaml
openapi: 3.1.0
info:
  title: OTC Public Quote API
  version: 0.1.0
  description: >-
    Spot quotes, quote acceptance, orders, balances and sandbox certification.
    Authenticate with an environment-specific bearer key.
servers:
  - url: https://api.elkcrypto.com/sandbox
    description: Shared sandbox;  use a sandbox key after access activation.
  - url: https://api.elkcrypto.com
    description: Production; use a separate production key after approval.
security:
  - ApiKey: []
tags:
  - name: Quotes
    description: Authenticated counterparty-bound quote issuance and trade booking.
paths:
  /v1/catalogue:
    get:
      operationId: catalogue
      tags: [Quotes]
      summary: Read eligible products and centrally selected source capabilities
      description: >-
        Lists products available to your account, including quantity rules and
        pricing availability. Requires ViewQuotes and an approved source IP.
        Use limit and after_id for pagination. No request body is required.
      parameters:
        - $ref: '#/components/parameters/RequestId'
        - name: limit
          in: query
          required: false
          description: Maximum products per page, integer 1 through 200.
          schema: {type: integer, minimum: 1, maximum: 200, default: 50}
        - name: after_id
          in: query
          required: false
          description: Exclusive product UUID cursor from next_after_id; omit on the first page.
          schema:
            $ref: '#/components/schemas/Identifier'
      responses:
        '200':
          description: Eligible product page; pricing availability is indicative capability only.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CataloguePage'
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '405':
          description: invalid_request; only GET is supported.
          headers:
            Allow:
              required: true
              schema: {type: string, const: GET}
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
        '429':
          $ref: '#/components/responses/RateLimited'
        '503':
          description: catalogue_unavailable or service_unavailable; database or authorization storage failure.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
  /v1/sandbox/progress:
    get:
      operationId: sandbox_progress
      summary: Read automatic progress for the authenticated sandbox key
      servers:
        - url: https://api.elkcrypto.com/sandbox
      description: >-
        Sandbox only. Records observed API scenarios automatically. No request body,
        query parameters or idempotency key. Production returns 404. Completion
        does not grant production access. Replaced keys start with fresh progress.
      responses:
        '200':
          description: Current per-key progress
          content:
            application/json:
              schema:
                type: object
                required: [key_id, account_id, checklist_version, completed, passed_checks, missing_checks, first_observed_at, completed_at, expires_at_ms, revoked_at_ms]
                additionalProperties: false
                properties:
                  key_id: {type: string, format: uuid}
                  account_id: {type: string, format: uuid}
                  checklist_version: {type: string, const: sandbox-auto-v1}
                  completed: {type: boolean}
                  passed_checks:
                    type: array
                    uniqueItems: true
                    items: {type: string}
                  missing_checks:
                    type: array
                    uniqueItems: true
                    items: {type: string}
                  first_observed_at: {type: [string, 'null'], format: date-time}
                  completed_at: {type: [string, 'null'], format: date-time}
                  expires_at_ms: {type: integer, format: int64}
                  revoked_at_ms: {type: [integer, 'null'], format: int64}
        '401':
          description: Invalid, expired or revoked sandbox key
        '403':
          description: Source IP or account not authorized
        '404':
          description: Route not present in production
        '503':
          description: Progress storage unavailable; retry later
  /v1/get_quote:
    post:
      operationId: get_quote
      tags: [Quotes]
      summary: Obtain a new caller-specific Spot quote or recover its original result
      description: >-
        Returns a quote for the requested symbol, side and quantity. Requires
        ViewQuotes, SubmitRfq and access to the requested product and market.
        Supply market when the symbol is available in multiple eligible markets.
        Retries with the same Idempotency-Key and body return the original quote,
        including its original price and expires_at. Replay requires read access.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
        - $ref: '#/components/parameters/RequestId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/QuoteRequest'
            example:
              symbol: BTC/USD
              side: buy
              quantity: '0.25'
      responses:
        '200':
          description: >-
            Quote with price, pay/receive amounts and expires_at.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Quote'
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: idempotency_conflict; same scoped key with different canonical terms.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
        '413':
          $ref: '#/components/responses/TooLarge'
        '415':
          $ref: '#/components/responses/UnsupportedMediaType'
        '429':
          $ref: '#/components/responses/RateLimited'
        '503':
          description: >-
            pricing_unavailable for absent, unavailable or timed-out pricing;
            quote_unavailable for invalid pricing or changed authorization/product
            snapshot; service_unavailable for an internal failure.
            Retry using the original Idempotency-Key and request body.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
  /v1/accept:
    post:
      operationId: accept
      tags: [Quotes]
      summary: Book an owned quote exactly once or recover its original acceptance
      description: >-
        Accepts a quote by quote_id using its original terms. Requires ViewQuotes,
        AcceptTrade, product and market access, and sufficient funds or credit.
        The quote must be unexpired for a new acceptance. Use a distinct
        Idempotency-Key for acceptance; retries with that key and body return
        the existing order and its current status, including after quote expiry.
        Replay requires read access.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
        - $ref: '#/components/parameters/RequestId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AcceptRequest'
            example:
              quote_id: 22222222-2222-4222-8222-222222222222
      responses:
        '200':
          description: >-
            Order ID, quote terms, accepted_at and current status.
            Initial status is pending; subsequent statuses are filled or cancelled.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Acceptance'
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: >-
            quote_not_found. Missing and foreign-account quotes produce identical
            responses after current account/IP validation; no terms or ownership leak.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
        '409':
          description: >-
            idempotency_conflict for different canonical terms under the same
            scoped key; quote_already_accepted for an owned readable quote booked
            under another key; quote_expired for an owned readable unaccepted
            quote that has expired; insufficient_funds or insufficient_credit
            when available capacity cannot cover the pay amount.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
        '413':
          $ref: '#/components/responses/TooLarge'
        '415':
          $ref: '#/components/responses/UnsupportedMediaType'
        '429':
          $ref: '#/components/responses/RateLimited'
        '503':
          description: >-
            service_unavailable for an internal failure;
            funding_source_unavailable when funding capacity cannot be checked.
            Retry using the original Idempotency-Key and request body.
          headers:
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
            Cache-Control:
              $ref: '#/components/headers/NoStore'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
  /v1/heartbeat:
    get:
      operationId: heartbeat
      tags: [Health]
      summary: Check authenticated API and account-authority reachability
      description: >-
        Requires a valid key, approved source IP, active enrolled account, ViewQuotes
        and current KYC for linked desk clients. No body, query parameters or
        Content-Encoding is accepted. No Content-Type or Idempotency-Key is needed.
        Returns API and account-authority connectivity checks. Poll every
        15 seconds; use backoff and jitter after failures.
      responses:
        '200':
          description: API and current account-authority checks succeeded
          headers:
            Cache-Control:
              $ref: '#/components/headers/NoStore'
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [status, as_of, checks]
                properties:
                  status:
                    type: string
                    const: ok
                  as_of:
                    $ref: '#/components/schemas/UtcTimestamp'
                  checks:
                    type: object
                    additionalProperties: false
                    required: [api, account_authority]
                    properties:
                      api:
                        type: string
                        const: ok
                      account_authority:
                        type: string
                        const: ok
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          description: service_unavailable; API/database/account authority could not be checked
  /v1/balances:
    get:
      operationId: balances
      tags: [Balances]
      summary: Read the authenticated client's desk-owned balances and credit display
      description: >-
        Returns asset balances, holds, available funds and USD credit.
        Requires a linked account, current KYC, an approved IP and ViewQuotes.
        Available credit equals limit minus outstanding exposure minus holds.
        A zero credit limit permits funded orders only. No request body is required.
      responses:
        '200':
          description: Current balances, holds and credit
          headers:
            Cache-Control:
              $ref: '#/components/headers/NoStore'
            X-Request-ID:
              $ref: '#/components/headers/RequestId'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Balances'
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          description: service_unavailable; desk contract is unavailable, invalid or not installed
  /v1/orders:
    get:
      operationId: orders
      tags: [Orders]
      summary: Read the authenticated account's API orders, newest first
      description: >-
        Returns up to 50 orders. No body, Content-Type or Idempotency-Key is needed.
        Requires ViewQuotes and market access. Results are scoped to your account.
      parameters:
        - name: after_id
          in: query
          description: next_after_id from the preceding page
          schema:
            $ref: '#/components/schemas/Identifier'
      responses:
        '200':
          description: Account-scoped API order history
          content:
            application/json:
              schema:
                type: object
                required: [records, next_after_id]
                properties:
                  records:
                    type: array
                    maxItems: 50
                    items:
                      $ref: '#/components/schemas/Acceptance'
                  next_after_id:
                    type: [string, 'null']
                    format: uuid
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          description: service_unavailable; retry the read with bounded backoff
  /v1/orders/{order_id}:
    get:
      operationId: order
      tags: [Orders]
      summary: Read an owned API order and its current reporting status
      parameters:
        - name: order_id
          in: path
          required: true
          schema:
            $ref: '#/components/schemas/Identifier'
      responses:
        '200':
          description: Current order report with immutable quote terms
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Acceptance'
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: quote_not_found; missing and foreign orders are indistinguishable
        '503':
          description: service_unavailable; retry the read with bounded backoff
components:
  securitySchemes:
    ApiKey:
      type: http
      scheme: bearer
      description: >-
        Send Authorization: Bearer <key> over HTTPS. Each key is associated with
        an account and environment. Invalid, expired or revoked keys return 401.
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: >-
        Client-generated UUID, scoped to account and operation. Use the same
        UUID and body for retries. Decimal strings are normalized and JSON
        property order is ignored when comparing requests. A changed request
        with the same UUID returns idempotency_conflict.
      schema:
        $ref: '#/components/schemas/Identifier'
    RequestId:
      name: X-Request-ID
      in: header
      required: false
      description: >-
        Optional request tracing UUID. The server generates one if omitted.
      schema:
        $ref: '#/components/schemas/Identifier'
  headers:
    RequestId:
      description: Request tracing UUID, also present in error bodies.
      required: true
      schema:
        $ref: '#/components/schemas/Identifier'
    NoStore:
      description: Authenticated responses must not be cached.
      required: true
      schema:
        type: string
        const: no-store
  schemas:
    CataloguePage:
      type: object
      additionalProperties: false
      required: [records, next_after_id]
      properties:
        records:
          type: array
          maxItems: 200
          items:
            $ref: '#/components/schemas/CatalogueProduct'
        next_after_id:
          description: Exclusive cursor for the next page, null when no lookahead product exists.
          oneOf:
            - $ref: '#/components/schemas/Identifier'
            - type: 'null'
    CatalogueProduct:
      type: object
      additionalProperties: false
      required: [product_id, instrument_id, market_id, market, base_asset_id, quote_asset_id, symbol, enabled, broker_rules, underlying_ids, offerings, pricing_available]
      properties:
        product_id: {$ref: '#/components/schemas/Identifier'}
        instrument_id: {$ref: '#/components/schemas/Identifier'}
        market_id: {$ref: '#/components/schemas/Identifier'}
        market: {$ref: '#/components/schemas/Market'}
        base_asset_id: {$ref: '#/components/schemas/Identifier'}
        quote_asset_id: {$ref: '#/components/schemas/Identifier'}
        symbol: {$ref: '#/components/schemas/Symbol'}
        enabled: {type: boolean, const: true}
        broker_rules: {$ref: '#/components/schemas/BrokerRules'}
        underlying_ids:
          type: array
          minItems: 1
          uniqueItems: true
          items: {$ref: '#/components/schemas/Identifier'}
        offerings:
          type: array
          maxItems: 1
          description: >-
            Selected centrally routed offering only, not an input choice. A retained
            stale, disabled or withdrawn offering may be present but unavailable.
            No route or no matching selected pair yields an empty array.
          items: {$ref: '#/components/schemas/SelectedOffering'}
        pricing_available:
          type: boolean
          description: Current selected RFQ capability only; not a live quote or execution guarantee.
    BrokerRules:
      description: >-
        Independent broker economics. Legacy-fixed products retain these rules in
        addition to source quantity and raw-price rules. Dynamic products have no
        invented global economics and use selected source precision.
      oneOf:
        - type: object
          additionalProperties: false
          required: [mode, price_tick, minimum_quantity, quantity_step]
          properties:
            mode: {type: string, const: legacy_fixed}
            price_tick: {$ref: '#/components/schemas/CanonicalDecimal'}
            minimum_quantity: {$ref: '#/components/schemas/CanonicalDecimal'}
            quantity_step: {$ref: '#/components/schemas/CanonicalDecimal'}
        - type: object
          additionalProperties: false
          required: [mode]
          properties:
            mode: {type: string, const: venue_dynamic}
    SelectedOffering:
      type: object
      additionalProperties: false
      required: [gateway_id, provider, offering_id, revision, rules, present, available, last_seen_at_ms, offering_source_observed_at_ms, offering_inventory_mode, inventory_mode, source_observed_at_ms, generated_at_ms, expires_at_ms]
      properties:
        gateway_id:
          type: string
          pattern: '^[a-z][a-z0-9_-]{0,63}$'
          description: Server-selected connection identity; never accepted as a customer selector.
        provider: {type: string, pattern: '^[a-z][a-z0-9_-]{0,31}$'}
        offering_id: {type: string, pattern: '^[A-Za-z0-9][A-Za-z0-9_./-]{0,95}$'}
        revision: {type: string, pattern: '^[0-9a-f]{64}$'}
        rules: {$ref: '#/components/schemas/OfferingRules'}
        present: {type: boolean}
        available:
          type: boolean
          description: Current connection/offering lease and controls; RFQ support is separate in rules.
        last_seen_at_ms: {type: integer, format: int64, minimum: 0}
        offering_source_observed_at_ms: {type: integer, format: int64, minimum: 0}
        offering_inventory_mode: {$ref: '#/components/schemas/InventoryMode'}
        inventory_mode: {$ref: '#/components/schemas/InventoryMode'}
        source_observed_at_ms: {type: integer, format: int64, minimum: 0}
        generated_at_ms: {type: integer, format: int64, minimum: 0}
        expires_at_ms: {type: integer, format: int64, minimum: 0}
    InventoryMode:
      type: string
      enum: [reviewed_configuration, live_discovery]
      description: Metadata provenance, not a provider entitlement or session-health certification.
    OfferingRules:
      type: object
      additionalProperties: false
      required: [instrument_id, base_asset, quote_asset, kind, provider_instrument, provider_stream_instrument, rfq_supported, indicative_stream_supported, enabled, minimum_quantity, maximum_quantity, quantity_step, price_tick, price_significant_digits]
      properties:
        instrument_id: {type: string, pattern: '^[A-Za-z0-9][A-Za-z0-9_./-]{0,95}$'}
        base_asset: {$ref: '#/components/schemas/Asset'}
        quote_asset: {$ref: '#/components/schemas/Asset'}
        kind: {type: string, const: SPOT}
        provider_instrument: {type: string, pattern: '^[A-Za-z0-9][A-Za-z0-9_./-]{0,95}$'}
        provider_stream_instrument: {type: string, pattern: '^(?:[A-Za-z0-9][A-Za-z0-9_./-]{0,95})?$'}
        rfq_supported: {type: boolean}
        indicative_stream_supported: {type: boolean}
        enabled: {type: boolean}
        minimum_quantity: {$ref: '#/components/schemas/Decimal'}
        maximum_quantity: {$ref: '#/components/schemas/Decimal'}
        quantity_step: {$ref: '#/components/schemas/Decimal'}
        price_tick:
          oneOf:
            - {$ref: '#/components/schemas/Decimal'}
            - {type: string, const: ''}
        price_significant_digits: {type: integer, minimum: 0, maximum: 18}
      oneOf:
        - properties:
            price_tick: {$ref: '#/components/schemas/Decimal'}
            price_significant_digits: {const: 0}
        - properties:
            price_tick: {const: ''}
            price_significant_digits: {minimum: 1, maximum: 18}
      description: >-
        Exact source constraints. Quantity must satisfy min/MAX/step, without rounding.
        Raw price precision is either fixed tick or significant digits, never a guessed
        conversion. Legacy broker final-price precision is independently retained.
    Identifier:
      type: string
      format: uuid
      minLength: 36
      maxLength: 36
      pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
      description: UUID identifier; server responses use lowercase canonical spelling.
    QuoteId:
      type: string
      format: uuid
      minLength: 36
      maxLength: 36
      pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$'
      description: >-
        Cryptographically random server-generated UUIDv4. Nonselectable and
        immutably account-bound. Knowledge of an ID never grants access.
    Decimal:
      type: string
      minLength: 1
      maxLength: 39
      pattern: '^(?!0(?:\.0+)?$)(?:0|[1-9][0-9]{0,19})(?:\.[0-9]{1,18})?$'
      description: >-
        Positive exact decimal string, up to 20 integer and 18 fractional digits.
        No sign, exponent, whitespace, integer leading zeros or JSON numbers.
        Catalogue tick/lot/minimum rules also apply. Trailing fractional zeros
        normalize before comparison and fingerprinting (1.0 equals 1).
    CanonicalDecimal:
      type: string
      minLength: 1
      maxLength: 39
      pattern: '^(?!0$)(?:0|[1-9][0-9]{0,19})(?:\.[0-9]{0,17}[1-9])?$'
      description: Positive exact decimal; canonical output has no trailing fractional zeros.
    UtcTimestamp:
      type: string
      format: date-time
      pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$'
      description: UTC ISO 8601, exactly millisecond precision; server/database authority.
    Asset:
      type: string
      pattern: '^[A-Z][A-Z0-9]{1,11}$'
    Symbol:
      type: string
      pattern: '^[A-Z][A-Z0-9]{1,11}/[A-Z][A-Z0-9]{1,11}$'
      description: Distinct base/quote asset codes, such as BTC/USD.
    Market:
      type: string
      pattern: '^[A-Z][A-Z0-9-]{1,23}$'
    AssetAmount:
      type: object
      additionalProperties: false
      required: [asset, amount]
      properties:
        asset:
          $ref: '#/components/schemas/Asset'
        amount:
          $ref: '#/components/schemas/CanonicalDecimal'
    Side:
      type: string
      enum: [buy, sell]
      description: >-
        Client perspective. Buy acquires base and owes quote; sell delivers base
        and receives quote. Price is quote-asset units per one base unit.
    QuoteRequest:
      type: object
      additionalProperties: false
      required: [symbol, side, quantity]
      properties:
        symbol:
          $ref: '#/components/schemas/Symbol'
        market:
          oneOf:
            - $ref: '#/components/schemas/Market'
            - type: 'null'
          description: Required on market_required; omission and null are equivalent.
        side:
          $ref: '#/components/schemas/Side'
        quantity:
          $ref: '#/components/schemas/Decimal'
          description: Base units; never resized by pricing.
    AcceptRequest:
      type: object
      additionalProperties: false
      required: [quote_id]
      properties:
        quote_id:
          $ref: '#/components/schemas/QuoteId'
    Quote:
      type: object
      additionalProperties: false
      required: [quote_id, symbol, market, side, price, pay, receive, issued_at, expires_at]
      description: >-
        Quoted price, final pay/receive amounts and expiry. Use pay and receive
        as the complete exchange amounts.
      properties:
        quote_id:
          $ref: '#/components/schemas/QuoteId'
        symbol:
          $ref: '#/components/schemas/Symbol'
        market:
          $ref: '#/components/schemas/Market'
        side:
          $ref: '#/components/schemas/Side'
        price:
          $ref: '#/components/schemas/CanonicalDecimal'
          description: Quote-asset units per base unit.
        pay:
          $ref: '#/components/schemas/AssetAmount'
        receive:
          $ref: '#/components/schemas/AssetAmount'
        issued_at:
          $ref: '#/components/schemas/UtcTimestamp'
        expires_at:
          $ref: '#/components/schemas/UtcTimestamp'
          description: Exclusive expiry. Retry never refreshes the quote.
      example:
        quote_id: 22222222-2222-4222-8222-222222222222
        symbol: BTC/USD
        market: OTC-SPOT
        side: buy
        price: '65000'
        pay: {asset: USD, amount: '16250'}
        receive: {asset: BTC, amount: '0.25'}
        issued_at: '2026-09-23T14:30:00.000Z'
        expires_at: '2026-09-23T14:30:05.000Z'
    SignedAmount:
      type: string
      maxLength: 128
      pattern: '^-?(0|[1-9][0-9]*)(\.[0-9]+)?$'
      description: Signed finite plain decimal string; never floating point JSON or exponent notation.
    Balances:
      type: object
      additionalProperties: false
      required: [schema_version, source, as_of, balances, credit]
      properties:
        schema_version:
          type: integer
          enum: [1, 2]
        source:
          type: string
          const: desk_journal
        as_of:
          $ref: '#/components/schemas/UtcTimestamp'
          description: Desk statement observation time, not a provider mark timestamp.
        balances:
          type: array
          maxItems: 1000
          items:
            type: object
            additionalProperties: false
            required: [asset, balance]
            properties:
              asset:
                type: string
                maxLength: 64
                pattern: '^[A-Z0-9_-]+$'
              balance:
                $ref: '#/components/schemas/SignedAmount'
              on_hold:
                $ref: '#/components/schemas/SignedAmount'
              available:
                $ref: '#/components/schemas/SignedAmount'
        credit:
          type: object
          additionalProperties: false
          required: [currency, basis, limit, outstanding, available]
          properties:
            currency:
              type: string
              const: USD
            basis:
              type: string
              enum: [desk_total_owed, asset_deficits_v1]
            limit:
              oneOf:
                - $ref: '#/components/schemas/SignedAmount'
                - type: 'null'
            outstanding:
              $ref: '#/components/schemas/SignedAmount'
            on_hold:
              $ref: '#/components/schemas/SignedAmount'
            available:
              oneOf:
                - $ref: '#/components/schemas/SignedAmount'
                - type: 'null'
      allOf:
        - if:
            properties:
              schema_version: {const: 2}
          then:
            properties:
              balances:
                items:
                  required: [asset, balance, on_hold, available]
              credit:
                required: [on_hold]
                properties:
                  basis: {const: asset_deficits_v1}
                  available:
                    $ref: '#/components/schemas/SignedAmount'
    Acceptance:
      type: object
      additionalProperties: false
      required: [order_id, trade_id, quote, accepted_at, status, updated_at]
      properties:
        order_id:
          $ref: '#/components/schemas/Identifier'
          description: Same opaque identifier as trade_id; preferred for order queries.
        status:
          type: string
          enum: [pending, filled, cancelled]
          description: Current order status.
        updated_at:
          $ref: '#/components/schemas/UtcTimestamp'
        trade_id:
          $ref: '#/components/schemas/Identifier'
        quote:
          $ref: '#/components/schemas/Quote'
        accepted_at:
          $ref: '#/components/schemas/UtcTimestamp'
          description: Time the quote was accepted.
    ApiError:
      type: object
      additionalProperties: false
      required: [code, message, request_id]
      properties:
        code:
          type: string
          enum:
            - invalid_request
            - market_required
            - unauthenticated
            - sandbox_key_on_production
            - permission_denied
            - action_unavailable
            - quote_not_found
            - idempotency_conflict
            - quote_expired
            - quote_already_accepted
            - insufficient_funds
            - insufficient_credit
            - funding_source_unavailable
            - request_too_large
            - unsupported_media_type
            - rate_limited
            - pricing_unavailable
            - quote_unavailable
            - service_unavailable
            - catalogue_unavailable
        message:
          type: string
          description: Safe human-readable text; not a stable parsing contract; no secret or denied terms.
        request_id:
          $ref: '#/components/schemas/Identifier'
      example:
        code: pricing_unavailable
        message: Pricing is unavailable.
        request_id: 77777777-7777-4777-8777-777777777777
  responses:
    InvalidRequest:
      description: >-
        market_required when an eligible symbol needs explicit market disambiguation;
        invalid_request for invalid JSON/schema/headers or catalogue-incompatible
        quantity. Unknown/duplicate JSON fields and duplicate semantic headers
        are rejected; errors do not echo credentials or private terms.
      headers:
        X-Request-ID:
          $ref: '#/components/headers/RequestId'
        Cache-Control:
          $ref: '#/components/headers/NoStore'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiError'
    Unauthenticated:
      description: >-
        unauthenticated for missing, malformed, unknown, expired or revoked keys.
        sandbox_key_on_production for a structurally valid sandbox-prefixed key
        on production routes; message explains the /sandbox base URL. This
        diagnostic does not confirm that the supplied key exists.
      headers:
        WWW-Authenticate:
          required: true
          schema:
            type: string
            const: Bearer
        X-Request-ID:
          $ref: '#/components/headers/RequestId'
        Cache-Control:
          $ref: '#/components/headers/NoStore'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiError'
    Forbidden:
      description: >-
        permission_denied for inactive account, disallowed IP or missing current
        read eligibility. Unknown and unauthorized requested products share this
        response. action_unavailable for missing new-operation mutation permission
        on an otherwise readable resource. Never expose denied quote terms or
        receipt contents. Committed readable retries do not need mutation permission.
      headers:
        X-Request-ID:
          $ref: '#/components/headers/RequestId'
        Cache-Control:
          $ref: '#/components/headers/NoStore'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiError'
    TooLarge:
      description: request_too_large. Configured body bound exceeded.
      headers:
        X-Request-ID:
          $ref: '#/components/headers/RequestId'
        Cache-Control:
          $ref: '#/components/headers/NoStore'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiError'
    UnsupportedMediaType:
      description: unsupported_media_type. Content-Type must be application/json.
      headers:
        X-Request-ID:
          $ref: '#/components/headers/RequestId'
        Cache-Control:
          $ref: '#/components/headers/NoStore'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiError'
    RateLimited:
      description: >-
        rate_limited. Configured admission limit reached. Delay then retry the
        original command; never substitute an idempotency key for uncertain work.
      headers:
        Retry-After:
          description: Optional delay in whole seconds.
          schema:
            type: integer
            minimum: 0
        X-Request-ID:
          $ref: '#/components/headers/RequestId'
        Cache-Control:
          $ref: '#/components/headers/NoStore'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiError'

````
