Getting started overview

This guide outlines the process for institutional clients and partners to begin using the MercadoBitcoin API. It covers account creation, API key generation, and executing an initial authenticated request. The MercadoBitcoin API is primarily designed for programmatic access to market data and trading functionalities, facilitating automated strategies and integrations for qualified users.

Before proceeding, ensure you have reviewed the MercadoBitcoin costs and deadlines page to understand the fee structure applicable to trading and withdrawals.

Here’s a quick reference for the essential steps:

Step What to Do Where
1. Account Creation Register an institutional account MercadoBitcoin website
2. Verification Complete KYC/AML procedures MercadoBitcoin account portal
3. API Key Generation Generate API key and secret MercadoBitcoin account settings
4. Environment Setup Install a programming language and HTTP client Local development environment
5. First Request Send an authenticated API call Code editor/terminal

Create an account and get keys

Access to the MercadoBitcoin API requires an institutional account. The process involves registration, identity verification, and then the generation of API credentials.

1. Register an institutional account

Navigate to the MercadoBitcoin homepage and initiate the account creation process. Select the option for an institutional or business account, as API access is typically provided to these client types. You will be prompted to provide corporate details, including company name, CNPJ (Brazilian company registration number), and contact information.

2. Complete identity verification (KYC/AML)

MercadoBitcoin, like other regulated financial entities, requires compliance with Know Your Customer (KYC) and Anti-Money Laundering (AML) regulations. This involves submitting documentation to verify the identity of the institution and its authorized representatives. Required documents may include:

  • Articles of Incorporation or equivalent
  • Proof of address for the institution
  • Identification documents for beneficial owners and authorized signatories
  • Bank statements or other financial proofs

The verification process can take several business days. You will receive notifications regarding the status of your application.

3. Generate API keys

Once your institutional account is fully verified and active, you can proceed to generate your API keys. This is typically done within the account's security or API settings section. The process usually involves:

  1. Logging into your MercadoBitcoin account.
  2. Navigating to the 'API Access' or 'Security' section.
  3. Generating a new API key pair, which consists of an API Key (public identifier) and an API Secret (private credential).

Important: The API Secret is typically shown only once upon generation. It is crucial to copy and store it securely immediately. If lost, you may need to revoke the existing key and generate a new one, which can disrupt any active integrations.

Your first request

With your API key and secret, you can now make your first authenticated request to the MercadoBitcoin API. This example will demonstrate a simple market data request, as trading requests require additional parameters and permissions.

Authentication Method

MercadoBitcoin's API uses a signature-based authentication method, often involving HMAC-SHA512. This means you will typically sign your requests using your API Secret. The exact parameters for signing (e.g., nonce, URL path, query string) are critical and must match the server's expected format. For a general understanding of API authentication, refer to the OAuth 2.0 specification, though MercadoBitcoin may use a custom signature scheme.

Example: Fetching the current order book

This example uses Python with the requests library. You will need to replace placeholder values with your actual API credentials. Assume a hypothetical endpoint for fetching order book data.

Prerequisites:

  • Python installed (version 3.8+)
  • requests library installed (pip install requests)

Python code example:


import requests
import hmac
import hashlib
import time
import json

# --- Replace with your actual API credentials ---
API_KEY = "YOUR_MERCADOBITCOIN_API_KEY"
API_SECRET = "YOUR_MERCADOBITCOIN_API_SECRET".encode('utf-8') # Secret must be bytes
# -------------------------------------------------

# Base URL for the MercadoBitcoin API (example - verify with official docs)
BASE_URL = "https://api.mercadobitcoin.com.br/api/v4"

def make_authenticated_request(method, path, params=None, data=None):
    # Generate a nonce (unique number for each request)
    nonce = str(int(time.time() * 1000))

    # Construct the message to be signed
    # The exact format of the message to sign is crucial and specific to MercadoBitcoin.
    # This is a common pattern, but verify with MercadoBitcoin's specific API documentation.
    # Often, it includes nonce, method, path, and potentially query/body parameters.
    message = f"nonce={nonce}&method={method}&path={path}"
    if params:
        # Sort parameters to ensure consistent signature
        sorted_params = '&'.join([f"{k}={v}" for k, v in sorted(params.items())])
        message += f"&{sorted_params}"
    if data:
        # If data is JSON, normalize it for signing
        message += f"&{json.dumps(data, separators=(',', ':'))}"
    
    # Sign the message with HMAC-SHA512
    signature = hmac.new(API_SECRET, message.encode('utf-8'), hashlib.sha512).hexdigest()

    headers = {
        "X-MB-APIKEY": API_KEY,
        "X-MB-NONCE": nonce,
        "X-MB-SIGNATURE": signature,
        "Content-Type": "application/json"
    }

    url = f"{BASE_URL}{path}"
    
    print(f"Requesting: {url}")
    print(f"Headers: {headers}")
    print(f"Message to sign: {message}")

    try:
        if method == 'GET':
            response = requests.get(url, headers=headers, params=params)
        elif method == 'POST':
            response = requests.post(url, headers=headers, json=data)
        else:
            raise ValueError("Unsupported HTTP method")

        response.raise_for_status() # Raise an exception for HTTP errors
        return response.json()
    except requests.exceptions.HTTPError as e:
        print(f"HTTP Error: {e.response.status_code} - {e.response.text}")
        return None
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

