How to Write OKX API Signatures Correctly: Fix Invalid Signature Errors

Β·

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:

πŸ‘‰ Learn how to securely generate your API keys for automated trading

Additionally:


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 + body

This string is then signed using HMAC SHA256 with your SecretKey, and finally encoded in Base64.

Parameters Explained

ParameterDescription
timestampSame value as OK-ACCESS-TIMESTAMP, in ISO 8601 format with milliseconds (e.g., 2025-04-05T12:30:05.123Z). Must be UTC.
methodHTTP method in uppercase β€” either GET or POST.
requestPathFull API endpoint path (e.g., /api/v5/account/balance). Query parameters are included in this path for GET requests.
bodyRequest body as a raw JSON string. Omit if it's a GET request without a body.
SecretKeyThe 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 string

4. 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: 1

Step 2: Prepare Request Details

Step 3: Generate Signature

Message:

2025-04-05T12:30:05.123ZGET/api/v5/account/balance?ccy=BTC

Signed 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

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