Getting started overview

Integrating with the OKEx API involves a sequence of steps designed to ensure secure and authorized access to its cryptocurrency exchange services. This guide focuses on the foundational process of setting up an OKEx account, generating the necessary API credentials, and successfully making an initial API request. The OKEx API supports both RESTful endpoints for synchronous operations and WebSocket interfaces for real-time market data and account updates.

The core components for API access are an API Key, Secret Key, and Passphrase, which together form the authentication mechanism for all authenticated requests. OKEx provides official SDKs for Python, Java, and Go, simplifying the integration process by handling cryptographic signing and request formatting.

This reference outlines the essential steps to move from account creation to a successful API call, providing a roadmap for developers beginning their integration journey with OKEx.

Quick Reference Table

Step What to do Where to go
1. Account Creation Register for an OKEx account. OKEx Registration Page
2. Identity Verification (KYC) Complete required identity verification levels. OKEx KYC Guide
3. API Key Generation Create an API Key, Secret Key, and Passphrase. Set appropriate permissions. OKEx API Management
4. Environment Setup Install a supported SDK or prepare your HTTP client. OKEx SDK Documentation
5. First Request Make an unauthenticated or authenticated API call. OKEx Public API Endpoints or OKEx Trade API Endpoints

Create an account and get keys

Before making any API calls, you need an OKEx account and a set of API credentials. This process ensures that your API interactions are secure and properly authorized.

Account Registration and KYC

  1. Register an account: Navigate to the OKEx registration page and sign up using your email or phone number. Follow the prompts to set up your password.
  2. Complete Identity Verification (KYC): OKEx, like other regulated financial service providers, requires users to complete Know Your Customer (KYC) verification. This typically involves submitting identification documents and may include facial recognition. The level of verification completed can affect API access limits and withdrawal thresholds. This is a common practice in the financial industry, as outlined by organizations like the Financial Crimes Enforcement Network (FinCEN) for anti-money laundering (AML) purposes.
  3. Enable Two-Factor Authentication (2FA): For enhanced security, enable 2FA on your account. This is a prerequisite for generating API keys. OKEx supports Google Authenticator and SMS 2FA.

Generating API Keys

Once your account is set up and secured with 2FA, you can generate API keys:

  1. Access API Management: Log in to your OKEx account and navigate to the API Management section, usually found under your profile or security settings.
  2. Create a new API Key: Click on the "Create API Key" button. You will be prompted to provide the following information:
    • API Key Name: A descriptive name for your API key (e.g., "MyTradingBot").
    • Passphrase: A unique password for this API key. This is separate from your account login password and is crucial for authenticating API requests. Keep this secure.
    • Permissions: Carefully select the permissions required for your application. Permissions dictate what actions your API key can perform (e.g., read-only market data, trading, withdrawals). Granting only necessary permissions adheres to the principle of least privilege, enhancing security.
    • IP Address Whitelist (Optional but Recommended): For production environments, it is highly recommended to whitelist specific IP addresses that will be making API requests. This restricts API access exclusively to those IPs.
  3. Record Credentials: After creation, OKEx will display your API Key and Secret Key. The Secret Key is shown only once and cannot be retrieved later. Copy both the API Key, Secret Key, and the Passphrase you set to a secure location immediately. Treat your Secret Key like your password.

Your first request

With your API credentials in hand, you can now make your first API request. This section demonstrates how to retrieve public market data, which typically does not require authentication, and then an authenticated request for account information.

Unauthenticated Request: Public Market Data

A common starting point is to fetch public market data, such as the current price of a cryptocurrency pair. This type of request does not require your API Key, Secret Key, or Passphrase.

Example: Get Ticker Information (REST API)

This example uses the /api/v5/market/ticker endpoint to retrieve the ticker for BTC-USDT.

curl -X GET "https://www.okx.com/api/v5/market/ticker?instId=BTC-USDT"

A successful response will return JSON data containing the latest ticker information for BTC-USDT. For full details on the response structure, refer to the OKEx Get Ticker Data documentation.

Authenticated Request: Account Information

Authenticated requests require signing each request with your API Key, Secret Key, and Passphrase. The signature process involves combining specific request parameters with your Secret Key using a cryptographic hash function (HMAC-SHA256). OKEx provides official SDKs to abstract this complexity.

Using the Python SDK

The OKEx Python SDK simplifies authenticated requests. First, install the SDK:

pip install okx-api

