Authentication overview

Bitmex provides both REST and WebSocket APIs, enabling programmatic access for various trading activities, including order placement, account management, and real-time market data retrieval. Authentication for these APIs is critical to ensure that only authorized users can perform actions on their accounts and to protect against unauthorized access or data manipulation. The primary authentication mechanism involves the use of API Keys combined with cryptographic signatures.

When an API call is made, developers must include a unique signature generated from the request's parameters, a timestamp, and their secret API Key. This signature acts as proof of identity and ensures the integrity of the request. The process is designed to prevent replay attacks and unauthorized modifications to API requests, aligning with standard practices for securing financial transaction APIs. Understanding the precise construction of these signatures is fundamental for successful integration with the Bitmex API, as detailed in the Bitmex REST API introduction.

Supported authentication methods

Bitmex primarily supports an API Key and signature-based authentication method for both its REST and WebSocket APIs. This approach is common in cryptocurrency exchanges due to its balance of security and programmatic flexibility. Unlike simpler token-based systems, the signature mechanism adds an extra layer of verification, ensuring that the request content itself has not been altered.

API Key & Signature (REST API)

For REST API requests, authentication involves sending specific headers with each request:

  • api-key: Your public API Key, which identifies your account.
  • api-expires: A Unix timestamp (in seconds) indicating when the request expires. This helps prevent replay attacks.
  • api-signature: A HMAC-SHA256 signature of a concatenation of the HTTP method, request path, expiration timestamp, and request body (if present). The signature is generated using your secret API Key.

The server then verifies this signature using its copy of your secret key. If the signature matches, and the expiration timestamp is valid, the request is processed. This method is documented thoroughly in the Bitmex API documentation on authentication.

API Key & Signature (WebSocket API)

WebSocket authentication follows a similar principle but is handled during the initial connection handshake. After establishing a WebSocket connection, a specific authKeyExpires message is sent with the API Key and a signature. The signature for WebSocket authentication is generated from the string 'GET/realtime' + expires using the secret API Key. This authenticates the session for subsequent real-time data subscriptions and private channel interactions, such as order updates or wallet information.

The WebSocket API provides real-time market data and allows for immediate order placement and cancellation, making secure authentication during connection crucial. More information on WebSocket authentication can be found in the Bitmex WebSocket API introduction.

Authentication Methods Table

Method When to Use Security Level
API Key & Signature (REST) Programmatic trading, account management, fetching historical data via HTTP requests. High. Requires cryptographic signing of each request, preventing tampering and replay attacks.
API Key & Signature (WebSocket) Real-time market data subscriptions, live order placement/cancellation, streaming account updates. High. Authenticates the session upon connection, securing all subsequent real-time interactions.

Getting your credentials

To obtain your API credentials for Bitmex, you must first have an active Bitmex account. The process involves generating API Keys directly from your account settings interface. These keys consist of a public API Key and a secret API Key.

  1. Log in to your Bitmex account: Navigate to the Bitmex website and sign in with your username and password.
  2. Access API Key Management: Once logged in, go to the "API Key" section, typically found under your profile or account settings.
  3. Generate New API Key: Click on the option to create a new API Key. You will be prompted to provide a name for your key (e.g., "MyTradingBot") and configure its permissions.
  4. Configure Permissions: Carefully select the permissions for your API Key. Bitmex allows granular control over what actions an API Key can perform, such as "Order" (for placing/canceling orders), "Withdraw" (for initiating withdrawals), or "Read" (for accessing account data). For security, it is best practice to grant only the minimum necessary permissions. For example, a key used only for reading market data should not have withdrawal permissions.
  5. Record Secret Key: Upon generation, Bitmex will display your API Key ID (public key) and your API Secret. The API Secret is shown only once at the time of creation. It is crucial to copy and store this secret key immediately and securely, as it cannot be retrieved later. If lost, you will need to generate a new key.
  6. IP Whitelisting (Optional but Recommended): For enhanced security, Bitmex allows you to whitelist specific IP addresses that can use your API Key. If your trading bot or application runs from a static IP, whitelisting that IP significantly reduces the risk of unauthorized access even if your key is compromised.

It is important to treat your secret API Key with the same level of security as your account password. Never share it publicly or commit it directly into source code repositories.

Authenticated request example

This example demonstrates how to construct an authenticated GET request for the Bitmex REST API using Python. The request retrieves user wallet history. This requires a GET method, a specific path, and no request body.


import hashlib
import hmac
import time
import urllib.parse
import requests

