Authentication overview

MercadoBitcoin's API is designed for programmatic interaction with its exchange services, enabling institutional clients and partners to access market data and execute trades programmatically. Authentication for this API primarily relies on a signature-based mechanism using API keys and secrets. This method ensures that all requests originating from a client are verifiable and authorized, preventing unauthorized access to sensitive account information and trading functionalities. The core principle involves signing each request with a unique secret key, which the MercadoBitcoin server then verifies against the public API key provided in the request headers.

The API's design follows established security practices for cryptocurrency exchanges, where the integrity and authenticity of each API call are paramount. Unauthorized API access can lead to significant financial losses or data breaches. Therefore, understanding and implementing the correct authentication flow is crucial for any developer integrating with MercadoBitcoin's platform, as outlined in their official documentation on API integration MercadoBitcoin website.

Supported authentication methods

MercadoBitcoin's API primarily supports a signature-based authentication method, which is common among cryptocurrency exchanges due to its robust security properties. This method involves generating an API key and a corresponding secret key from the user's account. These keys are then used to sign each request sent to the API, ensuring both authenticity and integrity.

API Key and Secret (HMAC-SHA512 Signature)

This is the standard authentication method for MercadoBitcoin's private API endpoints. It involves the following components:

  • API Key (Public Key): A unique identifier for your application or account, included in the request headers.
  • Secret Key (Private Key): A confidential key used to generate a cryptographic signature for each request. This key should never be transmitted directly over the network.
  • Signature: A hash (typically HMAC-SHA512) generated from a combination of the request's payload, timestamp, and your secret key. This signature is then included in the request headers, allowing the server to verify the request's authenticity without direct exposure of the secret key.

This approach aligns with industry best practices for securing API interactions, similar to those employed by other financial and cryptocurrency platforms, which often use cryptographic signatures to validate API requests AWS Signature Version 4 documentation.

Authentication Methods Overview

Method When to Use Security Level
API Key & Secret (HMAC-SHA512) For all private API calls (trading, account balance, order management) High (cryptographically signed requests)
No Authentication For public API calls (market data, general exchange information) N/A (publicly accessible data)

Getting your credentials

To obtain the necessary API credentials for MercadoBitcoin, institutional clients and partners typically follow a specific procedure within their account dashboard. The process generally involves generating an API key and a corresponding secret key.

  1. Log In to Your MercadoBitcoin Account: Access your account through the official MercadoBitcoin website MercadoBitcoin homepage.
  2. Navigate to API Settings: Look for a dedicated 'API' or 'Developer' section within your account settings or profile management area. The exact path may vary but is usually labeled clearly.
  3. Generate New API Key: Within the API settings, there will be an option to 'Generate New API Key' or similar. This action will typically produce a pair of keys: a public API Key and a private Secret Key.
  4. Record Your Secret Key: The Secret Key is often displayed only once upon generation. It is crucial to copy and store this key immediately and securely, as it generally cannot be retrieved again if lost. If lost, you would need to revoke the existing key and generate a new one.
  5. Configure Permissions (Optional but Recommended): Some platforms allow you to set specific permissions for your API keys (e.g., read-only access, trading access, withdrawal access). Configure these permissions to adhere to the principle of least privilege, granting only the necessary access for your application's functionality.
  6. Whitelist IP Addresses (If Available): For enhanced security, if the platform offers IP whitelisting, configure it to allow requests only from your application's static IP addresses. This prevents unauthorized calls even if your API keys are compromised.

It is important to treat these credentials with the same level of security as your account password. They grant programmatic access to your account and should be handled with extreme care.

Authenticated request example

An authenticated request to MercadoBitcoin's private API endpoints requires specific headers and a cryptographic signature. While the exact implementation details can vary based on the programming language and libraries used, the core components remain consistent. The following example illustrates the conceptual structure of an authenticated request using Python, assuming you have an API key, a secret key, and the necessary request parameters.

This example demonstrates how to construct a signed request for a hypothetical endpoint that requires authentication. The URL and payload are illustrative.


import hashlib
import hmac
import time
import requests
import json

# --- Your MercadoBitcoin API Credentials ---
API_KEY = "YOUR_API_KEY_HERE"
SECRET_KEY = "YOUR_SECRET_KEY_HERE" # Keep this absolutely secret

