API setup and security

How to Create an OKX API Key for Spot, Perpetuals and Demo Trading

Create an OKX API key for spot, perpetuals or demo trading; compare Exchange and DEX keys, choose Trade without Withdraw, and run a demo perpetual request.

Direct answer

Create an OKX Exchange API key with Read for account data and add Trade only when the application must place spot or perpetual orders; ordinary trading bots do not need Withdraw. One live key can cover spot and perpetuals when the account mode supports both, while demo trading needs a separate demo key and `x-simulated-trading: 1`. OKX DEX or Onchain access uses a separate developer-portal project and key.

Permission classes3Read, Trade and Withdraw.
IP limit per key20Bind only real production outbound addresses.
Non-IP inactivity expiry14 daysApplies to Trade/Withdraw keys; demo is excluded.
Recommended startRead onlyAdd Trade only after authentication succeeds.

The safest way to create an OKX API key

An API key should have one owner, one purpose and the smallest useful permission set. A portfolio dashboard normally needs Read only. A trading bot needs Read and Trade, but it does not automatically need Withdraw. A separate key makes it possible to revoke one integration without breaking every other application.

Use caseReadTradeWithdrawRecommended boundary
Portfolio or tax exportYesNoNoRead-only key; no order capability
Alerts and monitoringYesNoNoRead-only key; IP allowlist if hosted
Trading botYesOnly when requiredNoSeparate key, fixed IP, order limits in the app
Withdrawal automationYesAs requiredOnly after a security reviewIsolate from ordinary trading and apply independent controls

Three quantitative rules that affect production

RuleOfficial valueOperational consequence
Permission classes3Read, Trade and Withdraw can be reviewed separately; a bot does not require all three
IP addresses per keyUp to 20Multiple egress points are possible, but only actual production IPs should be listed
Non-IP key inactivity expiry14 daysTrade/Withdraw keys without an IP binding can expire after inactivity and need monitoring or rotation

These values turn “secure the key” into testable controls: permissions can be enumerated, egress addresses documented and key expiry monitored.

Configuration examples for real integrations

IntegrationData or actionPermissionAdditional boundary
Portfolio or tax dashboardBalances, fills and billsReadServer-side secret; scheduled retrieval
Price and risk alertsPublic market data plus account positionsReadUse unauthenticated public endpoints wherever possible
Execution botAccount queries, orders and cancellationsRead + TradeFixed IP, symbol allowlist, order/day limits and an emergency key-revoke path

Withdraw is not a normal trading-bot requirement. If automated withdrawals are truly necessary, isolate them into a separate service, key, approval flow and limit.

How do I create an OKX API key for perpetual contracts?

Create an Exchange API key in the trading account, enable Read and then Trade, and keep Withdraw off. Confirm the account mode supports derivatives before sending orders. A USDT-margined perpetual uses an instrument such as BTC-USDT-SWAP; spot uses BTC-USDT. The private order endpoint is the same POST /api/v5/trade/order, but the instrument, trade mode, position settings and margin requirements differ.

Can spot and perpetuals use the same OKX API key?

Yes, a live Exchange API key can authenticate both spot and perpetual requests when it has Trade permission and the account is configured for those products. It is still safer to create separate keys when different applications own the spot and derivatives strategies: separate credentials make revocation, IP allowlisting and log review narrower. Demo and live credentials should never be shared.

Is Trade permission enough, or does a bot need Withdraw?

For account reads, order placement and cancellation, use Read + Trade. Withdraw is not required for a normal spot or perpetual execution bot. Enabling it increases the consequence of a credential leak without improving order execution. If withdrawals must be automated, move that function to a separate service, separate key and separate approval path.

OKX official Exchange API documentation showing API key creation, Read, Trade and Withdraw permissions, IP binding and the 14-day inactivity rule
OKX Exchange API documentation: one trading-account key can be assigned Read, Trade and Withdraw permissions; the same section documents IP binding and inactivity expiry. Screenshot captured August 21, 2026. Open the official section ↗

How do I create an OKX demo trading API key?

Open Trade → Demo Trading → Personal Center → Demo Trading API, then create a dedicated demo key. Demo REST requests use the documented API host and must include x-simulated-trading: 1. OKX states that demo keys do not expire under the 14-day inactivity rule. A successful demo order validates request construction, but not live balances, production IPs or real-money risk controls.

OKX official demo trading API documentation showing demo endpoints, API key creation path and x-simulated-trading request header
OKX demo-trading documentation shows the separate Demo API key flow and the required x-simulated-trading: 1 header. Screenshot captured August 21, 2026. Open the official section ↗

What is the difference between OKX Exchange API and DEX or Onchain API?

API familyCredential locationMain purposeTypical asset control
Exchange V5 APIOKX trading account API settingsCentralized spot, perpetuals, balances and ordersAssets held in the exchange account
DEX / Onchain APIProject in the OKX developer portalOnchain quotes, routing and transaction constructionUser wallet signs or sends onchain transactions

The two products use similar authentication concepts but not the same project or API key. A DEX key does not grant centralized Exchange order permission, and an Exchange key is not the credential for the Onchain developer project.

OKX Onchain developer portal documentation showing how to generate a new DEX API key inside a project and view the secret key
Onchain credentials are created inside a developer-portal project, not in the centralized Exchange trading-account API settings. Screenshot captured August 21, 2026. Open the official guide ↗
OKX Onchain DEX API documentation showing required authentication headers and HMAC SHA256 signature steps
The Onchain DEX API uses its project key, passphrase, timestamp and signature headers when calling routes such as /api/v6/dex/aggregator/swap. Screenshot captured August 21, 2026. Open the official authentication page ↗

