К основному содержанию
скилл CX Codex

ccxt-csharp — скилл для Claude Code: настройка CCXT в C#

Скилл ccxt-csharp для Claude Code помогает подключить CCXT к проекту на C# и работать с криптобиржами через REST и WebSocket. Включается при настройке обмена и рыночных данных.

MIT ★ 44 950 обновлён 2026-11-18

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add ccxt/ccxt --skill ccxt-csharp -a claude-code
Открыть на GitHub

Что делает ccxt-csharp

Скилл объясняет, как установить CCXT.NET и подключить биржу к приложению на C# или .NET. Он разбирает REST-запросы для тикеров, стакана, баланса и ордеров, а также потоки WebSocket для котировок, сделок и изменений стакана.

В примерах используются классы бирж, методы Fetch* и Watch*, а для приватных запросов — apiKey и secret. REST и WebSocket подключаются через пространства имён ccxt и ccxt.pro; WebSocket-соединение закрывают вызовом Close(). Для работы проекта требуется .NET Standard 2.0 или выше; также перечислены .NET Core 2.0+, .NET 5+ и .NET Framework 4.6.1+.

Какие задачи решает

  • подключить CCXT.NET к проекту на C#
  • получить тикер и данные стакана через REST API
  • размещать и отменять ордера на бирже
  • принимать обновления котировок через WebSocket

Примеры запросов агенту

  • Подключи CCXT.NET к моему проекту на C# и получи тикер BTC/USDT через REST.
  • Покажи, как выставить лимитный ордер и получить баланс через CCXT.
  • Добавь получение обновлений стакана BTC/USDT через WebSocket.

Как установить ccxt-csharp

1Через Skills CLI (Vercel)

npx skills add ccxt/ccxt --skill ccxt-csharp -a claude-code

2Вручную: положить файлы

~/.claude/skills/ccxt-csharp/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/ccxt-csharp/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о ccxt-csharp

Как установить ccxt-csharp в Claude Code?

Выполни npx skills add ccxt/ccxt --skill ccxt-csharp -a claude-code. Файл скилла находится по пути ~/.claude/skills/ccxt-csharp/SKILL.md.

Что делает ccxt-csharp?

Помогает подключить CCXT.NET к приложению на C# и использовать REST API или WebSocket для работы с биржевыми данными и ордерами.

Что нужно для работы ccxt-csharp?

Нужен .NET Standard 2.0 или выше. Также перечислены .NET Core 2.0+, .NET 5+ и .NET Framework 4.6.1+.

Исходный текст

SKILL.md · MIT
---
name: ccxt-csharp
description: 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+.
---

# 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.NET
```

Or via Visual Studio:
1. Right-click project → Manage NuGet Packages
2. Search for "CCXT.NET"
3. 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** | `using ccxt;` | `using ccxt.pro;` |
| **Methods** | `Fetch*` (FetchTicker, FetchOrderBook) | `Watch*` (WatchTicker, WatchOrderBook) |
| **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 - `FetchTicker` not `fetchTicker`, `WatchTicker` not `watchTicker`. Exceptions that stay camelCase: `unWatch*` methods, synchronous helpers (`amountToPrecision`, `priceToPrecision`, `setSandboxMode`; `exchange.market(symbol)` returns the raw dictionary, while `exchange.Market(symbol)` returns the typed `Market` struct) and properties (`apiKey`, `secret`, `has`, `features`, `markets`, `verbose`). Result structs use lowercase fields (`ticker.last`, `order.id`, `balance["BTC"].free`).

## Creating Exchange Instance

### REST API
```csharp
using ccxt;

// Public API (no authentication)
var exchange = new Binance(new Dictionary<string, object>
{
    { "enableRateLimit", true }, // Recommended!
});

