OKX API Key Doesn't Exist: Fix This Error in Minutes
Learn why OKX throws the 'API key doesn't exist' error, how to troubleshoot it step by step, and prevent it from breaking your trading bots again.
Learn why OKX throws the 'API key doesn't exist' error, how to troubleshoot it step by step, and prevent it from breaking your trading bots again.
You've generated your API key on OKX, copied it into your bot config, hit run — and immediately get slapped with error code 50111: "API key doesn't exist." It's one of the most frustrating errors in crypto API trading because the key clearly exists — you just created it. The problem is almost never that the key is actually missing. It's that something between your code and OKX's servers is slightly off, and the exchange can't match what you're sending to what it has on file.
This error is not unique to OKX. Traders on Binance, Bybit, and Bitget run into nearly identical issues with their own API systems. But OKX has a few specific quirks — like its passphrase requirement and dual environment setup — that make this particular error more common than on other platforms. Let's break down every cause and fix it for good.
Before you start rewriting code, walk through this checklist. In about 80% of cases, the problem falls into one of these categories:
Quick check: log into OKX, go to API management, and verify the key is listed and active. If it's not there, it was deleted. If it is, the issue is in your code or configuration.
Let's build a proper OKX API authentication from scratch. The most reliable way to avoid the 'api key not working' problem is to handle credentials correctly from the start. OKX uses HMAC SHA256 signatures with a timestamp, and every piece must be exact.
import hmac
import hashlib
import base64
import time
import requests
# Step 1: Store credentials WITHOUT any whitespace
API_KEY = "your-api-key-here".strip()
API_SECRET = "your-api-secret-here".strip()
PASSPHRASE = "your-passphrase-here".strip()
# Step 2: Use the correct base URL
# Live trading:
BASE_URL = "https://www.okx.com"
# Demo trading (if your key is for demo):
# BASE_URL = "https://www.okx.com" # same URL, but add header
def get_timestamp():
"""OKX expects ISO 8601 format timestamp."""
return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
def sign_request(timestamp, method, path, body=''):
"""Create HMAC SHA256 signature for OKX API."""
message = timestamp + method.upper() + path + body
signature = hmac.new(
API_SECRET.encode('utf-8'),
message.encode('utf-8'),
hashlib.sha256
)
return base64.b64encode(signature.digest()).decode()
def make_request(method, path, body=''):
timestamp = get_timestamp()
headers = {
'OK-ACCESS-KEY': API_KEY,
'OK-ACCESS-SIGN': sign_request(timestamp, method, path, body),
'OK-ACCESS-TIMESTAMP': timestamp,
'OK-ACCESS-PASSPHRASE': PASSPHRASE,
'Content-Type': 'application/json',
# For demo trading, uncomment the next line:
# 'x-simulated-trading': '1',
}
url = BASE_URL + path
response = requests.request(method, url, headers=headers, data=body)
return response.json()
# Test: fetch account balance
result = make_request('GET', '/api/v5/account/balance')
print(result)
Pay close attention to the .strip() calls on every credential. That single method call eliminates the most common cause of 'okx api key doesn't exist' errors. Also note the x-simulated-trading header — if your key was created for demo trading on OKX, you must include this header, or the live environment won't recognize your key at all.
When something goes wrong, OKX returns structured error codes. Don't just check for success — parse the error and react to it. Here's a robust approach with the most common error codes you'll encounter:
import json
# OKX API error codes related to authentication
ERROR_CODES = {
'50111': 'API key does not exist — check key, whitespace, or demo/live mismatch',
'50112': 'API key is invalid or expired',
'50113': 'Invalid signature — check secret key and signing method',
'50114': 'Passphrase is incorrect',
'50115': 'IP address not whitelisted for this API key',
}
def diagnose_api_error(response_data):
"""Parse OKX response and provide actionable diagnosis."""
code = response_data.get('code', '0')
if code == '0':
print('Request successful.')
return response_data['data']
msg = response_data.get('msg', 'Unknown error')
diagnosis = ERROR_CODES.get(code, 'Unrecognized error code')
print(f'OKX Error {code}: {msg}')
print(f'Diagnosis: {diagnosis}')
if code == '50111':
print('\nTroubleshooting steps:')
print('1. Verify key exists in OKX dashboard (API Management)')
print('2. Check for invisible whitespace: repr(API_KEY)')
print('3. Confirm you are using the correct environment')
print(' - Demo key? Add x-simulated-trading: 1 header')
print(' - Live key? Remove that header')
print('4. Ensure key belongs to the correct account/subaccount')
return None
# Usage
result = make_request('GET', '/api/v5/account/balance')
data = diagnose_api_error(result)
if data:
for asset in data:
print(f"Total equity: {asset['totalEq']} USD")
This diagnostic approach saves hours of guesswork. Instead of staring at a generic error message, you get immediate, actionable steps. If you're running trading bots across multiple exchanges — say OKX and Bybit simultaneously — having structured error handling like this on each connection prevents one broken key from crashing your entire operation.
A question that comes up constantly: does API key expire? The answer depends on the exchange and how you configured the key.
| Exchange | Default Expiration | Custom Expiration | Auto-Revoke Conditions |
|---|---|---|---|
| OKX | No expiration | Optional (set at creation) | 90 days of inactivity (subaccounts) |
| Binance | No expiration | Not available | Manual revocation only |
| Bybit | No expiration | Optional (30/90 days) | After password change |
| Coinbase | No expiration | Not available | OAuth tokens expire, API keys don't |
| Bitget | No expiration | Optional | After security setting changes |
On OKX specifically, if you set an expiration date when creating the key and forgot about it, that key is now dead. There's no warning email — it just stops working. The fix is simple: create a new key. Also worth noting: if you change your OKX account password or modify security settings, some keys may be automatically invalidated as a security measure.
Pro tip: if you're using tools like VoiceOfChain for real-time trading signals and routing those signals to automated bots, always set up a monitoring check that tests your API key validity every few hours. A dead key during a signal-driven trade means a missed opportunity.
Once you've fixed the immediate error, set up your system so it doesn't happen again. Here's a production-ready key validation script that you can run as a health check:
import os
import sys
def validate_okx_credentials():
"""Pre-flight check for OKX API credentials."""
# Load from environment variables (never hardcode in production)
api_key = os.environ.get('OKX_API_KEY', '').strip()
api_secret = os.environ.get('OKX_API_SECRET', '').strip()
passphrase = os.environ.get('OKX_PASSPHRASE', '').strip()
errors = []
if not api_key:
errors.append('OKX_API_KEY environment variable is empty')
elif len(api_key) < 30:
errors.append(f'API key looks too short ({len(api_key)} chars) — possible truncation')
elif api_key != api_key.strip():
errors.append('API key contains leading/trailing whitespace')
if not api_secret:
errors.append('OKX_API_SECRET environment variable is empty')
if not passphrase:
errors.append('OKX_PASSPHRASE is empty — OKX requires a passphrase')
if errors:
print('Credential validation FAILED:')
for e in errors:
print(f' - {e}')
return False
# Test actual connectivity
try:
result = make_request('GET', '/api/v5/account/config')
if result.get('code') == '0':
uid = result['data'][0]['uid']
print(f'OKX API connected successfully. Account UID: {uid}')
return True
else:
print(f'OKX rejected credentials: {result.get("msg")}')
return False
except Exception as e:
print(f'Connection failed: {e}')
return False
if __name__ == '__main__':
if not validate_okx_credentials():
sys.exit(1)
Run this as part of your bot's startup sequence. On platforms like Gate.io and KuCoin, similar validation patterns apply — always verify credentials before entering any trading logic. The few seconds it adds to startup saves you from silent failures during live trading.
The 'OKX API key doesn't exist' error is almost always a configuration problem, not a platform bug. Whitespace in credentials, demo/live environment mismatches, and forgotten passphrases account for the vast majority of cases. Build your authentication layer carefully — with proper stripping, environment separation, and structured error handling — and this error becomes a thing of the past. Whether you're connecting bots to OKX, routing signals from VoiceOfChain to automated strategies, or managing portfolios across Binance and Bybit, solid API key hygiene is the foundation everything else runs on.