# --- Request Details ---
METHOD = "POST"
# Example: Get account balance
ENDPOINT = "/tapi/v3/" # Placeholder, refer to MercadoBitcoin's actual API docs
BASE_URL = "https://api.mercadobitcoin.net"
NONCE = str(int(time.time() * 1000000)) # Unique number for each request (microseconds)

# Example payload for a TAPI v3 request
# Actual parameters depend on the specific method you're calling
# For simplicity, this example assumes a generic TAPI v3 structure
params = {
    "tapi_method": "list_orders",
    "tapi_nonce": NONCE
}

# Construct the message to be signed
# For TAPI v3, the message is typically the URL-encoded parameters string.
# Ensure parameters are sorted alphabetically for consistent signing if required.
# IMPORTANT: Consult MercadoBitcoin's specific API documentation for exact signing rules.
message_string = "&".join([f"{key}={value}" for key, value in sorted(params.items())])

# Generate the HMAC-SHA512 signature
# The secret key must be encoded to bytes
hmac_signature = hmac.new(SECRET_KEY.encode('utf-8'), message_string.encode('utf-8'), hashlib.sha512).hexdigest()

# Set up headers for the request
headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    "TAPI-ID": API_KEY,
    "TAPI-MAC": hmac_signature
}

# Make the request
try:
    response = requests.post(BASE_URL + ENDPOINT, headers=headers, data=message_string)
    response.raise_for_status() # Raise an exception for HTTP errors
    print("Request successful!")
    print("Response:", response.json())
except requests.exceptions.HTTPError as errh:
    print(f"HTTP Error: {errh}")
except requests.exceptions.ConnectionError as errc:
    print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
    print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
    print(f"An unexpected error occurred: {err}")

Note: This example is a conceptual guide. Developers must refer to MercadoBitcoin's official API documentation for the most accurate and up-to-date signing specifications, endpoint URLs, and parameter requirements MercadoBitcoin documentation.

Security best practices

Securing your API credentials and interactions with MercadoBitcoin is paramount to protecting your assets and data. Adhering to robust security practices can mitigate common risks associated with API usage.

  • Never Hardcode Credentials: Avoid embedding API keys and secrets directly into your source code. Use environment variables, secure configuration files, or secret management services (e.g., AWS Secrets Manager, Google Cloud Secret Manager) to store and retrieve credentials securely.
  • Principle of Least Privilege: When generating API keys, grant only the minimum necessary permissions. For example, if your application only needs to read market data, do not grant it trading or withdrawal permissions. Regularly review and adjust permissions as needed.
  • IP Whitelisting: If MercadoBitcoin's API supports it, configure IP whitelisting to restrict API access only to a predefined set of trusted IP addresses from which your application operates. This adds an extra layer of security, as even if keys are compromised, they cannot be used from unauthorized locations.
  • Rotate API Keys Regularly: Periodically rotate your API keys. This practice reduces the window of exposure if a key is compromised. When rotating, generate a new key, update your applications, and then revoke the old key.
  • Implement Strong Monitoring and Alerting: Monitor API usage for unusual patterns, such as an exceptionally high number of requests, requests from unexpected IP addresses, or failed authentication attempts. Set up alerts to notify you immediately of suspicious activity.
  • Secure Development Practices: Follow secure coding guidelines to prevent vulnerabilities like injection attacks, cross-site scripting (XSS), and insecure direct object references that could expose API keys or allow unauthorized actions. Secure development practices are crucial for overall system integrity Google Developers security guidelines.
  • Use HTTPS: Always interact with MercadoBitcoin's API over HTTPS to ensure that all data in transit is encrypted and protected from eavesdropping and tampering.
  • Enable Two-Factor Authentication (2FA) for Account Access: While not directly related to API key usage, enable 2FA on your MercadoBitcoin account to protect against unauthorized access to your dashboard, where API keys are managed.
  • Error Handling: Implement robust error handling in your application. Avoid logging sensitive information (like full API keys or specific error messages that reveal system internals) in public logs.
  • Validate All Inputs: Always validate and sanitize all inputs received by your application before processing them or passing them to the MercadoBitcoin API. This helps prevent various security vulnerabilities.