Integrating with the OKX API allows traders and developers to automate trading strategies, fetch real-time market data, and manage assets programmatically. However, one of the most common hurdles users face when building private API requests is encountering the "Invalid Sign" error (code: 50113). This typically stems from incorrect signature generation.
In this guide, weβll walk you through the correct way to generate an OKX API signature using HMAC SHA256 and Base64 encoding, explain each required header, and help you avoid common pitfalls that lead to authentication failures.
Understanding Private API Request Headers
All private REST API requests to OKX must include four specific headers:
OK-ACCESS-KEY: Your API key (a string provided when creating the API on OKX).OK-ACCESS-SIGN: The digital signature generated using your secret key and request details.OK-ACCESS-TIMESTAMP: The UTC time of the request in ISO format (e.g.,2025-04-05T12:30:05.123Z).OK-ACCESS-PASSPHRASE: The passphrase you set when generating the API key.
π Learn how to securely generate your API keys for automated trading
Additionally:
- The request body must be valid JSON with a
Content-Type: application/jsonheader. - For demo trading (paper trading), include the header:
x-simulated-trading: 1
How to Generate the OK-ACCESS-SIGN Signature
The OK-ACCESS-SIGN header is the core of secure authentication. It ensures that only authorized users can access private account data or execute trades.
Signature Formula
The signature is created by hashing the following concatenated string:
timestamp + method + requestPath + bodyThis string is then signed using HMAC SHA256 with your SecretKey, and finally encoded in Base64.
Parameters Explained
| Parameter | Description |
|---|---|
| timestamp | Same value as OK-ACCESS-TIMESTAMP, in ISO 8601 format with milliseconds (e.g., 2025-04-05T12:30:05.123Z). Must be UTC. |
| method | HTTP method in uppercase β either GET or POST. |
| requestPath | Full API endpoint path (e.g., /api/v5/account/balance). Query parameters are included in this path for GET requests. |
| body | Request body as a raw JSON string. Omit if it's a GET request without a body. |
| SecretKey | The private secret key associated with your API key (never shared publicly). |
Example in JavaScript (Using CryptoJS)
const CryptoJS = require('crypto-js');
// Example values
const timestamp = '2025-04-05T12:30:05.123Z';
const method = 'GET';
const requestPath = '/api/v5/account/balance?ccy=BTC';
const body = ''; // Empty for GET requests without body
const secretKey = '22582BD0CFF14C41EDBF1AB98506286D';
// Create the message to sign
const message = timestamp + method + requestPath + body;
// Generate HMAC SHA256 signature and encode in Base64
const sign = CryptoJS.enc.Base64.stringify(
CryptoJS.HmacSHA256(message, secretKey)
);
console.log('OK-ACCESS-SIGN:', sign);This generated sign value should be used directly in the OK-ACCESS-SIGN header.
Common Mistakes That Cause "Invalid Sign" Error
Even small deviations from the signing process can result in authentication failure. Here are frequent causes of error code 50113:
1. Timestamp Mismatch
The timestamp used in the signature must exactly match the one sent in the OK-ACCESS-TIMESTAMP header β including millisecond precision and UTC timezone.
β Using local time or truncated seconds will cause failure.
2. Incorrect Request Path Handling
For GET requests, query parameters like ?ccy=BTC must be part of the requestPath. They are not placed in the body.
β Including query params in the body or omitting them from the path breaks the signature.
3. Body Stringification Issues
For POST requests, ensure the body is passed as a stringified JSON without extra spaces unless intended.
Use:
JSON.stringify({ instId: "BTC-USDT", lever: "5", mgnMode: "isolated" })Not:
{ instId: "BTC-USDT", lever: "5", mgnMode: "isolated" } // Object, not string4. SecretKey vs APIKey Confusion
Ensure you're using the SecretKey, not the APIKey, for HMAC signing.
5. Encoding Errors
Always use Base64 encoding after HMAC SHA256 β not Hex, URL encoding, or others.
Step-by-Step Guide: Fetching BTC Balance in Demo Trading
Letβs walk through a full example to retrieve BTC balance in demo mode.
Step 1: Set Headers
OK-ACCESS-KEY: your_api_key_here
OK-ACCESS-PASSPHRASE: your_passphrase_here
OK-ACCESS-TIMESTAMP: 2025-04-05T12:30:05.123Z
Content-Type: application/json
x-simulated-trading: 1Step 2: Prepare Request Details
- Method:
GET - Path:
/api/v5/account/balance?ccy=BTC - Body: (empty)
- Timestamp:
2025-04-05T12:30:05.123Z - SecretKey:
22582BD0CFF14C41EDBF1AB98506286D
Step 3: Generate Signature
Message:
2025-04-05T12:30:05.123ZGET/api/v5/account/balance?ccy=BTCSigned with HMAC SHA256 + Base64 β Resulting OK-ACCESS-SIGN
Step 4: Send Request
Use any HTTP client (e.g., cURL, Axios, Postman) with all headers set correctly.
π Try building and testing your own API calls securely
Frequently Asked Questions (FAQ)
Q1: Why do I keep getting "Invalid Sign" even with correct code?
A: Double-check timestamp synchronization. Use NTP-synced clocks and ensure millisecond precision matches between signature and header. Also verify no extra whitespace or encoding differences exist in the body or path.
Q2: Should I include query parameters in the signature?
A: Yes β for GET requests, append query parameters directly to the requestPath. For example, /api/v5/account/balance?ccy=BTC becomes part of the signing string.
Q3: Can I reuse the same signature for multiple requests?
A: No. Each signature is unique to the timestamp, method, path, and body. Reusing signatures will fail due to time expiration or mismatched components.
Q4: How long is a signature valid?
A: OKX requires timestamps to be within 30 seconds of server time. If your system clock is off, the request will be rejected regardless of signature accuracy.
Q5: Is there a tool to test my signature?
A: While OKX doesnβt provide an official validator, you can use online HMAC generators (with caution) or debug step-by-step using console logs in development environments.
Q6: Does demo trading require different endpoints?
A: No β demo trading uses the same API endpoints but requires the additional header x-simulated-trading: 1. Without it, your request defaults to live trading.
Best Practices for Secure and Reliable Integration
- Store your API Key, SecretKey, and Passphrase securely β never hardcode them in frontend code.
- Use environment variables or secure vaults for credential management.
- Implement automatic timestamp generation with millisecond precision.
- Log requests during development (without exposing secrets) to debug issues.
- Rotate API keys periodically for enhanced security.
By following these guidelines, you can eliminate signature errors and build robust integrations with the OKX trading platform.
Whether you're building bots, dashboards, or algorithmic strategies, mastering API authentication is the first critical step toward seamless automation.
π Start building powerful trading tools with reliable API access today