# --- Replace with your actual API Key and Secret ---
api_key = "YOUR_API_KEY"
api_secret = "YOUR_API_SECRET"
# ---------------------------------------------------

base_url = "https://www.bitmex.com/api/v1"
path = "/user/walletHistory"
method = "GET"
body = "" # GET requests typically have no body

# Calculate expiration (e.g., 5 minutes from now)
expires = int(time.time()) + 300

# Create the signature string
signature_payload = method + path + str(expires) + body

# Generate HMAC-SHA256 signature
hashed = hmac.new(api_secret.encode('utf-8'), signature_payload.encode('utf-8'), hashlib.sha256)
signature = hashed.hexdigest()

# Construct headers
headers = {
    "api-key": api_key,
    "api-expires": str(expires),
    "api-signature": signature,
    "Content-Type": "application/json" # Even for GET, good practice to include
}

# Make the request
url = base_url + path
response = requests.request(method, url, headers=headers)

# Print the response
print(f"Status Code: {response.status_code}")
print(f"Response Body: {response.json()}")

# Example of handling a POST request with a body (e.g., placing an order)
# path_post = "/order"
# method_post = "POST"
# body_post = '{"symbol": "XBTUSD", "side": "Buy", "orderQty": 1, "price": 50000}'
# expires_post = int(time.time()) + 300
# signature_payload_post = method_post + path_post + str(expires_post) + body_post
# hashed_post = hmac.new(api_secret.encode('utf-8'), signature_payload_post.encode('utf-8'), hashlib.sha256)
# signature_post = hashed_post.hexdigest()
# headers_post = {
#     "api-key": api_key,
#     "api-expires": str(expires_post),
#     "api-signature": signature_post,
#     "Content-Type": "application/json"
# }
# response_post = requests.request(method_post, base_url + path_post, headers=headers_post, data=body_post)
# print(f"POST Status Code: {response_post.status_code}")
# print(f"POST Response Body: {response_post.json()}")

This Python example uses the requests library for HTTP communication and the hmac and hashlib modules for cryptographic operations. The key steps are calculating the expiration timestamp, constructing the signature payload, generating the HMAC-SHA256 hash, and then attaching the API Key, expiration, and signature to the request headers. This process must be repeated for every authenticated request, with the signature payload changing based on the specific request method, path, expiration, and body.

Security best practices

Implementing strong security practices is paramount when interacting with any financial API, especially one that controls real assets like Bitmex. A lapse in security can lead to significant financial losses. Here are key recommendations:

  • Least Privilege Principle: Grant API Keys only the minimum necessary permissions. For example, if an application only needs to read market data, do not give it permission to place orders or initiate withdrawals. This limits the potential damage if the key is compromised.
  • IP Whitelisting: Whenever possible, restrict API Key usage to a predefined list of trusted IP addresses. This ensures that even if an attacker obtains your API Key, they cannot use it from an unauthorized location. Bitmex provides this feature in the API management section of your account.
  • Secure Storage of Secret Keys: Never hardcode API secret keys directly into your application's source code. Store them in environment variables, secure configuration files, or a dedicated secret management service. Ensure that these storage locations are protected with appropriate access controls. For example, cloud providers offer secrets management services that integrate with application deployments.
  • Regular Key Rotation: Periodically rotate your API Keys. This means generating new keys and revoking old ones. Regular rotation minimizes the window of opportunity for an attacker if a key is ever compromised without your knowledge.
  • Timestamp Security (api-expires): The api-expires header is crucial for preventing replay attacks. Ensure your timestamp generation is accurate and that the expiration window is reasonable (e.g., 5 minutes). A shorter window enhances security but requires precise time synchronization between your system and Bitmex's servers.
  • HTTPS/TLS Usage: Always use HTTPS for all API communications. Bitmex's API endpoints are served over HTTPS by default, ensuring that data transmitted between your application and the server is encrypted and protected from eavesdropping.
  • Error Handling and Logging: Implement robust error handling for API authentication failures. Log these failures securely (without exposing sensitive information) to detect potential brute-force attempts or misconfigurations.
  • Two-Factor Authentication (2FA) on Account: While not directly for API calls, enable 2FA on your Bitmex account itself. This adds a critical layer of security to prevent unauthorized access to your account and API Key management interface.
  • Avoid Public Repositories: Never commit API Keys or secrets to public (or even private, unless extremely careful) source code repositories like GitHub. Use .gitignore files to exclude credential files from version control.

Adhering to these best practices significantly reduces the risk of security incidents and helps maintain the integrity of your trading operations on Bitmex.