Getting started overview
Integrating with the Huobi API enables programmatic access to its cryptocurrency exchange functionalities, including spot and derivatives trading, market data, and account management. The Huobi platform offers both RESTful APIs for transactional operations and WebSocket APIs for real-time data streaming. This guide focuses on the initial steps required to set up your environment and execute a basic authenticated API call.
The process involves account creation, security verification (including KYC and 2FA), API key generation, and finally, making a signed request. Huobi provides comprehensive official API documentation that details all available endpoints and parameters.
Quick Reference Steps
| Step | Description | Where to do it |
|---|---|---|
| 1. Register Account | Create a new Huobi account. | Huobi Registration Page |
| 2. Complete KYC | Verify your identity (required for trading and withdrawals). | Huobi Security Center > Identity Verification |
| 3. Enable 2FA | Set up Two-Factor Authentication for security. | Huobi Security Center > 2FA |
| 4. Generate API Keys | Create an API key pair (Access Key and Secret Key). | Huobi API Management Page |
| 5. Configure Permissions | Assign appropriate permissions to your API key (e.g., Read, Trade). | Huobi API Management Page |
| 6. Make First Request | Execute a simple authenticated API call to test the setup. | Using your preferred programming language/tool |
Create an account and get keys
To access the Huobi API, you must first establish a user account and secure your access credentials. Follow these steps:
1. Register and Verify Your Huobi Account
- Account Registration: Navigate to the Huobi registration page and sign up using your email or mobile number.
- Identity Verification (KYC): Huobi, like other regulated exchanges, requires Know Your Customer (KYC) verification. This typically involves submitting identification documents and a selfie. Complete this process through the Huobi Security Center under 'Identity Verification'. KYC is essential for enabling trading features and higher withdrawal limits.
- Enable Two-Factor Authentication (2FA): For enhanced security, enable 2FA (e.g., Google Authenticator) on your account. This is a critical step to protect your assets and API access. You can find this option in the Huobi Security Center.
2. Generate API Keys
Once your account is set up and secured, you can generate the necessary API keys:
- Access API Management: Log into your Huobi account. Navigate to the user icon (usually top right), then select 'API Management' (or similar wording).
- Create New Key: Click on 'Create API' or 'New API Key'.
- Label Your Key: Provide a descriptive name for your API key (e.g., "MyTradingBot"). This helps you identify its purpose later.
- Set IP Whitelisting (Optional but Recommended): For security, Huobi allows you to restrict API access to specific IP addresses. If you have a static IP address for your application server, enter it here. This significantly reduces the risk of unauthorized access even if your keys are compromised.
- Configure Permissions: Carefully select the permissions for your API key. For a first test, 'Read' permissions might suffice. For trading, you will need to enable 'Trade' permissions. Avoid granting 'Withdrawal' permissions unless absolutely necessary for your application and ensure robust security measures are in place if you do.
- Confirm and Save Keys: After setting permissions, confirm the creation. Huobi will display your Access Key (also known as API Key ID) and your Secret Key. The Secret Key is shown only once. Copy both immediately and store them securely. If you lose your Secret Key, you will need to generate a new API key pair.
Security Reminder: Treat your Secret Key like a password. Do not embed it directly in client-side code, commit it to version control, or share it publicly. Use environment variables or a secure configuration management system.
Your first request
This section demonstrates how to make a basic authenticated request to the Huobi API. We'll use the API for fetching account balances, which requires authentication but no complex parameters. Huobi's REST API uses HMAC-SHA256 for signing requests, a common method for securing API calls that involve sensitive user data, as detailed in the IETF RFC 2104.
API Endpoint for Account Balances
The endpoint to retrieve account balances is typically:
GET /v1/account/accounts/{account-id}/balance
Before calling this, you first need to get your account-id. You can retrieve a list of your accounts using:
GET /v1/account/accounts
This initial call to /v1/account/accounts will return your account ID(s), which you then use in the balance request. For simplicity, we'll demonstrate a market data request first, which does not require authentication, and then an authenticated account balance request.
Example 1: Unauthenticated Market Data Request (Candlestick Data)
This request fetches the latest 1-minute candlestick data for Bitcoin (BTC) against Tether (USDT). This does not require API keys.
import requests
url = "https://api.huobi.pro/market/history/kline"
params = {
"symbol": "btcusdt",
"period": "1min",
"size": 1
}
try:
response = requests.get(url, params=params)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
data = response.json()
if data and data['status'] == 'ok' and data['data']:
print("Latest BTC/USDT 1-minute candlestick data:")
print(data['data'][0])
else:
print(f"Error or no data: {data.get('err-msg', 'Unknown error')}")
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
Example 2: Authenticated Request (Account Balances)
Making an authenticated request involves signing the request with your secret key. This example uses Python, leveraging the hmac and hashlib libraries for signing. Replace YOUR_ACCESS_KEY and YOUR_SECRET_KEY with your generated credentials.
import requests
import hmac
import hashlib
import base64
import urllib.parse
import datetime
# --- Configuration --- #
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"
API_HOST = "api.huobi.pro"
# --- Helper function for signing requests --- #
def generate_signature(method, host, path, params):
sorted_params = sorted(params.items())
query_string = urllib.parse.urlencode(sorted_params)
payload = [method, host, path, query_string]
signature_payload = "\n".join(payload)
hashed_payload = hmac.new(SECRET_KEY.encode('utf-8'),
signature_payload.encode('utf-8'),
hashlib.sha256).digest()
signature = base64.b64encode(hashed_payload).decode('utf-8')
return signature
# --- Get current timestamp and format --- #
dt_utc = datetime.datetime.utcnow()
now_iso = dt_utc.isoformat(timespec='milliseconds') + 'Z'
# --- Request Parameters for getting account IDs --- #
method = "GET"
path = "/v1/account/accounts"
params = {
"AccessKeyId": ACCESS_KEY,
"SignatureMethod": "HmacSHA256",
"SignatureVersion": "2",
"Timestamp": now_iso
}
# --- Generate Signature --- #
signature = generate_signature(method, API_HOST, path, params)
params["Signature"] = signature
# --- Make the request --- #
url = f"https://{API_HOST}{path}?{urllib.parse.urlencode(params)}"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data and data['status'] == 'ok' and data['data']:
print("Account details:")
account_id = data['data'][0]['id'] # Assuming you want the first account ID
print(f"First Account ID: {account_id}")
# --- Now request balances for the found account_id --- #
path_balances = f"/v1/account/accounts/{account_id}/balance"
# Re-generate timestamp for the new request
dt_utc_balance = datetime.datetime.utcnow()
now_iso_balance = dt_utc_balance.isoformat(timespec='milliseconds') + 'Z'
params_balances = {
"AccessKeyId": ACCESS_KEY,
"SignatureMethod": "HmacSHA256",
"SignatureVersion": "2",
"Timestamp": now_iso_balance
}
signature_balances = generate_signature(method, API_HOST, path_balances, params_balances)
params_balances["Signature"] = signature_balances
url_balances = f"https://{API_HOST}{path_balances}?{urllib.parse.urlencode(params_balances)}"
response_balances = requests.get(url_balances)
response_balances.raise_for_status()
data_balances = response_balances.json()
if data_balances and data_balances['status'] == 'ok':
print("Account Balances:")
print(data_balances['data'])
else:
print(f"Error fetching balances: {data_balances.get('err-msg', 'Unknown error')}")
else:
print(f"Error or no account data: {data.get('err-msg', 'Unknown error')}")
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
This code snippet first retrieves your account ID(s) and then uses the first available ID to fetch your account balances. A successful response will return a JSON object containing your assets and their respective types (e.g., 'trade' for available balance, 'frozen' for assets held in orders).
Common next steps
After successfully making your first API call, consider these next steps to deepen your integration with the Huobi API:
- Explore More Endpoints: Review the Huobi API reference documentation to understand the full range of available endpoints for spot trading, derivatives, margin, and more.
- Implement Trading Logic: For automated trading, integrate endpoints for placing orders (
POST /v1/order/orders), canceling orders (POST /v1/order/orders/{order-id}/submitcancel), and querying open orders (GET /v1/order/openOrders). - Utilize WebSocket API: For real-time market data or account updates, transition to Huobi's WebSocket API. This is more efficient for continuous data streams than polling REST endpoints. The WebSocket API documentation provides details on connecting and subscribing to channels.
- Error Handling: Implement robust error handling mechanisms in your application to gracefully manage API rate limits, invalid parameters, authentication failures, and other potential issues.
- Security Best Practices: Continuously review and apply security best practices for API key management, IP whitelisting, and secure coding to protect your application and assets.
- Huobi SDKs: Consider using one of the official Huobi SDKs (Python, Java, C#, Go, JavaScript) to simplify interaction with the API, as they often handle signing and request formatting automatically.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting tips:
- Incorrect API Keys: Double-check that you are using the correct Access Key and Secret Key. Ensure there are no leading or trailing spaces. Copy-pasting errors are frequent.
- Signature Mismatch: The most common issue with authenticated requests is an incorrect signature. Verify the following:
- Method: Ensure the HTTP method (GET, POST) used in signing matches the actual request method.
- Host and Path: Confirm the
host(api.huobi.pro) andpath(e.g.,/v1/account/accounts) are exact matches used in the signature payload. - Parameters: All query parameters (
AccessKeyId,SignatureMethod,SignatureVersion,Timestamp) must be included in the signature string in lexicographical order, URL-encoded. - Timestamp: The
Timestampmust be in UTC, ISO 8601 format with milliseconds and 'Z' suffix (e.g.,2026-05-29T12:00:00.000Z). Huobi's servers might reject requests with a timestamp significantly out of sync. Ensure your system's clock is accurate. - Secret Key Encoding: The Secret Key used for HMAC signing must be bytes, typically UTF-8 encoded.
- Permissions: Ensure your API key has the necessary permissions for the endpoint you are trying to access (e.g., 'Read' for market data, 'Trade' for placing orders). Check this in your Huobi API Management settings.
- Rate Limits: If you are making multiple requests quickly, you might hit Huobi's API rate limits. The API will return an error indicating too many requests. Implement exponential backoff or ensure your request frequency is within limits.
- Network Issues: Verify your internet connection and ensure no firewalls or proxies are blocking access to
api.huobi.pro. - Official Documentation: Refer to the Huobi API documentation on authentication and specific endpoint details. The documentation often includes example request/response structures.
- SDKs: If struggling with manual signature generation, consider using one of the Huobi SDKs. They abstract away the complexity of signing requests.