Authentication overview

Bitfinex provides programmatic access to its trading, data, and account management functionalities through a comprehensive set of APIs, including a REST API and a WebSocket API. Authentication for these interfaces is primarily managed through API keys and secrets, which are used to generate cryptographic signatures for each request. This approach ensures that all interactions are authenticated to a specific user and that the integrity of the request payload is maintained.

The authentication process involves combining a user's API key with a secret key to generate a unique signature for each API call. This signature is then transmitted along with the request, allowing the Bitfinex servers to verify both the sender's identity and that the request has not been tampered with in transit. This method is a standard practice for securing API interactions in financial contexts, offering a balance between security and usability for developers and automated trading systems.

Bitfinex's API documentation provides detailed specifications for constructing authenticated requests, including required headers and payload structures for both REST and WebSocket connections. Developers can find specific guidance on signing requests in the official Bitfinex WebSocket authentication and Bitfinex Rest API authentication guides. SDKs are also available in several programming languages, such as Node.js and Python, to simplify the implementation of these authentication mechanisms.

Supported authentication methods

Bitfinex utilizes a signature-based authentication method that relies on API keys and secrets. This method is applied consistently across both its REST and WebSocket APIs to ensure secure communication for all programmatic interactions.

Method When to Use Security Level
API Key & HMAC-SHA384 Signature All programmatic access via REST API and WebSocket API, including trading, account management, and private data retrieval. High. Requires a secret key to sign each request, verifying both identity and message integrity.

The core of Bitfinex's authentication relies on the creation of a cryptographic signature using the Hash-based Message Authentication Code (HMAC) with the SHA-384 hashing algorithm. This process involves concatenating specific request parameters (such as the request path, nonce, and request body) and then encrypting this string with the user's API secret key. The resulting signature is then sent as part of the request headers. This ensures that only authorized parties with access to the secret key can generate valid requests, and that the request payload has not been altered since it was signed. For a general understanding of HMAC, the IETF's RFC 2104 on HMAC provides foundational details.

Getting your credentials

To obtain the necessary API key and secret for authenticating with Bitfinex, you must generate them within your Bitfinex account settings. This process involves several steps to ensure security and proper configuration of access permissions.

  1. Log In to Your Bitfinex Account: Access your account through the official Bitfinex website.
  2. Navigate to API Keys: Once logged in, go to the API Keys section. This is typically found under your account settings or profile management area.
  3. Create a New Key: Select the option to 'Create New Key' or 'Generate API Key'.
  4. Configure Permissions: Bitfinex allows granular control over API key permissions. Carefully select the specific read and write permissions that your application requires. For example, if your application only needs to read market data, you should not grant trading or withdrawal permissions. Granting only necessary permissions is a critical security practice to limit the potential impact if your API key is compromised. The Bitfinex API Key setup guide details available permissions.
  5. Add IP Whitelist (Optional, but Recommended): For enhanced security, you can specify a list of IP addresses that are authorized to use the API key. Any requests originating from an IP address not on this whitelist will be rejected. This significantly reduces the risk of unauthorized access even if your API key and secret are stolen.
  6. Generate and Record Credentials: After configuring permissions and (optionally) IP whitelisting, generate the key. Bitfinex will display your API Key and API Secret. It is crucial to copy and store your API Secret immediately and securely, as it will often only be shown once and cannot be retrieved later. If lost, you will need to generate a new key pair.
  7. Confirm Activation: Some API key creations may require email confirmation or two-factor authentication (2FA) verification to finalize the process.

Always treat your API secret key with the same level of security as your account password. Avoid hardcoding it directly into your application's source code, and instead use environment variables or secure configuration management systems.

Authenticated request example

This example demonstrates how to make an authenticated request to the Bitfinex REST API using Python. The request retrieves account information.


import hashlib
import hmac
import json
import time
import requests

# Replace with your actual API Key and Secret
API_KEY = "YOUR_BITFINEX_API_KEY"
API_SECRET = "YOUR_BITFINEX_API_SECRET"

BASE_URL = "https://api.bitfinex.com"

