MercadoBitcoin.Client 4.0.4

dotnet add package MercadoBitcoin.Client --version 4.0.4
                    
NuGet\Install-Package MercadoBitcoin.Client -Version 4.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MercadoBitcoin.Client" Version="4.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MercadoBitcoin.Client" Version="4.0.4" />
                    
Directory.Packages.props
<PackageReference Include="MercadoBitcoin.Client" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MercadoBitcoin.Client --version 4.0.4
                    
#r "nuget: MercadoBitcoin.Client, 4.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MercadoBitcoin.Client@4.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MercadoBitcoin.Client&version=4.0.4
                    
Install as a Cake Addin
#tool nuget:?package=MercadoBitcoin.Client&version=4.0.4
                    
Install as a Cake Tool

MercadoBitcoin.Client

.NET C# System.Text.Json AOT License API HTTP/2

A complete and modern .NET 10 library for integrating with the Mercado Bitcoin API v4. This library provides access to all available platform endpoints, including public data, trading, account management, and wallet operations, with native support for HTTP/3 and System.Text.Json for maximum performance and AOT compatibility.

WARNING: BREAKING CHANGE IN VERSION 4.0.0

All public constructors of MercadoBitcoinClient have been removed. The only supported way to instantiate the client is now via extension methods (MercadoBitcoinClientExtensions.CreateWithRetryPolicies, etc.) or dependency injection (services.AddMercadoBitcoinClient(...)).

Before (obsolete):

var client = new MercadoBitcoinClient();

After (v4.0.0+):

var client = MercadoBitcoinClientExtensions.CreateWithRetryPolicies();
// or via DI:
services.AddMercadoBitcoinClient(...);

See the "Migration and Updates" section for details.

๐Ÿš€ Features

  • โœ… Complete Coverage: All Mercado Bitcoin API v4 endpoints
  • โœ… .NET 10 + C# 14: Latest framework and language with optimized performance
  • โœ… System.Text.Json: Native JSON serialization with Source Generators for maximum performance
  • โœ… AOT Compatible: Compatible with Native AOT compilation for ultra-fast applications
  • โœ… Native HTTP/3: optional HTTP/3 configuration for maximum performance (HTTP/2 by default)
  • โœ… Async/Await: Native asynchronous programming
  • โœ… Strongly Typed: Typed data models for type safety
  • โœ… OpenAPI Integration: Client automatically generated via NSwag
  • โœ… Clean Architecture: Organized and maintainable code
  • โœ… Error Handling: Robust error handling system
  • โœ… Retry Policies: Exponential backoff + configurable jitter
  • โœ… Manual Circuit Breaker: Protection against cascading failures (configurable)
  • โœ… Rate Limit Aware: Respects limits and Retry-After header
  • โœ… CancellationToken in All Endpoints: Complete cooperative cancellation
  • โœ… Custom User-Agent: Override via MB_USER_AGENT env var for observability
  • โœ… Production Ready: Ready for production use
  • โœ… Comprehensive Tests: 64 tests covering all scenarios
  • โœ… Validated Performance: Benchmarks prove 2x+ improvements
  • โœ… Robust Handling: Graceful skip for scenarios without credentials
  • โœ… CI/CD Ready: Optimized configuration for continuous integration

๐Ÿ“ฆ Installation

# Via Package Manager Console
Install-Package MercadoBitcoin.Client

# Via .NET CLI
dotnet add package MercadoBitcoin.Client

# Via PackageReference
<PackageReference Include="MercadoBitcoin.Client" Version="4.0.0-alpha.1" />

โšก๏ธ Usage: Public vs Private Endpoints

Attention:

  • Public Data (e.g., tickers, candles, trades, orderbook, fees, symbols) DO NOT require authentication. Just instantiate the client and call the methods.
  • Private Data (e.g., balances, orders, deposits, withdrawals, trading) REQUIRE authentication. Use AuthenticateAsync before calling private methods.

Quick Examples

Public Data (NO authentication needed):