Minimal OKX perpetual API request in demo mode

This example uses OKX’s documented Python SDK pattern and explicitly selects demo mode. Replace the placeholders with a demo key, confirm the demo account mode, and change price or size only inside the simulated environment.

import okx.Trade as Trade

api = Trade.TradeAPI(
    "YOUR_DEMO_API_KEY",
    "YOUR_DEMO_SECRET_KEY",
    "YOUR_DEMO_PASSPHRASE",
    False,
    "1",  # 1 = demo trading; 0 would be live
)

result = api.place_order(
    instId="BTC-USDT-SWAP",
    tdMode="isolated",
    side="buy",
    ordType="limit",
    px="10000",
    sz="1",
)
print(result)

The SDK’s demo flag adds the simulated-trading behavior. A raw REST client must sign the request and add x-simulated-trading: 1 itself. Never paste a real Secret or Passphrase into browser JavaScript, chat or source control.

Step-by-step setup

  1. Write down the task first. State which application will use the key and whether it reads data or sends orders.
  2. Open OKX through the OKX registration page, then navigate to API settings inside the authenticated account. Create a key for this application rather than recycling an old credential. The referral offer provides 20% off trading fees.
  3. Select the minimum permission. Begin with Read; add Trade only after testing.
  4. Store all credential parts immediately. Put the API key, secret and passphrase in a secret manager or encrypted environment configuration. Do not paste them into chat, source code, screenshots or analytics logs.
  5. Bind the key to a stable outbound IP when possible. Confirm the IP seen by OKX is the one used by the production server.
  6. Test one private read request. Verify authentication, time synchronization and account scope before enabling order methods.
  7. Create separate demo credentials. Do not use a successful demo request as proof that live credentials or live risk controls are correct.

How OKX REST signatures work

The official authentication guide describes a pre-hash string assembled from the request timestamp, uppercase HTTP method, request path and request body. That string is signed with the API secret using HMAC SHA-256 and Base64 encoded. Private REST requests also send the API key, signature, timestamp and passphrase in the documented headers.

prehash = timestamp + METHOD + requestPath + body
signature = Base64(HMAC_SHA256(secret, prehash))

The request path must include its query string, and the body used for signing must match the body actually sent. Keep system time synchronized and never log the secret or raw credentials while debugging.

Common authentication failures

SymptomCheck firstSafe diagnostic
Invalid signatureMethod, path, body and Base64 encodingLog the pre-hash string with secrets redacted
Timestamp expiredServer clock and timestamp formatCompare the server clock with UTC
Invalid passphraseThe passphrase saved when the key was createdRecreate the key if the value cannot be recovered safely
Permission deniedRead, Trade or Withdraw scopeCall a read endpoint first; do not broaden permissions blindly
IP restrictionActual outbound IP of the running serverInspect egress from the production environment, not a laptop
Demo request failsDemo key and demo request requirementsRecheck the official demo-trading section

Pre-production security checklist

  • one key per integration and environment;
  • no API secrets committed to Git or bundled into browser JavaScript;
  • Withdraw disabled for ordinary dashboards and trading bots;
  • stable-IP allowlist where operationally possible;
  • logs redact the API key, secret, passphrase and signature;
  • a documented revoke-and-rotate procedure;
  • order-size, symbol and loss controls enforced by the application; and
  • a small live test only after demo and read-only checks pass.

When authentication is working, use the OKX fee calculator with the actual rate shown in your account rather than assuming one public headline rate applies to every user.

OKX referral offer Create an OKX account Check regional availability, complete verification, then start with a small deposit and withdrawal test. Get exclusive new-user welcome rewards and 20% off trading fees Open OKX

Frequently asked questions

Which OKX API permissions should I enable?

Start with Read. Add Trade only when the application must place or cancel orders. Leave Withdraw disabled unless a narrowly defined, reviewed workflow truly requires it.

Should I bind an OKX API key to an IP address?

Yes when your server or gateway has a stable outbound IP. An allowlist reduces where a leaked key can be used, but it does not replace secure secret storage or minimum permissions.

Are OKX demo and live API keys the same?

No. Treat demo and live trading as separate environments, create separate credentials, and use the demo-trading request requirements documented by OKX.

Why does OKX return an invalid signature error?

Common causes are a wrong timestamp, HTTP method, request path, body, secret, passphrase, or Base64-encoded HMAC result. Log the pre-hash string without logging the secret.

How many IP addresses can an OKX API key bind?

The OKX V5 documentation states that one API key can bind up to 20 IP addresses. A production integration should still list only its real outbound addresses.

Do OKX API keys expire?

OKX documents that a non-IP-bound key with Trade or Withdraw permission expires after 14 days of inactivity. Demo trading keys are excluded from that rule. Check the current account and documentation for the live status.

Can one OKX API key trade both spot and perpetuals?

A live Exchange API key with Trade permission can be used for both when the account mode and product access support them. The instrument IDs and trade modes still differ, and demo trading requires a separately created demo key.

Does a perpetual trading bot need Withdraw permission?

No. Read plus Trade is sufficient for ordinary account queries, order placement and cancellation. Withdraw should remain disabled unless a separately reviewed withdrawal workflow truly requires it.

Is an OKX DEX API key the same as an Exchange API key?

No. The Exchange V5 API key is created in the trading account for centralized spot and derivatives. The DEX or Onchain API uses a separate project and key in the OKX developer portal for onchain routing and transactions.