# Example usage: Get the order book for BTC/BRL (hypothetical path)
# You MUST verify the actual API path and parameters from MercadoBitcoin's official documentation.
ORDER_BOOK_PATH = "/orderbook"
ORDER_BOOK_PARAMS = {"symbol": "BTCBRL"}

print("\n--- Attempting to fetch order book ---")
order_book = make_authenticated_request('GET', ORDER_BOOK_PATH, params=ORDER_BOOK_PARAMS)

if order_book:
    print("Order Book fetched successfully:")
    print(json.dumps(order_book, indent=2))
else:
    print("Failed to fetch order book.")

Note on API Documentation: The exact API endpoints, required parameters, and the precise method for constructing the signature (especially the message string for HMAC) are specific to MercadoBitcoin. This example provides a common pattern, but you must refer to the official MercadoBitcoin API documentation, typically provided to institutional clients, for the authoritative specification. The Cloudflare API documentation provides an example of how a well-documented API specifies endpoints and authentication.

Common next steps

After successfully making your first authenticated request, consider these common next steps:

  • Explore Market Data Endpoints: Access other public endpoints for real-time price feeds, historical data, and trade history to build analytical tools or inform trading decisions.
  • Implement Trading Endpoints: Integrate with private endpoints to place, modify, and cancel orders. This requires careful handling of parameters like order type (limit, market), price, quantity, and asset pair. Ensure robust error handling and idempotent request mechanisms.
  • Manage Account Information: Access endpoints to retrieve account balances, transaction history, and open orders. This is crucial for reconciling trades and monitoring portfolio performance.
  • Error Handling and Logging: Implement comprehensive error handling to gracefully manage API rate limits, authentication failures, and invalid requests. Log all API interactions for auditing and debugging purposes.
  • Security Best Practices: Review and implement security best practices for API keys, such as environment variables for credentials, IP whitelisting, and regular key rotation. Do not hardcode API keys directly into your application's source code.
  • Webhooks: Investigate if MercadoBitcoin offers webhooks for real-time notifications on events like order fills or account balance changes. Webhooks can reduce the need for constant polling and improve application responsiveness. The Stripe Webhooks documentation offers a good overview of how webhooks can be structured and secured.

Troubleshooting the first call

Encountering issues with your initial API call is common. Here are some troubleshooting steps:

  • Check API Key and Secret: Double-check that your API_KEY and API_SECRET are copied correctly and are active. Typos or leading/trailing spaces are common culprits.
  • Signature Mismatch: The most frequent issue with HMAC-based authentication is an incorrect signature. Verify the following:
    • The exact string used to generate the HMAC hash (message in the example) matches MercadoBitcoin's specification. This includes the order of parameters, inclusion of nonce, HTTP method, and path.
    • The API Secret is correctly encoded as bytes before hashing (.encode('utf-8')).
    • The hashing algorithm (SHA512) and HMAC usage are correct.
  • Nonce Issues: Ensure the nonce is unique for each request and is within any specified time window if MercadoBitcoin enforces one. A common error is reusing a nonce or using a timestamp that is too far in the past/future.
  • Endpoint and Parameters: Confirm that the BASE_URL, path, and any params or data sent in your request exactly match the MercadoBitcoin API documentation for the specific endpoint you are targeting.
  • HTTP Method: Ensure you are using the correct HTTP method (GET, POST) for the endpoint. Using POST for an endpoint expecting GET will result in an error.
  • Rate Limits: If you make too many requests too quickly, you might hit rate limits. Check the response headers or error messages for indications of rate limiting. Implement exponential backoff for retries if necessary.
  • Network Issues: Verify your internet connection and ensure no firewalls or proxies are blocking your outbound requests to the MercadoBitcoin API servers.
  • Consult MercadoBitcoin Support: If you have exhausted these troubleshooting steps and still face issues, contact MercadoBitcoin's institutional support channel. Provide them with the request details, error messages, and any relevant logs.