Below is a Python implementation for signing OKEx API requests, covering both GET and POST methods:
Python Implementation for API Signing
import hmac
import base64
import requests
import datetime
import json
# Configuration (replace with your credentials)
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
API_PASSPHRASE = "your_passphrase"
BASE_URL = "https://www.okx.com"
def get_timestamp():
"""Generate ISO 8601 formatted UTC timestamp"""
now = datetime.datetime.utcnow()
return now.isoformat("T", "milliseconds") + "Z"
def generate_signature(timestamp, method, endpoint, body, secret_key):
"""Generate HMAC SHA256 signature"""
message = str(timestamp) + method.upper() + endpoint
if body:
message += json.dumps(body)
mac = hmac.new(
bytes(secret_key, "utf-8"),
bytes(message, "utf-8"),
digestmod="sha256"
)
return base64.b64encode(mac.digest()).decode("utf-8")
def get_headers(method, endpoint, body=None):
"""Generate request headers"""
timestamp = get_timestamp()
return {
"OK-ACCESS-KEY": API_KEY,
"OK-ACCESS-SIGN": generate_signature(timestamp, method, endpoint, body, API_SECRET),
"OK-ACCESS-TIMESTAMP": timestamp,
"OK-ACCESS-PASSPHRASE": API_PASSPHRASE,
"Content-Type": "application/json"
}
def api_request(method, endpoint, body=None):
"""Execute authenticated API request"""
url = BASE_URL + endpoint
headers = get_headers(method, endpoint, body)
if method == "GET":
response = requests.get(url, headers=headers)
elif method == "POST":
response = requests.post(url, headers=headers, json=body)
return response.json()Common Use Cases
GET Request Example (Account Balance)
balance = api_request("GET", "/api/v5/account/balance")
print(balance)POST Request Example (Place Order)
order_data = {
"instId": "BTC-USDT",
"tdMode": "cash",
"side": "buy",
"ordType": "market",
"sz": "1"
}
order_result = api_request("POST", "/api/v5/trade/order", order_data)
print(order_result)Troubleshooting Invalid Signatures
When receiving {'msg': 'Invalid Sign', 'code': '50113'} errors:
Timestamp Verification:
- Ensure your system clock is synchronized with NTP
- Timestamp must be within ยฑ30 seconds of OKEx server time
Body Formatting:
- For POST requests, include the body in signature calculation
- Use consistent JSON serialization (no extra spaces or line breaks)
Endpoint Accuracy:
- Verify the endpoint path matches exactly with API documentation
- Include version prefix (e.g.,
/api/v5/)
๐ For more API examples, visit OKEx's official documentation
FAQ Section
Why does my GET request work but POST fails?
POST requests require including the request body in the signature calculation, while GET requests typically don't have a body. Ensure your signature function properly handles both cases.
How often should I regenerate my API keys?
For security best practices, rotate your API keys every 30-90 days. OKEx allows multiple active keys to facilitate smooth transitions.
What's the difference between live and demo trading?
Demo trading (simulated environment) requires adding x-simulated-trading: 1 header, while live trading uses 0. Demo accounts help test strategies without real funds.
Can I use the same signature for multiple requests?
No. Each request requires a fresh signature with current timestamp. Reusing signatures will trigger security rejections.
How do I troubleshoot 50113 errors?
- Verify your secret key is correct
- Check timestamp format (ISO 8601 with milliseconds)
- Ensure proper JSON formatting for POST bodies
- Confirm endpoint paths are exact matches
๐ Explore advanced trading APIs on OKEx's developer portal