// Private API (with authentication)
var exchange = new Binance(new Dictionary<string, object>
{
    { "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(new Dictionary<string, object>
{
    { "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 amount
```

### Fetching 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.baseVolume);    // 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 levels
```

### Creating 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 balance
```

### Fetching 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");
    var bestBid = (IList<object>)orderbook.bids[0]; // each row is [price, amount]
    var bestAsk = (IList<object>)orderbook.asks[0];
    Console.WriteLine($"Best bid: {bestBid[0]}");
    Console.WriteLine($"Best ask: {bestAsk[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(new Dictionary<string, object>
{
    { "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(new Dictionary<string, object>
{
    { "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.tickers)
    {
        Console.WriteLine($"{kvp.Key}: {kvp.Value.last}");
    }
}
await exchange.Close();
```

## Testnet, Capabilities, Precision and Pagination

### Testnet / sandbox first
```csharp
var exchange = new Binance();
exchange.apiKey = "...";
exchange.secret = "...";
exchange.setSandboxMode(true); // right after construction; throws NotSupported if there is no testnet
```
Always try orders on a testnet (or with the minimum size) before going live.

### Check what an exchange supports
```csharp
var has = exchange.has;
if (has.ContainsKey("fetchOHLCV") && has["fetchOHLCV"] is bool supported && supported) { /* ... */ }
var features = exchange.features; // per market type: createOrder params, fetch limits, daysBack, ...
```

### Respect market precision and limits
```csharp
await exchange.LoadMarkets();
var amount = exchange.amountToPrecision("BTC/USDT", 0.0012345); // string
var price = exchange.priceToPrecision("BTC/USDT", 64123.456789);
var order = await exchange.CreateOrder("BTC/USDT", "limit", "buy", Convert.ToDouble(amount), Convert.ToDouble(price));
```

### Pagination
```csharp
var candles = await exchange.FetchOHLCV("BTC/USDT", "1h", since, null, new Dictionary<string, object> { { "paginate", true } });
```

### Unsubscribing and closing (ccxt.pro)
```csharp
using ccxt.pro;

var exchange = new Binance();
await exchange.WatchTicker("BTC/USDT");
await exchange.unWatchTicker("BTC/USDT"); // lowercase in C#: unWatch* are not PascalCased; check exchange.has["unWatchTicker"] first
await exchange.Close();
```

## Complete Method Reference

Names below are the canonical camelCase unified names; use your language's casing (`fetch_ohlcv` in Python/PHP, `FetchOHLCV` in C#/Go). Arguments are **positional in this order** — trailing ones are optional and `params` (exchange-specific extras) is always last and omitted here. Signatures mirror `ts/src/base/Exchange.ts`. Support varies per exchange: check `exchange.has['<method>']` (and `exchange.features` for finer options) before calling.

### Market Data Methods

#### Tickers & Prices
- `fetchTicker(symbol)` - Fetch ticker for one symbol
- `fetchTickers([symbols])` - Fetch multiple tickers at once
- `fetchBidsAsks([symbols])` - Fetch best bid/ask for multiple symbols
- `fetchLastPrices([symbols])` - Fetch last prices
- `fetchMarkPrice(symbol)` - Fetch mark price (derivatives)
- `fetchMarkPrices([symbols])` - Fetch mark prices (derivatives)

#### Order Books
- `fetchOrderBook(symbol, limit)` - Fetch order book
- `fetchOrderBooks([symbols], limit)` - Fetch multiple order books
- `fetchL2OrderBook(symbol, limit)` - Fetch level 2 order book
- `fetchL3OrderBook(symbol, limit)` - Fetch level 3 order book (if supported)

#### Trades
- `fetchTrades(symbol, since, limit)` - Fetch public trades
- `fetchMyTrades(symbol, since, limit)` - Fetch your trades (auth required)
- `fetchOrderTrades(id, symbol, since, limit)` - Fetch trades for specific order

#### OHLCV (Candlesticks)
- `fetchOHLCV(symbol, timeframe, since, limit)` - Fetch candlestick data
- `fetchIndexOHLCV(symbol, timeframe, since, limit)` - Fetch index price OHLCV
- `fetchMarkOHLCV(symbol, timeframe, since, limit)` - Fetch mark price OHLCV
- `fetchPremiumIndexOHLCV(symbol, timeframe, since, limit)` - Fetch premium index OHLCV

### Account & Balance

- `fetchBalance()` - Fetch account balance (auth required)
- `fetchAccounts()` - Fetch sub-accounts
- `fetchLedger(code, since, limit)` - Fetch ledger history
- `fetchLedgerEntry(id, code)` - Fetch specific ledger entry
- `fetchDeposits(code, since, limit)` - Fetch deposit history
- `fetchWithdrawals(code, since, limit)` - Fetch withdrawal history
- `fetchDepositsWithdrawals(code, since, limit)` - Fetch both deposits and withdrawals (replaces the older `fetchTransactions`)

### Trading Methods

#### Creating Orders
- `createOrder(symbol, type, side, amount, price)` - Create order (generic; `price` is `undefined`/`None`/`null` for market orders)
- `createLimitOrder(symbol, side, amount, price)` - Create limit order
- `createMarketOrder(symbol, side, amount)` - Create market order
- `createLimitBuyOrder(symbol, amount, price)` - Buy limit order
- `createLimitSellOrder(symbol, amount, price)` - Sell limit order
- `createMarketBuyOrder(symbol, amount)` - Buy market order
- `createMarketSellOrder(symbol, amount)` - Sell market order
- `createMarketOrderWithCost(symbol, side, cost)` - Market order sized in quote currency
- `createMarketBuyOrderWithCost(symbol, cost)` - Buy spending a quote amount (e.g. 100 USDT)
- `createMarketSellOrderWithCost(symbol, cost)` - Sell for a quote amount
- `createStopLimitOrder(symbol, side, amount, price, triggerPrice)` - Stop-limit order
- `createStopMarketOrder(symbol, side, amount, triggerPrice)` - Stop-market order
- `createStopLossOrder(symbol, type, side, amount, price, stopLossPrice)` - Stop-loss order
- `createTakeProfitOrder(symbol, type, side, amount, price, takeProfitPrice)` - Take-profit order
- `createTriggerOrder(symbol, type, side, amount, price, triggerPrice)` - Trigger (conditional) order
- `createTrailingAmountOrder(symbol, type, side, amount, price, trailingAmount, trailingTriggerPrice)` - Trailing stop (absolute)
- `createTrailingPercentOrder(symbol, type, side, amount, price, trailingPercent, trailingTriggerPrice)` - Trailing stop (%)
- `createPostOnlyOrder(symbol, type, side, amount, price)` - Post-only (maker-only) order
- `createReduceOnlyOrder(symbol, type, side, amount, price)` - Reduce-only order
- `createOrderWithTakeProfitAndStopLoss(symbol, type, side, amount, price, takeProfit, stopLoss)` - Order with attached TP/SL
- `createOrders([orders])` - Create multiple orders at once

The unified way to attach conditions to any `createOrder` call is through `params`: `triggerPrice`, `stopLossPrice`, `takeProfitPrice`, `stopLoss: { triggerPrice, price }`, `takeProfit: { triggerPrice, price }`, `reduceOnly`, `postOnly`, `timeInForce`, `clientOrderId`, `marginMode`, `hedged`. Which ones an exchange accepts is declared in `exchange.features[marketType][subType].createOrder`. (`stopPrice` is a legacy alias; prefer `triggerPrice`.)

#### Managing Orders
- `fetchOrder(id, symbol)` - Fetch single order
- `fetchOrders(symbol, since, limit)` - Fetch all orders
- `fetchOpenOrders(symbol, since, limit)` - Fetch open orders
- `fetchClosedOrders(symbol, since, limit)` - Fetch closed orders
- `fetchCanceledOrders(symbol, since, limit)` - Fetch canceled orders
- `fetchCanceledAndClosedOrders(symbol, since, limit)` - Fetch canceled + closed orders
- `fetchOrderWithClientOrderId(clientOrderId, symbol)` - Fetch by your client order id
- `cancelOrder(id, symbol)` - Cancel single order
- `cancelOrderWithClientOrderId(clientOrderId, symbol)` - Cancel by your client order id
- `cancelOrders([ids], symbol)` - Cancel multiple orders
- `cancelOrdersForSymbols([{ id, symbol }])` - Cancel orders across symbols
- `cancelAllOrders(symbol)` - Cancel all orders for symbol
- `cancelAllOrdersAfter(timeout)` - Dead-man switch: cancel everything after `timeout` ms (0 disables)
- `editOrder(id, symbol, type, side, amount, price)` - Modify order
- `editOrders([orders])` - Modify multiple orders

### Margin & Leverage

- `fetchCrossBorrowRate(code)` - Cross-margin borrow rate
- `fetchCrossBorrowRates()` - All cross-margin borrow rates
- `fetchIsolatedBorrowRate(symbol)` - Isolated-margin borrow rate
- `fetchIsolatedBorrowRates()` - All isolated-margin borrow rates
- `fetchBorrowInterest(code, symbol, since, limit)` - Borrow interest paid
- `borrowCrossMargin(code, amount)` / `repayCrossMargin(code, amount)` - Cross-margin loans
- `borrowIsolatedMargin(symbol, code, amount)` / `repayIsolatedMargin(symbol, code, amount)` - Isolated-margin loans
- `fetchLeverage(symbol)` / `fetchLeverages([symbols])` - Current leverage
- `setLeverage(leverage, symbol)` - Set leverage
- `fetchLeverageTiers([symbols])` - Leverage tiers
- `fetchMarketLeverageTiers(symbol)` - Leverage tiers for one market
- `fetchMarginMode(symbol)` / `fetchMarginModes([symbols])` - Margin mode (cross/isolated)
- `setMarginMode(marginMode, symbol)` - Set margin mode
- `addMargin(symbol, amount)` / `reduceMargin(symbol, amount)` / `setMargin(symbol, amount)` - Adjust isolated position margin
- `fetchMarginAdjustmentHistory(symbol, type, since, limit)` - Margin adjustment history

Deprecated and always throw `NotSupported`: `fetchBorrowRate`, `borrowMargin`, `repayMargin` — use the cross/isolated variants above (there is no `fetchBorrowRates`; use `fetchCrossBorrowRates` / `fetchIsolatedBorrowRates`).

### Derivatives & Futures

#### Positions
- `fetchPosition(symbol)` - Fetch single position
- `fetchPositions([symbols])` - Fetch all positions
- `fetchPositionsForSymbol(symbol)` - All positions for one symbol (e.g. both hedge sides)
- `fetchPositionHistory(symbol, since, limit)` - Position history for one symbol
- `fetchPositionsHistory([symbols], since, limit)` - Position history for many symbols
- `fetchPositionsRisk([symbols])` - Position risk info
- `fetchPositionMode(symbol)` - Fetch position mode (one-way/hedge)
- `setPositionMode(hedged, symbol)` - Set position mode
- `closePosition(symbol, side)` - Close position
- `closeAllPositions()` - Close all positions

#### Funding & Settlement
- `fetchFundingRate(symbol)` - Current funding rate
- `fetchFundingRates([symbols])` - Multiple funding rates
- `fetchFundingRateHistory(symbol, since, limit)` - Funding rate history
- `fetchFundingHistory(symbol, since, limit)` - Your funding payments
- `fetchFundingInterval(symbol)` / `fetchFundingIntervals([symbols])` - Funding interval

#### Open Interest, Liquidations & Sentiment
- `fetchOpenInterest(symbol)` - Open interest for symbol
- `fetchOpenInterests([symbols])` - Multiple open interests
- `fetchOpenInterestHistory(symbol, timeframe, since, limit)` - OI history
- `fetchLiquidations(symbol, since, limit)` - Public liquidations
- `fetchMyLiquidations(symbol, since, limit)` - Your liquidations
- `fetchLongShortRatioHistory(symbol, timeframe, since, limit)` - Long/short ratio history

#### Options
- `fetchOption(symbol)` - Fetch option info
- `fetchOptionChain(code)` - Fetch option chain
- `fetchGreeks(symbol)` - Fetch option greeks
- `fetchAllGreeks([symbols])` - Greeks for many options

Exchange-specific (implemented by only a few venues, not in the base class): `fetchSettlementHistory`, `fetchMySettlementHistory`, `fetchVolatilityHistory`, `fetchUnderlyingAssets`, `fetchBorrowRateHistory`, `fetchOpenOrder`, `fetchOrdersByStatus`, `fetchDeposit`, `fetchWithdrawal`. Always gate them on `exchange.has`.

### Fees

- `fetchTradingFee(symbol)` - Trading fee for symbol
- `fetchTradingFees()` - Trading fees for all symbols
- `fetchDepositWithdrawFee(code)` - Deposit/withdrawal fee
- `fetchDepositWithdrawFees([codes])` - Multiple deposit/withdraw fees
- `fetchTransactionFee(code)` / `fetchTransactionFees([codes])` - Older fee API, prefer `fetchDepositWithdrawFees`

### Deposits & Withdrawals

- `fetchDepositAddress(code)` - Get deposit address (pass `{ network: 'TRC20' }` in params to choose a chain)
- `fetchDepositAddresses([codes])` - Multiple deposit addresses
- `fetchDepositAddressesByNetwork(code)` - Addresses by network
- `createDepositAddress(code)` - Create new deposit address
- `withdraw(code, amount, address)` - Withdraw funds; pass the memo/tag and network in params: `{ tag: '...', network: 'ERC20' }`

### Transfer & Convert

- `transfer(code, amount, fromAccount, toAccount)` - Internal transfer between accounts (`'spot'`, `'swap'`, `'funding'`, ...)
- `fetchTransfer(id, code)` - Fetch transfer info
- `fetchTransfers(code, since, limit)` - Fetch transfer history
- `fetchConvertCurrencies()` - Currencies available for convert
- `fetchConvertQuote(fromCode, toCode, amount)` - Get conversion quote (returns a quote `id`)
- `createConvertTrade(id, fromCode, toCode, amount)` - Execute a conversion using the quote `id`
- `fetchConvertTrade(id, code)` - Fetch convert trade
- `fetchConvertTradeHistory(code, since, limit)` - Convert history

### Market Info

- `loadMarkets(reload)` - Load and cache markets (call once; most methods do it for you)
- `fetchMarkets()` - Fetch all markets (raw, uncached)
- `fetchCurrencies()` - Fetch all currencies
- `fetchTime()` - Fetch exchange server time
- `fetchStatus()` - Fetch exchange status

### Precision & Market Helpers (synchronous, no network)

- `market(symbol)` - Market structure: `precision`, `limits` (`amount.min`, `cost.min`, ...), `contractSize`, `type`, ...
- `amountToPrecision(symbol, amount)` - Round an amount to the market's step (returns a string)
- `priceToPrecision(symbol, price)` - Round a price to the market's tick (returns a string)
- `costToPrecision(symbol, cost)` - Round a cost
- `currencyToPrecision(code, fee)` - Round a currency amount (e.g. a fee)
- `milliseconds()` / `iso8601(ts)` / `parse8601(str)` - Time helpers
- `setSandboxMode(true)` - Switch to the exchange's testnet (call right after construction)

### WebSocket Methods (ccxt.pro)

Most market-data and account methods have a `watch*` equivalent; each returns the next update when awaited, so call it in a loop. Every `watch*` subscription has a matching `unWatch*` to unsubscribe without closing the whole connection.

#### Real-time Market Data
- `watchTicker(symbol)` / `watchTickers([symbols])` - Ticker updates
- `watchOrderBook(symbol, limit)` / `watchOrderBookForSymbols([symbols], limit)` - Order book updates
- `watchTrades(symbol, since, limit)` / `watchTradesForSymbols([symbols], since, limit)` - Public trades
- `watchOHLCV(symbol, timeframe, since, limit)` / `watchOHLCVForSymbols([[symbol, timeframe]], since, limit)` - Candles
- `watchBidsAsks([symbols])` - Best bid/ask
- `watchMarkPrice(symbol)` / `watchMarkPrices([symbols])` - Mark price (derivatives)
- `watchFundingRate(symbol)` / `watchFundingRates([symbols])` - Funding rate (derivatives)
- `watchLiquidations(symbol, since, limit)` / `watchLiquidationsForSymbols([symbols], since, limit)` - Public liquidations

#### Real-time Account Data (Auth Required)
- `watchBalance()` - Balance updates
- `watchOrders(symbol, since, limit)` / `watchOrdersForSymbols([symbols], since, limit)` - Your order updates
- `watchMyTrades(symbol, since, limit)` / `watchMyTradesForSymbols([symbols], since, limit)` - Your fills
- `watchPositions([symbols], since, limit)` - Position updates
- `watchPosition(symbol)` - One position
- `watchMyLiquidations(symbol, since, limit)` - Your liquidations

#### Unsubscribing
- `unWatchTicker(symbol)`, `unWatchTickers([symbols])`, `unWatchOrderBook(symbol)`, `unWatchOrderBookForSymbols([symbols])`, `unWatchTrades(symbol)`, `unWatchTradesForSymbols([symbols])`, `unWatchOHLCV(symbol, timeframe)`, `unWatchOHLCVForSymbols([[symbol, timeframe]])`, `unWatchBidsAsks([symbols])`, `unWatchMarkPrice(symbol)`, `unWatchMarkPrices([symbols])`, `unWatchFundingRate(symbol)`, `unWatchFundingRates([symbols])`, `unWatchOrders(symbol)`, `unWatchMyTrades(symbol)`, `unWatchPositions([symbols])`
- Check support first: `exchange.has['unWatchTicker']`. Use `close()` to drop every subscription and the socket.

#### Trading over WebSocket (lower latency, where supported)
- `createOrderWs(symbol, type, side, amount, price)`, `editOrderWs(id, symbol, type, side, amount, price)`, `cancelOrderWs(id, symbol)`, `cancelOrdersWs([ids], symbol)`, `cancelAllOrdersWs(symbol)`, `fetchOrderBookWs(symbol, limit)`

### Authentication Required

Methods marked with 🔒 require API credentials:

- All `create*` methods (creating orders, addresses)
- All `cancel*` methods (canceling orders)
- All `edit*` methods (modifying orders)
- All `fetchMy*` methods (your trades, orders)
- `fetchBalance`, `fetchLedger`, `fetchAccounts`
- `withdraw`, `transfer`
- Margin/leverage methods
- Position methods
- `watchBalance`, `watchOrders`, `watchMyTrades`, `watchPositions`

### 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

- `fetch*` - REST API methods (HTTP requests)
- `watch*` - WebSocket methods (real-time streams)
- `create*` - Create new resources (orders, addresses)
- `cancel*` - Cancel existing resources
- `edit*` - Modify existing resources
- `set*` - Configure settings (leverage, margin mode)
- `*Ws` suffix - WebSocket variant (some exchanges)



## 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 proxy
```

### Testing 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 `*Ws` suffix:

### Trading via WebSocket

**Creating Orders:**
- `createOrderWs` - Create order via WebSocket (faster than REST)
- `createLimitOrderWs` - Create limit order via WebSocket
- `createMarketOrderWs` - Create market order via WebSocket
- `createLimitBuyOrderWs` - Buy limit order via WebSocket
- `createLimitSellOrderWs` - Sell limit order via WebSocket
- `createMarketBuyOrderWs` - Buy market order via WebSocket
- `createMarketSellOrderWs` - Sell market order via WebSocket
- `createStopLimitOrderWs` - Stop-limit order via WebSocket
- `createStopMarketOrderWs` - Stop-market order via WebSocket
- `createStopLossOrderWs` - Stop-loss order via WebSocket
- `createTakeProfitOrderWs` - Take-profit order via WebSocket
- `createTrailingAmountOrderWs` - Trailing stop via WebSocket
- `createTrailingPercentOrderWs` - Trailing stop % via WebSocket
- `createPostOnlyOrderWs` - Post-only order via WebSocket
- `createReduceOnlyOrderWs` - Reduce-only order via WebSocket

**Managing Orders:**
- `editOrderWs` - Edit order via WebSocket
- `cancelOrderWs` - Cancel order via WebSocket (faster than REST)
- `cancelOrdersWs` - Cancel multiple orders via WebSocket
- `cancelAllOrdersWs` - Cancel all orders via WebSocket

**Fetching Data:**
- `fetchOrderWs` - Fetch order via WebSocket
- `fetchOrdersWs` - Fetch orders via WebSocket
- `fetchOpenOrdersWs` - Fetch open orders via WebSocket
- `fetchClosedOrdersWs` - Fetch closed orders via WebSocket
- `fetchMyTradesWs` - Fetch your trades via WebSocket
- `fetchBalanceWs` - Fetch balance via WebSocket
- `fetchPositionWs` - Fetch position via WebSocket
- `fetchPositionsWs` - Fetch positions via WebSocket
- `fetchPositionsForSymbolWs` - Fetch positions for symbol via WebSocket
- `fetchTradingFeesWs` - Fetch trading fees via WebSocket

### When to Use WebSocket Methods

**Use `*Ws` methods when:**
- 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 ccxt;

// During instantiation (recommended)
var exchange = new Binance(new Dictionary<string, object>
{
    { "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
   └─ NotSupported
```

### Basic 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($...

© ccxt · MIT · ccxt/ccxt

Похожие скиллы

Все скиллы по теме «Финансы и бизнес» →
csharp-testing affaan-m Скилл csharp-testing для написания и разбора тестов на C# и .NET: xUnit, FluentAssertions, моки, интеграционные тесты. CX Codex +1 6 200установок csharp-developer https://github.com/Jeffallan Скилл csharp-developer настраивает правила разработки на .NET 8 и C# 12 для создания API, Blazor-приложений и работы с EF Core. Пригодится при проектировании сервисов с CQRS и Result pattern. CX Codex +1 5 200установок modern-csharp codewithmukesh Скилл modern-csharp для Claude Code подсказывает агенту синтаксис C# 14: первичные конструкторы, коллекционные выражения, field и блоки расширений. Помогает писать новый код и чистить старый. CX Codex +1 4 100установок csharp-refactoring dotnet Скилл csharp-refactoring для Claude Code, Codex, Cursor, GitHub Copilot и Gemini CLI, который рефакторит C#/.NET-код без изменения поведения. Переименовывает, выносит, вливает и дедуплицирует по биндингам — не по тексту. CX Codex +1 3 000установок modern-csharp-coding-standards Aaronontheweb Скилл modern-csharp-coding-standards задаёт правила современного C# 12+: неизменяемые рекорды, pattern matching, структуры Span<T> и асинхронный код без лишних аллокаций памяти. CX Codex +1 2 300установок csharp-expert dotnet Скилл csharp-expert для Claude Code, Codex, Cursor и других агентов, который направляет C# и .NET запросы к нужному специалисту или находит плагин в маркетплейсе dotnet/skills. CX Codex +1 2 200установок

Из того же набора9

ccxt-python Скилл ccxt-python для Claude Code интегрирует криптовалютную библиотеку CCXT для работы с REST и WebSocket API бирж на Python. Применяется в ботах для торговли и скриптах анализа данных. CX Codex +1 2 400установок ccxt-typescript Скилл ccxt-typescript для Claude Code интегрирует библиотеку CCXT для работы с криптовалютными биржами в проекты на TypeScript и JavaScript. CX Codex +1 985установок ccxt-cli Скилл ccxt-cli учит агента работать с криптовалютными биржами через утилиту ccxt: запрашивать тикеры, свечи, баланс и выставлять ордера прямо из терминала. CX Codex +1 739установок new-exchange Скилл new-exchange создаёт скелет интеграции новой криптобиржи в библиотеку CCXT на TypeScript по шаблону сертифицированных бирж. CX Codex +1 134установок ccxt-java Скилл ccxt-java для Claude Code помогает подключать криптобиржи к Java-проектам через CCXT. Он охватывает REST-запросы и WebSocket-потоки для рыночных данных и ордеров. CX Codex +1 106установок ccxt-go Скилл ccxt-go для Claude Code помогает интегрировать криптовалютные биржи в Go-проекты через REST и WebSocket. Включается при разработке торговых систем, ботов и микросервисов. CX Codex +1 ★ 44 950звёзд репо ccxt-php Скилл ccxt-php для Claude Code помогает подключить криптобиржи к PHP-проекту через CCXT. Он включается при работе с рыночными данными, ордерами и потоками котировок. CX Codex +1 ★ 44 950звёзд репо CCXT Подключает агентов к криптобиржам и рынкам предсказаний через библиотеку CCXT. Позволяет запрашивать котировки, проверять баланс и управлять ордерами. CX Codex +1 ★ 44 950звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой