Skip to content

ccxt error normalization ​

ccxt throws messy error blobs: Invalid Api-Key, Passphrase wrong, fetch failed, ECONNRESET... each one needs a different fix, but the frontend just sees "Error".

src/lib/exchange-errors.ts is the mandatory translation step before any exchange call crosses the API boundary.

Error Normalization

Translation ​

ts
import { normalizeExchangeError } from '@/lib/exchange-errors';

const norm = normalizeExchangeError(err, 'okx');
// → {
//   code: 'invalid_passphrase',
//   status: 400,
//   messageKey: 'invalidPassphrase',
//   doc: 'live-trading',
//   hint: 'The Passphrase is the field you typed when creating the API on OKX — not your OKX login password.',
// }

Returns 4 key fields:

FieldPurpose
codePublic ExchangeErrorCode string (API-safe)
statusHTTP status the API boundary should return (4xx = user can fix)
messageKeyi18n key, frontend looks up zh/en table
docin-app docs slug (live-trading, api-keys, etc.)

Error code table ​

ExchangeErrorCodeTriggerUser action
invalid_api_keyOKX returns "API key does not exist"Re-copy the Key
invalid_passphraseOKX returns "Invalid Passphrase"Use the one you set at creation, not the login password
ip_not_whitelistedOKX returns "IP not in whitelist"Disable whitelist or add IP
permission_deniedOKX returns "no permission"Enable Read + Trade, do not enable Withdraw
invalid_signatureOKX returns "Invalid Sign"Copy the full Secret, don't trim
invalid_timestamp / expired_timestampClock skewRetry
rate_limited429Wait a few seconds
insufficient_balanceNot enough to place orderTop up
min_amountBelow minimumIncrease tradeAmount
symbol_not_foundWrong symbolSwitch symbol
network_errorfetch failed / ENOTFOUNDCheck network
exchange_unavailable503Wait
circuit_openBreaker open (3 fails / 60s)Wait 60s
auth_unknownFallbackOpen Settings

Entries that must go through normalize ​

Every exchange call that crosses the API boundary must use normalizeExchangeError:

RouteBehavior
/api/test-connectionOn failure, return 200 + {success:false, code, messageKey, doc, hint} (the test itself succeeded, the result is "fail")
/api/trade/panicIn REAL, market order failure → accumulate in errors[]
/api/trade/positionsIn REAL, manual close failure → 4xx + structured error
engine.ts three order sitesReturn EngineLog.remediationCode
engine.ts candle fetch failureAttach norm.code on EngineError.remediationCode and rethrow

Never return error.message to the API boundary — that's ccxt's internal string, may leak internals, and users can't read it.

Consistency rule ​

The JSON shape returned at the API boundary is fixed:

ts
{
  success: false,
  code: 'invalid_passphrase',     // ExchangeErrorCode
  messageKey: 'invalidPassphrase', // i18n key
  doc: 'live-trading',              // in-app doc slug
  hint: '...',                      // optional
  // Legacy field kept for backward compat:
  error: 'Raw message for debugging',  // not rendered to user, only logged
}

The frontend (StrategyTerminal, Sidebar, Onboarding modal) consistently uses code + messageKey + doc for rendering. The error field is logged only.

Why not use ccxt's built-in error types? ​

ccxt's AuthenticationError / ExchangeNotAvailable are coarse "categories" that don't distinguish:

  • Wrong API Key vs wrong Passphrase vs IP not whitelisted — all AuthenticationError
  • Timeout vs DNS failure vs 503 — all NetworkError

Our ExchangeErrorCode is a finer-grained, user-actionable classification aligned with our onboarding flow. The 1-click fix UX depends entirely on this precision.

Adding a new exchange ​

Add a BINANCE_PATTERNS (already there) next to OKX_PATTERNS. When adding a new OKX error code, extend the OKX_PATTERNS list first — don't invent a new ExchangeErrorCode unless none of the existing ones fit.

TodoAI · Turn trading ideas into automated strategies