ccxt-csharp
Original:🇺🇸 English
Translated
CCXT cryptocurrency exchange library for C# and .NET developers. Covers both REST API (standard) and WebSocket API (real-time). Helps install CCXT, connect to exchanges, fetch market data, place orders, stream live tickers/orderbooks, handle authentication, and manage errors in .NET projects. Use when working with crypto exchanges in C# applications, trading systems, or financial software. Supports .NET Standard 2.0+.
17installs
Sourceccxt/ccxt
Added on
NPX Install
npx skill4agent add ccxt/ccxt ccxt-csharpTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →CCXT for C#
A comprehensive guide to using CCXT in C# and .NET projects for cryptocurrency exchange integration.
Installation
Via NuGet Package Manager
bash
dotnet add package CCXT.NETOr via Visual Studio:
- Right-click project → Manage NuGet Packages
- Search for "CCXT.NET"
- Click Install
Requirements
- .NET Standard 2.0 or higher
- .NET Core 2.0+ / .NET 5+ / .NET Framework 4.6.1+
Quick Start
REST API
csharp
using ccxt;
var exchange = new Binance();
await exchange.LoadMarkets();
var ticker = await exchange.FetchTicker("BTC/USDT");
Console.WriteLine(ticker);WebSocket API - Real-time Updates
csharp
using ccxt.pro;
var exchange = new Binance();
while (true)
{
var ticker = await exchange.WatchTicker("BTC/USDT");
Console.WriteLine(ticker.Last); // Live updates!
}
await exchange.Close();REST vs WebSocket
| Feature | REST API | WebSocket API |
|---|---|---|
| Use for | One-time queries, placing orders | Real-time monitoring, live price feeds |
| Import | | |
| Methods | | |
| Speed | Slower (HTTP request/response) | Faster (persistent connection) |
| Rate limits | Strict (1-2 req/sec) | More lenient (continuous stream) |
| Best for | Trading, account management | Price monitoring, arbitrage detection |
Method naming: C# uses PascalCase - not , not
FetchTickerfetchTickerWatchTickerwatchTickerCreating Exchange Instance
REST API
csharp
using ccxt;
// Public API (no authentication)
var exchange = new Binance
{
EnableRateLimit = true // Recommended!
};
// Private API (with authentication)
var exchange = new Binance
{
ApiKey = "YOUR_API_KEY",
Secret = "YOUR_SECRET",
EnableRateLimit = true
};WebSocket API
csharp
using ccxt.pro;
// Public WebSocket
var exchange = new Binance();
// Private WebSocket (with authentication)
var exchange = new Binance
{
ApiKey = "YOUR_API_KEY",
Secret = "YOUR_SECRET"
};
// Always close when done
await exchange.Close();Common REST Operations
Loading Markets
csharp
// Load all available trading pairs
await exchange.LoadMarkets();
// Access market information
var btcMarket = exchange.Market("BTC/USDT");
Console.WriteLine(btcMarket.Limits.Amount.Min); // Minimum order amountFetching Ticker
csharp
// Single ticker
var ticker = await exchange.FetchTicker("BTC/USDT");
Console.WriteLine(ticker.Last); // Last price
Console.WriteLine(ticker.Bid); // Best bid
Console.WriteLine(ticker.Ask); // Best ask
Console.WriteLine(ticker.Volume); // 24h volume
// Multiple tickers (if supported)
var tickers = await exchange.FetchTickers(new[] { "BTC/USDT", "ETH/USDT" });Fetching Order Book
csharp
// Full orderbook
var orderbook = await exchange.FetchOrderBook("BTC/USDT");
Console.WriteLine(orderbook.Bids[0]); // [price, amount]
Console.WriteLine(orderbook.Asks[0]); // [price, amount]
// Limited depth
var orderbook = await exchange.FetchOrderBook("BTC/USDT", 5); // Top 5 levelsCreating Orders
Limit Order
csharp
// Buy limit order
var order = await exchange.CreateLimitBuyOrder("BTC/USDT", 0.01, 50000);
Console.WriteLine(order.Id);
// Sell limit order
var order = await exchange.CreateLimitSellOrder("BTC/USDT", 0.01, 60000);
// Generic limit order
var order = await exchange.CreateOrder("BTC/USDT", "limit", "buy", 0.01, 50000);Market Order
csharp
// Buy market order
var order = await exchange.CreateMarketBuyOrder("BTC/USDT", 0.01);
// Sell market order
var order = await exchange.CreateMarketSellOrder("BTC/USDT", 0.01);
// Generic market order
var order = await exchange.CreateOrder("BTC/USDT", "market", "sell", 0.01);Fetching Balance
csharp
var balance = await exchange.FetchBalance();
Console.WriteLine(balance["BTC"].Free); // Available balance
Console.WriteLine(balance["BTC"].Used); // Balance in orders
Console.WriteLine(balance["BTC"].Total); // Total balanceFetching Orders
csharp
// Open orders
var openOrders = await exchange.FetchOpenOrders("BTC/USDT");
// Closed orders
var closedOrders = await exchange.FetchClosedOrders("BTC/USDT");
// All orders (open + closed)
var allOrders = await exchange.FetchOrders("BTC/USDT");
// Single order by ID
var order = await exchange.FetchOrder(orderId, "BTC/USDT");Fetching Trades
csharp
// Recent public trades
var trades = await exchange.FetchTrades("BTC/USDT", limit: 10);
// Your trades (requires authentication)
var myTrades = await exchange.FetchMyTrades("BTC/USDT");Canceling Orders
csharp
// Cancel single order
await exchange.CancelOrder(orderId, "BTC/USDT");
// Cancel all orders for a symbol
await exchange.CancelAllOrders("BTC/USDT");WebSocket Operations (Real-time)
Watching Ticker (Live Price Updates)
csharp
using ccxt.pro;
var exchange = new Binance();
while (true)
{
var ticker = await exchange.WatchTicker("BTC/USDT");
Console.WriteLine($"Last: {ticker.Last}");
}
await exchange.Close();Watching Order Book (Live Depth Updates)
csharp
var exchange = new Binance();
while (true)
{
var orderbook = await exchange.WatchOrderBook("BTC/USDT");
Console.WriteLine($"Best bid: {orderbook.Bids[0][0]}");
Console.WriteLine($"Best ask: {orderbook.Asks[0][0]}");
}
await exchange.Close();Watching Trades (Live Trade Stream)
csharp
var exchange = new Binance();
while (true)
{
var trades = await exchange.WatchTrades("BTC/USDT");
foreach (var trade in trades)
{
Console.WriteLine($"{trade.Price} {trade.Amount} {trade.Side}");
}
}
await exchange.Close();Watching Your Orders (Live Order Updates)
csharp
var exchange = new Binance
{
ApiKey = "YOUR_API_KEY",
Secret = "YOUR_SECRET"
};
while (true)
{
var orders = await exchange.WatchOrders("BTC/USDT");
foreach (var order in orders)
{
Console.WriteLine($"{order.Id} {order.Status} {order.Filled}");
}
}
await exchange.Close();Watching Balance (Live Balance Updates)
csharp
var exchange = new Binance
{
ApiKey = "YOUR_API_KEY",
Secret = "YOUR_SECRET"
};
while (true)
{
var balance = await exchange.WatchBalance();
Console.WriteLine($"BTC: {balance["BTC"].Total}");
}
await exchange.Close();Watching Multiple Symbols
csharp
var exchange = new Binance();
var symbols = new[] { "BTC/USDT", "ETH/USDT", "SOL/USDT" };
while (true)
{
var tickers = await exchange.WatchTickers(symbols);
foreach (var kvp in tickers)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value.Last}");
}
}
await exchange.Close();Complete Method Reference
Market Data Methods
Tickers & Prices
- - Fetch ticker for one symbol
fetchTicker(symbol) - - Fetch multiple tickers at once
fetchTickers([symbols]) - - Fetch best bid/ask for multiple symbols
fetchBidsAsks([symbols]) - - Fetch last prices
fetchLastPrices([symbols]) - - Fetch mark prices (derivatives)
fetchMarkPrices([symbols])
Order Books
- - Fetch order book
fetchOrderBook(symbol, limit) - - Fetch multiple order books
fetchOrderBooks([symbols]) - - Fetch level 2 order book
fetchL2OrderBook(symbol) - - Fetch level 3 order book (if supported)
fetchL3OrderBook(symbol)
Trades
- - Fetch public trades
fetchTrades(symbol, since, limit) - - Fetch your trades (auth required)
fetchMyTrades(symbol, since, limit) - - Fetch trades for specific order
fetchOrderTrades(orderId, symbol)
OHLCV (Candlesticks)
- - Fetch candlestick data
fetchOHLCV(symbol, timeframe, since, limit) - - Fetch index price OHLCV
fetchIndexOHLCV(symbol, timeframe) - - Fetch mark price OHLCV
fetchMarkOHLCV(symbol, timeframe) - - Fetch premium index OHLCV
fetchPremiumIndexOHLCV(symbol, timeframe)
Account & Balance
- - Fetch account balance (auth required)
fetchBalance() - - Fetch sub-accounts
fetchAccounts() - - Fetch ledger history
fetchLedger(code, since, limit) - - Fetch specific ledger entry
fetchLedgerEntry(id, code) - - Fetch transactions
fetchTransactions(code, since, limit) - - Fetch deposit history
fetchDeposits(code, since, limit) - - Fetch withdrawal history
fetchWithdrawals(code, since, limit) - - Fetch both deposits and withdrawals
fetchDepositsWithdrawals(code, since, limit)
Trading Methods
Creating Orders
- - Create order (generic)
createOrder(symbol, type, side, amount, price, params) - - Create limit order
createLimitOrder(symbol, side, amount, price) - - Create market order
createMarketOrder(symbol, side, amount) - - Buy limit order
createLimitBuyOrder(symbol, amount, price) - - Sell limit order
createLimitSellOrder(symbol, amount, price) - - Buy market order
createMarketBuyOrder(symbol, amount) - - Sell market order
createMarketSellOrder(symbol, amount) - - Buy with specific cost
createMarketBuyOrderWithCost(symbol, cost) - - Stop-limit order
createStopLimitOrder(symbol, side, amount, price, stopPrice) - - Stop-market order
createStopMarketOrder(symbol, side, amount, stopPrice) - - Stop-loss order
createStopLossOrder(symbol, side, amount, stopPrice) - - Take-profit order
createTakeProfitOrder(symbol, side, amount, takeProfitPrice) - - Trailing stop
createTrailingAmountOrder(symbol, side, amount, trailingAmount) - - Trailing stop %
createTrailingPercentOrder(symbol, side, amount, trailingPercent) - - Trigger order
createTriggerOrder(symbol, side, amount, triggerPrice) - - Post-only order
createPostOnlyOrder(symbol, side, amount, price) - - Reduce-only order
createReduceOnlyOrder(symbol, side, amount, price) - - Create multiple orders at once
createOrders([orders]) - - OCO order
createOrderWithTakeProfitAndStopLoss(symbol, type, side, amount, price, tpPrice, slPrice)
Managing Orders
- - Fetch single order
fetchOrder(orderId, symbol) - - Fetch all orders
fetchOrders(symbol, since, limit) - - Fetch open orders
fetchOpenOrders(symbol, since, limit) - - Fetch closed orders
fetchClosedOrders(symbol, since, limit) - - Fetch canceled orders
fetchCanceledOrders(symbol, since, limit) - - Fetch specific open order
fetchOpenOrder(orderId, symbol) - - Fetch orders by status
fetchOrdersByStatus(status, symbol) - - Cancel single order
cancelOrder(orderId, symbol) - - Cancel multiple orders
cancelOrders([orderIds], symbol) - - Cancel all orders for symbol
cancelAllOrders(symbol) - - Modify order
editOrder(orderId, symbol, type, side, amount, price)
Margin & Leverage
- - Fetch borrow rate for margin
fetchBorrowRate(code) - - Fetch multiple borrow rates
fetchBorrowRates([codes]) - - Historical borrow rates
fetchBorrowRateHistory(code, since, limit) - - Cross margin borrow rate
fetchCrossBorrowRate(code) - - Isolated margin borrow rate
fetchIsolatedBorrowRate(symbol, code) - - Borrow margin
borrowMargin(code, amount, symbol) - - Repay margin
repayMargin(code, amount, symbol) - - Fetch leverage
fetchLeverage(symbol) - - Set leverage
setLeverage(leverage, symbol) - - Fetch leverage tiers
fetchLeverageTiers(symbols) - - Leverage tiers for market
fetchMarketLeverageTiers(symbol) - - Set margin mode (cross/isolated)
setMarginMode(marginMode, symbol) - - Fetch margin mode
fetchMarginMode(symbol)
Derivatives & Futures
Positions
- - Fetch single position
fetchPosition(symbol) - - Fetch all positions
fetchPositions([symbols]) - - Fetch positions for symbol
fetchPositionsForSymbol(symbol) - - Position history
fetchPositionHistory(symbol, since, limit) - - Multiple position history
fetchPositionsHistory(symbols, since, limit) - - Fetch position mode (one-way/hedge)
fetchPositionMode(symbol) - - Set position mode
setPositionMode(hedged, symbol) - - Close position
closePosition(symbol, side) - - Close all positions
closeAllPositions()
Funding & Settlement
- - Current funding rate
fetchFundingRate(symbol) - - Multiple funding rates
fetchFundingRates([symbols]) - - Funding rate history
fetchFundingRateHistory(symbol, since, limit) - - Your funding payments
fetchFundingHistory(symbol, since, limit) - - Funding interval
fetchFundingInterval(symbol) - - Settlement history
fetchSettlementHistory(symbol, since, limit) - - Your settlement history
fetchMySettlementHistory(symbol, since, limit)
Open Interest & Liquidations
- - Open interest for symbol
fetchOpenInterest(symbol) - - Multiple open interests
fetchOpenInterests([symbols]) - - OI history
fetchOpenInterestHistory(symbol, timeframe, since, limit) - - Public liquidations
fetchLiquidations(symbol, since, limit) - - Your liquidations
fetchMyLiquidations(symbol, since, limit)
Options
- - Fetch option info
fetchOption(symbol) - - Fetch option chain
fetchOptionChain(code) - - Fetch option greeks
fetchGreeks(symbol) - - Volatility history
fetchVolatilityHistory(code, since, limit) - - Fetch underlying assets
fetchUnderlyingAssets()
Fees & Limits
- - Trading fee for symbol
fetchTradingFee(symbol) - - Trading fees for multiple symbols
fetchTradingFees([symbols]) - - Trading limits
fetchTradingLimits([symbols]) - - Transaction/withdrawal fee
fetchTransactionFee(code) - - Multiple transaction fees
fetchTransactionFees([codes]) - - Deposit/withdrawal fee
fetchDepositWithdrawFee(code) - - Multiple deposit/withdraw fees
fetchDepositWithdrawFees([codes])
Deposits & Withdrawals
- - Get deposit address
fetchDepositAddress(code, params) - - Multiple deposit addresses
fetchDepositAddresses([codes]) - - Addresses by network
fetchDepositAddressesByNetwork(code) - - Create new deposit address
createDepositAddress(code, params) - - Fetch single deposit
fetchDeposit(id, code) - - Fetch single withdrawal
fetchWithdrawal(id, code) - - Fetch withdrawal addresses
fetchWithdrawAddresses(code) - - Fetch whitelist
fetchWithdrawalWhitelist(code) - - Withdraw funds
withdraw(code, amount, address, tag, params) - - Deposit funds (if supported)
deposit(code, amount, params)
Transfer & Convert
- - Internal transfer
transfer(code, amount, fromAccount, toAccount) - - Fetch transfer info
fetchTransfer(id, code) - - Fetch transfer history
fetchTransfers(code, since, limit) - - Currencies available for convert
fetchConvertCurrencies() - - Get conversion quote
fetchConvertQuote(fromCode, toCode, amount) - - Execute conversion
createConvertTrade(fromCode, toCode, amount) - - Fetch convert trade
fetchConvertTrade(id) - - Convert history
fetchConvertTradeHistory(code, since, limit)
Market Info
- - Fetch all markets
fetchMarkets() - - Fetch all currencies
fetchCurrencies() - - Fetch exchange server time
fetchTime() - - Fetch exchange status
fetchStatus() - - Borrow interest paid
fetchBorrowInterest(code, symbol, since, limit) - - Long/short ratio
fetchLongShortRatio(symbol, timeframe, since, limit) - - L/S ratio history
fetchLongShortRatioHistory(symbol, timeframe, since, limit)
WebSocket Methods (ccxt.pro)
All REST methods have WebSocket equivalents with prefix:
watch*Real-time Market Data
- - Watch single ticker
watchTicker(symbol) - - Watch multiple tickers
watchTickers([symbols]) - - Watch order book updates
watchOrderBook(symbol) - - Watch multiple order books
watchOrderBookForSymbols([symbols]) - - Watch public trades
watchTrades(symbol) - - Watch candlestick updates
watchOHLCV(symbol, timeframe) - - Watch best bid/ask
watchBidsAsks([symbols])
Real-time Account Data (Auth Required)
- - Watch balance updates
watchBalance() - - Watch your order updates
watchOrders(symbol) - - Watch your trade updates
watchMyTrades(symbol) - - Watch position updates
watchPositions([symbols]) - - Watch positions for symbol
watchPositionsForSymbol(symbol)
Authentication Required
Methods marked with 🔒 require API credentials:
- All methods (creating orders, addresses)
create* - All methods (canceling orders)
cancel* - All methods (modifying orders)
edit* - All methods (your trades, orders)
fetchMy* - ,
fetchBalance,fetchLedgerfetchAccounts - ,
withdraw,transferdeposit - Margin/leverage methods
- Position methods
- ,
watchBalance,watchOrders,watchMyTradeswatchPositions
Checking Method Availability
Not all exchanges support all methods. Check before using:
// Check if method is supported
if (exchange.has['fetchOHLCV']) {
const candles = await exchange.fetchOHLCV('BTC/USDT', '1h')
}
// Check multiple capabilities
console.log(exchange.has)
// {
// fetchTicker: true,
// fetchOHLCV: true,
// fetchMyTrades: true,
// fetchPositions: false,
// ...
// }Method Naming Convention
- - REST API methods (HTTP requests)
fetch* - - WebSocket methods (real-time streams)
watch* - - Create new resources (orders, addresses)
create* - - Cancel existing resources
cancel* - - Modify existing resources
edit* - - Configure settings (leverage, margin mode)
set* - suffix - WebSocket variant (some exchanges)
*Ws
Proxy Configuration
CCXT supports HTTP, HTTPS, and SOCKS proxies for both REST and WebSocket connections.
Setting Proxy
// HTTP Proxy
exchange.httpProxy = 'http://your-proxy-host:port'
// HTTPS Proxy
exchange.httpsProxy = 'https://your-proxy-host:port'
// SOCKS Proxy
exchange.socksProxy = 'socks://your-proxy-host:port'
// Proxy with authentication
exchange.httpProxy = 'http://user:pass@proxy-host:port'Proxy for WebSocket
WebSocket connections also respect proxy settings:
exchange.httpsProxy = 'https://proxy:8080'
// WebSocket connections will use this proxyTesting Proxy Connection
exchange.httpProxy = 'http://localhost:8080'
try {
await exchange.fetchTicker('BTC/USDT')
console.log('Proxy working!')
} catch (error) {
console.error('Proxy connection failed:', error)
}WebSocket-Specific Methods
Some exchanges provide WebSocket variants of REST methods for faster order placement and management. These use the suffix:
*WsTrading via WebSocket
Creating Orders:
- - Create order via WebSocket (faster than REST)
createOrderWs - - Create limit order via WebSocket
createLimitOrderWs - - Create market order via WebSocket
createMarketOrderWs - - Buy limit order via WebSocket
createLimitBuyOrderWs - - Sell limit order via WebSocket
createLimitSellOrderWs - - Buy market order via WebSocket
createMarketBuyOrderWs - - Sell market order via WebSocket
createMarketSellOrderWs - - Stop-limit order via WebSocket
createStopLimitOrderWs - - Stop-market order via WebSocket
createStopMarketOrderWs - - Stop-loss order via WebSocket
createStopLossOrderWs - - Take-profit order via WebSocket
createTakeProfitOrderWs - - Trailing stop via WebSocket
createTrailingAmountOrderWs - - Trailing stop % via WebSocket
createTrailingPercentOrderWs - - Post-only order via WebSocket
createPostOnlyOrderWs - - Reduce-only order via WebSocket
createReduceOnlyOrderWs
Managing Orders:
- - Edit order via WebSocket
editOrderWs - - Cancel order via WebSocket (faster than REST)
cancelOrderWs - - Cancel multiple orders via WebSocket
cancelOrdersWs - - Cancel all orders via WebSocket
cancelAllOrdersWs
Fetching Data:
- - Fetch order via WebSocket
fetchOrderWs - - Fetch orders via WebSocket
fetchOrdersWs - - Fetch open orders via WebSocket
fetchOpenOrdersWs - - Fetch closed orders via WebSocket
fetchClosedOrdersWs - - Fetch your trades via WebSocket
fetchMyTradesWs - - Fetch balance via WebSocket
fetchBalanceWs - - Fetch position via WebSocket
fetchPositionWs - - Fetch positions via WebSocket
fetchPositionsWs - - Fetch positions for symbol via WebSocket
fetchPositionsForSymbolWs - - Fetch trading fees via WebSocket
fetchTradingFeesWs
When to Use WebSocket Methods
Use methods when:
*Ws- You need faster order placement (lower latency)
- You're already connected via WebSocket
- You want to reduce REST API rate limit usage
- Trading strategies require sub-100ms latency
Use REST methods when:
- You need guaranteed execution confirmation
- You're making one-off requests
- The exchange doesn't support the WebSocket variant
- You need detailed error responses
Example: Order Placement Comparison
REST API (slower, more reliable):
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)WebSocket API (faster, lower latency):
const order = await exchange.createOrderWs('BTC/USDT', 'limit', 'buy', 0.01, 50000)Checking WebSocket Method Availability
Not all exchanges support WebSocket trading methods:
if (exchange.has['createOrderWs']) {
// Exchange supports WebSocket order creation
const order = await exchange.createOrderWs('BTC/USDT', 'limit', 'buy', 0.01, 50000)
} else {
// Fall back to REST
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)
}Authentication
Setting API Keys
csharp
using System;
// During instantiation (recommended)
var exchange = new Binance
{
ApiKey = Environment.GetEnvironmentVariable("BINANCE_API_KEY"),
Secret = Environment.GetEnvironmentVariable("BINANCE_SECRET"),
EnableRateLimit = true
};
// After instantiation
exchange.ApiKey = Environment.GetEnvironmentVariable("BINANCE_API_KEY");
exchange.Secret = Environment.GetEnvironmentVariable("BINANCE_SECRET");Testing Authentication
csharp
try
{
var balance = await exchange.FetchBalance();
Console.WriteLine("Authentication successful!");
}
catch (AuthenticationError)
{
Console.WriteLine("Invalid API credentials");
}Error Handling
Exception Hierarchy
BaseError
├─ NetworkError (recoverable - retry)
│ ├─ RequestTimeout
│ ├─ ExchangeNotAvailable
│ ├─ RateLimitExceeded
│ └─ DDoSProtection
└─ ExchangeError (non-recoverable - don't retry)
├─ AuthenticationError
├─ InsufficientFunds
├─ InvalidOrder
└─ NotSupportedBasic Error Handling
csharp
using ccxt;
try
{
var ticker = await exchange.FetchTicker("BTC/USDT");
}
catch (NetworkError ex)
{
Console.WriteLine($"Network error - retry: {ex.Message}");
}
catch (ExchangeError ex)
{
Console.WriteLine($"Exchange error - do not retry: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unknown error: {ex.Message}");
}Specific Exception Handling
csharp
try
{
var order = await exchange.CreateOrder("BTC/USDT", "limit", "buy", 0.01, 50000);
}
catch (InsufficientFunds)
{
Console.WriteLine("Not enough balance");
}
catch (InvalidOrder)
{
Console.WriteLine("Invalid order parameters");
}
catch (RateLimitExceeded)
{
Console.WriteLine("Rate limit hit - wait before retrying");
await Task.Delay(1000); // Wait 1 second
}
catch (AuthenticationError)
{
Console.WriteLine("Check your API credentials");
}Retry Logic for Network Errors
csharp
async Task<Ticker> FetchWithRetry(int maxRetries = 3)
{
for (int i = 0; i < maxRetries; i++)
{
try
{
return await exchange.FetchTicker("BTC/USDT");
}
catch (NetworkError)
{
if (i < maxRetries - 1)
{
Console.WriteLine($"Retry {i + 1}/{maxRetries}");
await Task.Delay(1000 * (i + 1)); // Exponential backoff
}
else
{
throw;
}
}
}
return null;
}Rate Limiting
Built-in Rate Limiter (Recommended)
csharp
var exchange = new Binance
{
EnableRateLimit = true // Automatically throttles requests
};Manual Delays
csharp
await exchange.FetchTicker("BTC/USDT");
await Task.Delay((int)exchange.RateLimit); // Wait between requests
await exchange.FetchTicker("ETH/USDT");Checking Rate Limit
csharp
Console.WriteLine(exchange.RateLimit); // Milliseconds between requestsCommon Pitfalls
Wrong Method Casing
csharp
// Wrong - lowercase (JavaScript style)
var ticker = await exchange.fetchTicker("BTC/USDT"); // ERROR!
// Correct - PascalCase (C# style)
var ticker = await exchange.FetchTicker("BTC/USDT");Not Awaiting Async Methods
csharp
// Wrong - missing await
var ticker = exchange.FetchTicker("BTC/USDT"); // Returns Task, not Ticker!
Console.WriteLine(ticker.Last); // ERROR!
// Correct
var ticker = await exchange.FetchTicker("BTC/USDT");
Console.WriteLine(ticker.Last); // Works!Using REST for Real-time Monitoring
csharp
// Wrong - wastes rate limits
while (true)
{
var ticker = await exchange.FetchTicker("BTC/USDT"); // REST
Console.WriteLine(ticker.Last);
await Task.Delay(1000);
}
// Correct - use WebSocket
using ccxt.pro;
var exchange = new Binance();
while (true)
{
var ticker = await exchange.WatchTicker("BTC/USDT"); // WebSocket
Console.WriteLine(ticker.Last);
}Not Closing WebSocket Connections
csharp
// Wrong - memory leak
var exchange = new ccxt.pro.Binance();
var ticker = await exchange.WatchTicker("BTC/USDT");
// Forgot to close!
// Correct
var exchange = new ccxt.pro.Binance();
try
{
while (true)
{
var ticker = await exchange.WatchTicker("BTC/USDT");
Console.WriteLine(ticker.Last);
}
}
finally
{
await exchange.Close();
}Incorrect Symbol Format
csharp
// Wrong symbol formats
"BTCUSDT" // Wrong - no separator
"BTC-USDT" // Wrong - dash separator
"btc/usdt" // Wrong - lowercase
// Correct symbol format
"BTC/USDT" // Unified CCXT formatTroubleshooting
Common Issues
1. "Package CCXT.NET not found"
- Solution: Run
dotnet add package CCXT.NET
2. "RateLimitExceeded"
- Solution: Set
EnableRateLimit = true
3. "AuthenticationError"
- Solution: Check API key and secret
- Verify API key permissions on exchange
- Check system clock is synced
4. "InvalidNonce"
- Solution: Sync system clock
- Use only one exchange instance per API key
5. "InsufficientFunds"
- Solution: Check available balance ()
balance["BTC"].Free - Account for trading fees
6. "ExchangeNotAvailable"
- Solution: Check exchange status/maintenance
- Retry after a delay
Debugging
csharp
// Enable verbose logging
exchange.Verbose = true;
// Check exchange capabilities
Console.WriteLine(exchange.Has);
// {
// FetchTicker = true,
// FetchOrderBook = true,
// CreateOrder = true,
// ...
// }
// Check market information
var market = exchange.Markets["BTC/USDT"];
// Check last request/response
Console.WriteLine(exchange.LastHttpResponse);
Console.WriteLine(exchange.LastJsonResponse);