def make_authenticated_request(path, body):
    nonce = str(int(time.time() * 1000000))
    full_path = "/api/v2/" + path
    
    # Convert body to JSON string (or empty string if no body)
    if body:
        body_json = json.dumps(body)
    else:
        body_json = ""

    # Payload for signature
    # Nonce | request_path | body_json
    payload_string = f"/api/v2/{path}{nonce}{body_json}"

    # Create signature
    signature = hmac.new(
        API_SECRET.encode('utf-8'),
        payload_string.encode('utf-8'),
        hashlib.sha384
    ).hexdigest()

    headers = {
        "bfx-nonce": nonce,
        "bfx-apikey": API_KEY,
        "bfx-signature": signature,
        "Content-Type": "application/json"
    }

    url = BASE_URL + full_path
    response = requests.post(url, headers=headers, data=body_json)
    response.raise_for_status() # Raise an exception for HTTP errors
    return response.json()

# Example: Get Wallet Balances
path = "auth/r/wallets"
body = {}

try:
    wallet_balances = make_authenticated_request(path, body)
    print("Wallet Balances:")
    for wallet in wallet_balances:
        print(f"  Type: {wallet[0]}, Currency: {wallet[1]}, Balance: {wallet[2]}")
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e.response.status_code} - {e.response.text}")
except Exception as e:
    print(f"An error occurred: {e}")

This Python script defines a function make_authenticated_request that handles the signature generation and request sending. It constructs the payload string, signs it using HMAC-SHA384, and then sends the request with the necessary headers. The example demonstrates fetching wallet balances, which is a common authenticated endpoint. Developers should ensure they replace placeholder API keys and secrets with their actual credentials and manage them securely.

Security best practices

When integrating with the Bitfinex API, adherence to security best practices is crucial to protect your account and assets. Compromised API keys can lead to unauthorized trading, withdrawals, and exposure of sensitive data.

  • Least Privilege Principle: Grant API keys only the minimum necessary permissions. For instance, if your application only monitors market data, do not enable trading or withdrawal permissions. Regularly review and adjust permissions as your application's needs evolve. Bitfinex offers granular permission settings that should be utilized thoroughly to minimize attack surface.
  • IP Whitelisting: Always restrict API key usage to a specific set of trusted IP addresses. If your application or server uses a static IP address, whitelist it. If your IP address is dynamic, consider using a VPN or a service that provides a static egress IP. This significantly limits the ability of an attacker to use your API key even if they manage to obtain it.
  • Secure Storage of API Keys: Never hardcode API keys and secrets directly into your application's source code. Instead, use environment variables, secure configuration files, or a secrets management service (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault). For local development, use .env files that are excluded from version control.
  • Nonce Management: Ensure that your nonce (a unique, incrementing number or timestamp) is truly unique for each request. Reusing a nonce can lead to replay attacks and request rejection. Bitfinex requires nonces to be monotonically increasing.
  • Implement Rate Limiting and Error Handling: Build robust error handling into your application, especially for authentication failures or rate limit exceeded errors. Implement exponential backoff for retries to avoid being blocked.
  • Regular Key Rotation: Periodically rotate your API keys. This means generating new keys and revoking old ones. A common practice is to rotate keys every 90 days. This mitigates the risk associated with long-lived credentials.
  • Monitor API Activity: Regularly review API logs and activity in your Bitfinex account to detect any unusual or unauthorized access patterns. Set up alerts for suspicious activity, such as failed authentication attempts from unknown IPs or unexpected trading volumes.
  • Use Strong Cryptography: Ensure your development environment and libraries use up-to-date cryptographic standards. Bitfinex uses HMAC-SHA384; ensure your implementation correctly generates this signature.
  • Secure Development Practices: Follow general secure coding guidelines, such as input validation, protection against common web vulnerabilities (e.g., SQL injection, XSS if applicable to your application), and keeping all dependencies updated.
  • Enable Two-Factor Authentication (2FA): While API keys bypass direct login 2FA, enabling 2FA on your Bitfinex account itself provides an additional layer of security against unauthorized access to your account settings where API keys are managed.