var client = MercadoBitcoinClientExtensions.CreateWithRetryPolicies();
var tickers = await client.GetTickersAsync("BTC-BRL");
var candles = await client.GetCandlesAsync("BTC-BRL", "1h", to: (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds(), countback: 24);

Private Data (Authentication needed):

var client = MercadoBitcoinClientExtensions.CreateWithRetryPolicies();
await client.AuthenticateAsync("your_login", "your_password");
var accounts = await client.GetAccountsAsync();
var balances = await client.GetBalancesAsync(accounts.First().Id);

๐Ÿ”ง Configuration

Basic Configuration (Code-Only)

The library is designed to be configured entirely via code, without relying on external configuration files like appsettings.json or .env.

using MercadoBitcoin.Client.Extensions;
using MercadoBitcoin.Client.Http;

// 1. Simplest usage (default settings)
var client = MercadoBitcoinClientExtensions.CreateWithRetryPolicies();

// 2. Custom Retry Policy (Code-based)
var retryConfig = new RetryPolicyConfig
{
    MaxRetryAttempts = 3,
    BaseDelaySeconds = 1.0,
    RetryOnRateLimit = true
};
var clientWithRetry = MercadoBitcoinClientExtensions.CreateWithRetryPolicies(retryConfig);

// 3. Advanced Configuration (HTTP settings + Retry)
var httpConfig = new HttpConfiguration 
{ 
    TimeoutSeconds = 60,
    HttpVersion = new Version(2, 0) 
};
var advancedClient = MercadoBitcoinClientExtensions.CreateWithHttp2(retryConfig, httpConfig);

Configuration with Dependency Injection (ASP.NET Core)

For applications using Dependency Injection, you can configure the client in your Program.cs or Startup.cs. You can pass values directly or load them from any source you prefer.

// Program.cs
services.AddMercadoBitcoinClient(options =>
{
    // You can hardcode values, read from environment variables, 
    // or use any other configuration source.
    options.BaseUrl = "https://api.mercadobitcoin.net/api/v4";
    options.HttpConfiguration.TimeoutSeconds = 45;
    
    // Example: Reading from Environment Variables manually
    var envTimeout = Environment.GetEnvironmentVariable("MB_TIMEOUT");
    if (!string.IsNullOrEmpty(envTimeout) && int.TryParse(envTimeout, out int timeout))
    {
        options.HttpConfiguration.TimeoutSeconds = timeout;
    }
});

Note: The library does not automatically read appsettings.json or .env files. If you wish to use them, you must read the values in your application and pass them to the AddMercadoBitcoinClient method or the client factory methods.

๐Ÿ”„ Retry Policies and HTTP/3

The library implements robust retry policies with Polly v8 and supports HTTP/3 for maximum performance, while using HTTP/2 by default for broader compatibility:

HTTP/3 Features

  • QUIC Protocol: Built on UDP for faster connection establishment
  • Multiplexing: Multiple simultaneous requests without head-of-line blocking
  • 0-RTT Resumption: Near-instant connection resumption
  • Improved Congestion Control: Better performance on lossy networks
  • Enhanced Security: Integrated TLS 1.3

Retry Policies

  • Exponential Backoff: Increasing delay between attempts
  • Circuit Breaker: Protection against cascading failures
  • Timeout Handling: Configurable timeouts per operation
  • Rate Limit Aware: Automatically respects API limits

Custom Retry Configurations

using MercadoBitcoin.Client.Http;

// Trading configuration (more aggressive)
var tradingConfig = MercadoBitcoinClientExtensions.CreateTradingRetryConfig();
// 5 attempts, initial delay 0.5s, backoff 1.5x, max 10s

// Public data configuration (more conservative)
var publicConfig = MercadoBitcoinClientExtensions.CreatePublicDataRetryConfig();
// 2 attempts, initial delay 2s, backoff 2x, max 30s

// Custom configuration
var customConfig = new RetryPolicyConfig
{
    MaxRetryAttempts = 3,
    BaseDelaySeconds = 1.0,
    BackoffMultiplier = 2.0,
    MaxDelaySeconds = 30.0,
    RetryOnTimeout = true,
    RetryOnRateLimit = true,
    RetryOnServerErrors = true
};

๐Ÿ—๏ธ Architecture

MercadoBitcoin.Client/
โ”œโ”€โ”€ ๐Ÿ“ Public Data      โ†’ Public data (tickers, orderbook, trades, candles)
โ”œโ”€โ”€ ๐Ÿ“ Account          โ†’ Account management (balances, tier, positions, fees)
โ”œโ”€โ”€ ๐Ÿ“ Trading          โ†’ Trading operations (orders, executions, cancellations)
โ”œโ”€โ”€ ๐Ÿ“ Wallet           โ†’ Wallet (deposits, withdrawals, addresses, limits)
โ””โ”€โ”€ ๐Ÿ“ Authentication   โ†’ Bearer Token authentication system

๐Ÿ“Š Supported Endpoints

๐Ÿ”“ Public Data

Endpoint Method Description
/{asset}/fees GET Asset withdrawal fees
/{symbol}/orderbook GET Order book
/{symbol}/trades GET Trade history
/candles GET Candlestick data (OHLCV)
/symbols GET Instrument information
/tickers GET Current prices
/{asset}/networks GET Available networks for the asset

๐Ÿ” Account and Authentication

Endpoint Method Description
/authorize POST Authentication via login/password
/accounts GET List user accounts
/accounts/{accountId}/balances GET Account balances
/accounts/{accountId}/tier GET Account fee tier
/accounts/{accountId}/{symbol}/fees GET Trading fees
/accounts/{accountId}/positions GET Open positions

๐Ÿ“ˆ Trading

Endpoint Method Description
/accounts/{accountId}/{symbol}/orders GET/POST List/Create orders
/accounts/{accountId}/{symbol}/orders/{orderId} GET/DELETE Get/Cancel order
/accounts/{accountId}/orders GET All orders
/accounts/{accountId}/cancel_all_open_orders DELETE Cancel all open orders

๐Ÿ’ฐ Wallet

Endpoint Method Description
/accounts/{accountId}/wallet/{symbol}/deposits GET Deposit history
/accounts/{accountId}/wallet/{symbol}/deposits/addresses GET Deposit addresses
/accounts/{accountId}/wallet/fiat/{symbol}/deposits GET Fiat deposits (BRL)
/accounts/{accountId}/wallet/{symbol}/withdraw GET/POST Get/Request withdrawals
/accounts/{accountId}/wallet/{symbol}/withdraw/{withdrawId} GET Get specific withdrawal
/accounts/{accountId}/wallet/withdraw/config/limits GET Withdrawal limits
/accounts/{accountId}/wallet/withdraw/config/BRL GET BRL withdrawal config
/accounts/{accountId}/wallet/withdraw/addresses GET Withdrawal addresses
/accounts/{accountId}/wallet/withdraw/bank-accounts GET Bank accounts

๐Ÿ’ป Usage Examples

๐Ÿ“Š Public Data (no authentication)

using MercadoBitcoin.Client.Extensions;
var client = MercadoBitcoinClientExtensions.CreateWithRetryPolicies();

// Get list of all available symbols
var symbols = await client.GetSymbolsAsync();
Console.WriteLine($"Available symbols: {symbols.Symbol.Count}");

// Get Bitcoin ticker
var tickers = await client.GetTickersAsync("BTC-BRL");
var btcTicker = tickers.First();
Console.WriteLine($"BTC: R$ {btcTicker.Last}");

// Get order book
var orderBook = await client.GetOrderBookAsync("BTC-BRL", limit: "10");
Console.WriteLine($"Best bid: R$ {orderBook.Bids[0][0]}");
Console.WriteLine($"Best ask: R$ {orderBook.Asks[0][0]}");

// Get trade history
var trades = await client.GetTradesAsync("BTC-BRL", limit: 100);
Console.WriteLine($"Last {trades.Count} trades retrieved");

// Get candle/chart data
var to = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var candles = await client.GetCandlesAsync("BTC-BRL", "1h", (int)to, countback: 24);
Console.WriteLine($"OHLCV for the last 24 hours retrieved");

๐Ÿ‘ค Private Data (with authentication)

using MercadoBitcoin.Client.Extensions;
var client = MercadoBitcoinClientExtensions.CreateWithRetryPolicies();
await client.AuthenticateAsync("your_login", "your_password");

// Get account information
var accounts = await client.GetAccountsAsync();
var account = accounts.First();
Console.WriteLine($"Account: {account.Name} ({account.Currency})");

// Get balances
var balances = await client.GetBalancesAsync(account.Id);
foreach (var balance in balances)
{
    Console.WriteLine($"{balance.Symbol}: {balance.Available} (available) + {balance.On_hold} (reserved)");
}

๐Ÿ“ˆ Trading

var accountId = accounts.First().Id;

// Create limit buy order
var buyOrder = new PlaceOrderRequest
{
    Side = "buy",
    Type = "limit",
    Qty = "0.001",              // Amount in BTC
    LimitPrice = 280000,        // Limit price in R$
    ExternalId = "my-order-001"
};

var placedOrder = await authenticatedClient.PlaceOrderAsync("BTC-BRL", accountId, buyOrder);
Console.WriteLine($"Order created: {placedOrder.OrderId}");

// List open orders
var openOrders = await authenticatedClient.ListOrdersAsync("BTC-BRL", accountId, status: "working");
Console.WriteLine($"You have {openOrders.Count} open orders");

// Cancel an order
var cancelResult = await authenticatedClient.CancelOrderAsync(accountId, "BTC-BRL", placedOrder.OrderId);
Console.WriteLine($"Cancellation: {cancelResult.Status}");

โšก Rate Limits

The library automatically respects Mercado Bitcoin API rate limits:

  • Public Data: 1 request/second
  • Trading: 3 requests/second (create/cancel), 10 requests/second (queries)
  • Account: 3 requests/second
  • Wallet: Varies by endpoint
  • Cancel All Orders: 1 request/minute

๐Ÿ”’ Security

Authentication

  • Uses Mercado Bitcoin's Bearer Token system
  • Tokens are automatically managed by the library
  • Support for automatic token renewal

Best Practices

  • Never expose your API credentials in source code
  • Use environment variables or Azure Key Vault for credentials
  • Implement retry policies with exponential backoff
  • Configure appropriate timeouts
// โœ… Good
var apiKey = Environment.GetEnvironmentVariable("MB_API_KEY");
var apiSecret = Environment.GetEnvironmentVariable("MB_API_SECRET");
await client.AuthenticateAsync(apiKey, apiSecret);

// โŒ Bad
await client.AuthenticateAsync("hardcoded_key", "hardcoded_secret");

โšก System.Text.Json and AOT Compatibility

Migration Benefits

The library has been completely migrated from Newtonsoft.Json to System.Text.Json with Source Generators, offering:

๐Ÿš€ Performance
  • 2x faster in serialization/deserialization
  • 50% less memory usage during JSON operations
  • 3x faster startup with Source Generators
  • Zero reflection at runtime
๐Ÿ“ฆ AOT Compatibility
  • Native AOT compilation supported
  • Ultra-fast applications with minimal startup time
  • Smaller footprint on memory and disk
  • Better performance in containerized environments

๐Ÿ” Migration and Updates

  • From 2.x to 3.0.0:

    • Migration to System.Text.Json with source generators.
    • Full AOT support and removal of Newtonsoft.Json.
    • HTTP/2 and major performance/architecture improvements.
    • See CHANGELOG.md and RELEASE_NOTES_v3.0.0.md for details.
  • From 3.x to 4.0.0-alpha.1:

    • Target framework updated to net10.0 and C# 14.
    • Public convenience constructors for MercadoBitcoinClient removed; use extension methods (CreateWithRetryPolicies, CreateWithHttp2, CreateForTrading, etc.) or DI (services.AddMercadoBitcoinClient(...)).
    • HTTP/2 is the default; HTTP/3 is available via HttpConfiguration.CreateHttp3Default().
    • New retry presets (CreateTradingRetryConfig, CreatePublicDataRetryConfig) and SIMD candle extensions.
    • See CHANGELOG.md and RELEASE_NOTES_v4.0.0-alpha.1.md for migration examples.

๐Ÿ›ก๏ธ Quality and Reliability

๐Ÿงช Quality Tests

The library has undergone rigorous quality tests ensuring:

โœ… Complete Coverage
  • 64 tests covering all API endpoints
  • 100% of public endpoints tested and validated
  • Private endpoints with graceful authentication handling
  • Error scenarios completely mapped and tested
๐Ÿš€ Proven Performance
  • Real benchmarks with Mercado Bitcoin API data
  • Thresholds adjusted based on production measurements
  • HTTP/3 vs HTTP/2 comparisons with measurable results
  • Optimized memory usage and validated

๐Ÿ“ˆ Observability and Metrics

The library exposes metrics via System.Diagnostics.Metrics (.NET Instrumentation) which can be collected by OpenTelemetry, Prometheus (via exporter), or Application Insights.

๐Ÿ”ข Counters

Instrument Name Type Description Tags
_retryCounter mb_client_http_retries Counter<long> Number of retry attempts executed status_code
_circuitOpenCounter mb_client_circuit_opened Counter<long> Number of times the circuit opened (no tag)
_circuitHalfOpenCounter mb_client_circuit_half_open Counter<long> Number of transitions to half-open (no tag)
_circuitClosedCounter mb_client_circuit_closed Counter<long> Number of times the circuit closed after success (no tag)

โฑ๏ธ Histogram

Instrument Name Type Unit Description Tags
_requestDurationHistogram mb_client_http_request_duration Histogram<double> ms Duration of HTTP requests (including retries) method, outcome, status_code

๐Ÿ“˜ Detailed Documentation

For Humans ๐Ÿง‘โ€๐Ÿ’ป

Complete guide with step-by-step instructions, code examples, best practices, and detailed explanations:

For AI Agents ๐Ÿค–

For automated consumption (LLMs / agents), use specialized guides containing contracts, operational flows, prompts, and safety heuristics:

These documents are self-contained and optimized for programmatic interpretation (structures, decision tables, retry strategies, and parameter validation).


Last update: November 2025 - Version 4.0.0-alpha.1 (Migration to .NET 10 & C# 14, HTTP/3 support, Polly v8, removal of public constructors, mandatory DI and extension methods, full AOT compatibility)

GitHub stars GitHub forks NuGet Version NuGet Downloads

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.0.4 257 11/22/2025
4.0.3 155 11/22/2025
4.0.2 191 11/21/2025
4.0.1 299 11/21/2025
4.0.0 325 11/21/2025
3.0.0 272 9/12/2025
2.1.1 171 9/12/2025
2.1.0 332 8/29/2025
2.0.1 194 8/22/2025
2.0.0 133 8/22/2025
1.0.2 204 8/19/2025
1.0.1 180 8/17/2025
1.0.0 180 8/15/2025

See CHANGELOG.md for full release notes.