Then, use the following Python code to retrieve account balance information:

from okx.Account import AccountAPI

# Replace with your actual API credentials
api_key = "YOUR_API_KEY"
secret_key = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"

# Initialize the AccountAPI client
# Use '0' for live trading, '1' for demo trading
account_api = AccountAPI(api_key, secret_key, passphrase, flag='0')

# Get account balance information
result = account_api.get_account_balance()

print(result)

This script initializes the API client with your credentials and then calls the get_account_balance() method. The SDK handles the request signing and network communication. The output will be a JSON object containing your account balance details, as documented in the OKEx Get Balance documentation.

Manual Authenticated Request (REST)

If not using an SDK, you must manually construct and sign authenticated requests. This involves:

  1. Constructing the pre-hash string: Combine the timestamp, HTTP method, request path, query string (if any), and request body (if any).
  2. Signing the pre-hash string: Use HMAC-SHA256 with your Secret Key to generate a signature.
  3. Adding headers: Include OK-ACCESS-KEY, OK-ACCESS-SIGN, OK-ACCESS-TIMESTAMP, and OK-ACCESS-PASSPHRASE in your request headers.

For a detailed breakdown of the signing process, consult the OKEx API Authentication documentation.

Common next steps

After successfully making your first API calls, consider these common next steps to further your integration with OKEx:

  • Explore More Endpoints: Review the comprehensive OKEx REST API documentation to understand the full range of available endpoints for market data, trading, funding, and account management.
  • Implement WebSocket API: For real-time data streaming (e.g., live market prices, order book updates, private account notifications), integrate with the OKEx WebSocket API. This is crucial for applications requiring low-latency updates.
  • Error Handling: Implement robust error handling in your application. The OKEx Error Codes documentation provides details on common error responses and their meanings.
  • Rate Limits: Be aware of and respect OKEx API rate limits to avoid temporary bans or service interruptions. Implement retry mechanisms with exponential backoff if you encounter rate limit errors.
  • Security Best Practices: Continuously review and apply security best practices for API key management, such as rotating keys periodically, using dedicated keys for different applications, and restricting IP access. The OAuth 2.0 Bearer Token Usage specification, while not directly applicable to OKEx's signature-based authentication, provides general guidance on token security.
  • Utilize Demo Trading: OKEx offers a demo trading environment. Use this sandbox to test your API integrations without risking real funds. When initializing SDKs, ensure you set the flag parameter to '1' for demo trading.

Troubleshooting the first call

Encountering issues with your initial API calls is common. Here are some troubleshooting tips for OKEx API integration:

  • 401 Unauthorized / Invalid Signature:
    • Check Credentials: Double-check your API Key, Secret Key, and Passphrase for typos. Remember, the Secret Key is only shown once.
    • Timestamp Accuracy: Ensure your system clock is synchronized with NTP (Network Time Protocol) servers. A significant time difference between your system and OKEx servers can cause signature validation to fail.
    • Signing Logic (Manual REST): If you are manually signing requests, meticulously review the OKEx API Authentication documentation. Small discrepancies in the pre-hash string construction or HMAC-SHA256 implementation will lead to signature errors.
    • Passphrase in Header: Confirm that the OK-ACCESS-PASSPHRASE header is correctly included in authenticated requests.
  • 403 Forbidden:
    • IP Whitelist: If you enabled an IP whitelist for your API key, ensure the IP address from which you are making the request is included in the approved list.
    • Permissions: Verify that the API key has the necessary permissions for the endpoint you are trying to access. For example, a key with only "Read" permissions cannot execute a trade.
  • 429 Too Many Requests:
    • Rate Limits: You have exceeded the API rate limits. Implement a delay or an exponential backoff strategy for retries. Refer to the OKEx Rate Limit documentation.
  • Endpoint Not Found (404):
    • Correct URL: Ensure the base URL (https://www.okx.com) and the specific endpoint path are correct.
    • API Version: OKEx uses /api/v5/ for its latest API version. Ensure your requests target the correct version.
  • SDK Specific Issues:
    • SDK Version: Ensure you are using the latest version of the OKEx SDK.
    • Dependencies: Check that all SDK dependencies are correctly installed.
    • Flag for Live/Demo: Confirm you are setting the flag parameter correctly ('0' for live, '1' for demo) when initializing the SDK client.
  • Refer to Documentation: The OKEx API documentation is the primary resource for detailed error messages, endpoint specifications, and authentication guidelines.