0
# CCXT - Cryptocurrency Trading Library
1
2
CCXT is a comprehensive cryptocurrency trading library that provides a unified API for accessing over 100 cryptocurrency exchanges. It enables developers to access market data, manage portfolios, execute trades, and handle account operations across multiple exchanges using a consistent interface. The library supports both REST API calls for standard operations and WebSocket connections for real-time data streaming.
3
4
## Package Information
5
6
- **Package Name**: @iam4x/ccxt
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install @iam4x/ccxt`
10
11
## Core Imports
12
13
```typescript
14
import ccxt from '@iam4x/ccxt';
15
```
16
17
For CommonJS:
18
19
```javascript
20
const ccxt = require('@iam4x/ccxt');
21
```
22
23
For specific exchanges and utilities:
24
25
```typescript
26
import ccxt, { binance, Exchange, NetworkError } from '@iam4x/ccxt';
27
```
28
29
## Basic Usage
30
31
```typescript
32
import ccxt from '@iam4x/ccxt';
33
34
// Create exchange instance
35
const exchange = new ccxt.binance({
36
apiKey: 'your-api-key',
37
secret: 'your-secret',
38
sandbox: true, // Enable sandbox mode for testing
39
});
40
41
// Fetch market data
42
const ticker = await exchange.fetchTicker('BTC/USDT');
43
const orderbook = await exchange.fetchOrderBook('BTC/USDT');
44
const trades = await exchange.fetchTrades('BTC/USDT');
45
46
// Account operations (requires API credentials)
47
const balance = await exchange.fetchBalance();
48
const order = await exchange.createLimitBuyOrder('BTC/USDT', 0.001, 50000);
49
50
// Handle errors
51
try {
52
const result = await exchange.fetchBalance();
53
} catch (error) {
54
if (error instanceof ccxt.NetworkError) {
55
console.log('Network error:', error.message);
56
} else if (error instanceof ccxt.ExchangeError) {
57
console.log('Exchange error:', error.message);
58
}
59
}
60
```
61
62
## Architecture
63
64
CCXT is built around several key components:
65
66
- **Exchange Classes**: Individual classes for each supported exchange, all extending the base Exchange class
67
- **Unified API**: Consistent method signatures and return formats across all exchanges
68
- **Error Handling**: Comprehensive error hierarchy for different types of failures
69
- **Type Safety**: Full TypeScript support with detailed type definitions
70
- **Rate Limiting**: Built-in rate limiting and request throttling
71
- **WebSocket Support**: Real-time data streaming through the Pro module
72
- **Multi-Language**: Available for JavaScript, Python, PHP, and C#
73
74
## Capabilities
75
76
### Exchange Management
77
78
Core functionality for creating and configuring exchange instances, with support for 100+ cryptocurrency exchanges including major ones like Binance, Coinbase, Kraken, and OKX.
79
80
```typescript { .api }
81
// Individual exchange classes (100+ available)
82
class binance extends Exchange { }
83
class coinbase extends Exchange { }
84
class kraken extends Exchange { }
85
class okx extends Exchange { }
86
// ... and 96+ more exchanges
87
88
// Exchange constructor options
89
interface ExchangeOptions {
90
apiKey?: string;
91
secret?: string;
92
password?: string;
93
uid?: string;
94
login?: string;
95
privateKey?: string;
96
walletAddress?: string;
97
token?: string;
98
sandbox?: boolean;
99
timeout?: number;
100
rateLimit?: number;
101
enableRateLimit?: boolean;
102
userAgent?: string;
103
headers?: { [key: string]: string };
104
proxy?: string;
105
httpsProxy?: string;
106
socksProxy?: string;
107
}
108
```
109
110
[Exchange Management](./exchange-management.md)
111
112
### Market Data
113
114
Comprehensive market data access including tickers, order books, trade history, OHLCV candlestick data, and market information across all supported exchanges.
115
116
```typescript { .api }
117
// Market data methods
118
fetchMarkets(params?: Dict): Promise<Market[]>;
119
fetchTicker(symbol: string, params?: Dict): Promise<Ticker>;
120
fetchTickers(symbols?: string[], params?: Dict): Promise<Tickers>;
121
fetchOrderBook(symbol: string, limit?: number, params?: Dict): Promise<OrderBook>;
122
fetchOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: Dict): Promise<OHLCV[]>;
123
fetchTrades(symbol: string, since?: number, limit?: number, params?: Dict): Promise<Trade[]>;
124
125
// Market data structures
126
interface Market {
127
id: string;
128
symbol: string;
129
base: string;
130
quote: string;
131
active: boolean;
132
type: 'spot' | 'margin' | 'swap' | 'future' | 'option';
133
spot: boolean;
134
margin: boolean;
135
swap: boolean;
136
future: boolean;
137
option: boolean;
138
contract: boolean;
139
contractSize?: number;
140
expiry?: number;
141
strike?: number;
142
precision: {
143
amount: number;
144
price: number;
145
};
146
limits: {
147
amount?: { min: number; max: number };
148
price?: { min: number; max: number };
149
cost?: { min: number; max: number };
150
};
151
info: any;
152
}
153
154
interface Ticker {
155
symbol: string;
156
timestamp: number;
157
datetime: string;
158
high: number;
159
low: number;
160
bid: number;
161
bidVolume?: number;
162
ask: number;
163
askVolume?: number;
164
vwap?: number;
165
open: number;
166
close: number;
167
last: number;
168
previousClose?: number;
169
change?: number;
170
percentage?: number;
171
average?: number;
172
baseVolume: number;
173
quoteVolume: number;
174
info: any;
175
}
176
```
177
178
[Market Data](./market-data.md)
179
180
### Account Management
181
182
Account operations including balance retrieval, account information, deposit addresses, withdrawal management, and multi-account support for exchanges that offer sub-accounts.
183
184
```typescript { .api }
185
fetchBalance(params?: Dict): Promise<Balances>;
186
fetchAccounts(params?: Dict): Promise<Account[]>;
187
fetchPositions(symbols?: string[], params?: Dict): Promise<Position[]>;
188
fetchLedger(code?: string, since?: number, limit?: number, params?: Dict): Promise<LedgerEntry[]>;
189
createDepositAddress(code: string, params?: Dict): Promise<DepositAddress>;
190
fetchDepositAddress(code: string, params?: Dict): Promise<DepositAddress>;
191
fetchDeposits(code?: string, since?: number, limit?: number, params?: Dict): Promise<Transaction[]>;
192
fetchWithdrawals(code?: string, since?: number, limit?: number, params?: Dict): Promise<Transaction[]>;
193
194
interface Balances {
195
[currency: string]: {
196
free: number;
197
used: number;
198
total: number;
199
};
200
info: any;
201
}
202
203
interface Position {
204
id?: string;
205
symbol: string;
206
side: 'long' | 'short';
207
amount: number;
208
contracts?: number;
209
contractSize?: number;
210
unrealizedPnl?: number;
211
percentage?: number;
212
timestamp?: number;
213
info: any;
214
}
215
```
216
217
[Account Management](./account-management.md)
218
219
### Order Management
220
221
Complete order lifecycle management including creation, modification, cancellation, and monitoring of different order types across spot, margin, and derivatives trading.
222
223
```typescript { .api }
224
createOrder(symbol: string, type: OrderType, side: OrderSide, amount: number, price?: number, params?: Dict): Promise<Order>;
225
createLimitBuyOrder(symbol: string, amount: number, price: number, params?: Dict): Promise<Order>;
226
createLimitSellOrder(symbol: string, amount: number, price: number, params?: Dict): Promise<Order>;
227
createMarketBuyOrder(symbol: string, amount: number, price?: number, params?: Dict): Promise<Order>;
228
createMarketSellOrder(symbol: string, amount: number, price?: number, params?: Dict): Promise<Order>;
229
createStopOrder(symbol: string, side: OrderSide, amount: number, price: number, stopPrice: number, params?: Dict): Promise<Order>;
230
editOrder(id: string, symbol: string, type: OrderType, side: OrderSide, amount?: number, price?: number, params?: Dict): Promise<Order>;
231
cancelOrder(id: string, symbol?: string, params?: Dict): Promise<Order>;
232
cancelAllOrders(symbol?: string, params?: Dict): Promise<Order[]>;
233
fetchOrder(id: string, symbol?: string, params?: Dict): Promise<Order>;
234
fetchOrders(symbol?: string, since?: number, limit?: number, params?: Dict): Promise<Order[]>;
235
fetchOpenOrders(symbol?: string, since?: number, limit?: number, params?: Dict): Promise<Order[]>;
236
fetchClosedOrders(symbol?: string, since?: number, limit?: number, params?: Dict): Promise<Order[]>;
237
238
type OrderType = 'limit' | 'market' | 'stop' | 'stop_limit' | 'trailing_stop';
239
type OrderSide = 'buy' | 'sell';
240
241
interface Order {
242
id: string;
243
clientOrderId?: string;
244
timestamp: number;
245
datetime: string;
246
lastTradeTimestamp?: number;
247
symbol: string;
248
type: OrderType;
249
side: OrderSide;
250
amount: number;
251
price?: number;
252
stopPrice?: number;
253
filled: number;
254
remaining: number;
255
cost: number;
256
trades?: Trade[];
257
fee?: {
258
currency: string;
259
cost: number;
260
rate?: number;
261
};
262
status: 'open' | 'closed' | 'canceled' | 'expired' | 'rejected';
263
info: any;
264
}
265
```
266
267
[Order Management](./order-management.md)
268
269
### Trading Operations
270
271
Trading execution and history including trade fetching, order-trade relationships, and portfolio management operations for active trading workflows.
272
273
```typescript { .api }
274
fetchMyTrades(symbol?: string, since?: number, limit?: number, params?: Dict): Promise<Trade[]>;
275
fetchOrderTrades(id: string, symbol?: string, since?: number, limit?: number, params?: Dict): Promise<Trade[]>;
276
277
interface Trade {
278
id: string;
279
order?: string;
280
timestamp: number;
281
datetime: string;
282
symbol: string;
283
type?: OrderType;
284
side: OrderSide;
285
amount: number;
286
price: number;
287
cost: number;
288
fee?: {
289
currency: string;
290
cost: number;
291
rate?: number;
292
};
293
info: any;
294
}
295
```
296
297
[Trading Operations](./trading-operations.md)
298
299
### Funding Operations
300
301
Comprehensive funding management including deposits, withdrawals, internal transfers, and address management for moving funds between exchanges and external wallets.
302
303
```typescript { .api }
304
withdraw(code: string, amount: number, address: string, tag?: string, params?: Dict): Promise<WithdrawalResponse>;
305
transfer(code: string, amount: number, fromAccount: string, toAccount: string, params?: Dict): Promise<TransferEntry>;
306
307
interface WithdrawalResponse {
308
id: string;
309
txid?: string;
310
timestamp: number;
311
datetime: string;
312
currency: string;
313
amount: number;
314
address: string;
315
tag?: string;
316
status: 'pending' | 'ok' | 'failed' | 'canceled';
317
fee?: {
318
currency: string;
319
cost: number;
320
};
321
info: any;
322
}
323
324
interface DepositAddress {
325
currency: string;
326
address: string;
327
tag?: string;
328
network?: string;
329
info: any;
330
}
331
```
332
333
[Funding Operations](./funding-operations.md)
334
335
### WebSocket Operations
336
337
Real-time data streaming capabilities for live market data, order updates, balance changes, and position monitoring through WebSocket connections.
338
339
```typescript { .api }
340
// WebSocket methods (available on pro exchanges)
341
watchTicker(symbol: string, params?: Dict): Promise<Ticker>;
342
watchOrderBook(symbol: string, limit?: number, params?: Dict): Promise<OrderBook>;
343
watchOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: Dict): Promise<OHLCV[]>;
344
watchTrades(symbol: string, since?: number, limit?: number, params?: Dict): Promise<Trade[]>;
345
watchOrders(symbol?: string, since?: number, limit?: number, params?: Dict): Promise<Order[]>;
346
watchBalance(params?: Dict): Promise<Balances>;
347
watchPositions(symbols?: string[], since?: number, limit?: number, params?: Dict): Promise<Position[]>;
348
349
```
350
351
[WebSocket Operations](./websocket-operations.md)
352
353
### Utility Functions
354
355
Comprehensive utility functions for cryptocurrency operations including mathematical precision, cryptographic operations, time handling, and data manipulation.
356
357
```typescript { .api }
358
// Precision arithmetic
359
class Precise {
360
constructor(number: string | number);
361
toString(): string;
362
static stringAdd(a: string, b: string): string;
363
static stringMul(a: string, b: string): string;
364
static stringDiv(a: string, b: string): string;
365
static stringSub(a: string, b: string): string;
366
}
367
368
// Time functions
369
function iso8601(timestamp?: number): string;
370
function parse8601(timestamp: string): number;
371
function seconds(): number;
372
function milliseconds(): number;
373
function now(): number;
374
375
// Cryptographic functions
376
function hash(request: string | Uint8Array, algorithm: string): string;
377
function hmac(request: string | Uint8Array, secret: string | Uint8Array, algorithm: string): string;
378
function ecdsa(request: string, secret: string, algorithm: string): string;
379
380
// Encoding functions
381
function base64ToBinary(str: string): Uint8Array;
382
function binaryToBase64(bytes: Uint8Array): string;
383
function urlencode(params: Dict): string;
384
```
385
386
[Utility Functions](./utility-functions.md)
387
388
### Error Handling
389
390
Comprehensive error hierarchy providing specific exception types for different failure scenarios, enabling precise error handling and recovery strategies.
391
392
```typescript { .api }
393
// Base error classes
394
class BaseError extends Error { }
395
class ExchangeError extends BaseError { }
396
class OperationFailed extends BaseError { }
397
398
// Authentication errors
399
class AuthenticationError extends ExchangeError { }
400
class PermissionDenied extends ExchangeError { }
401
class AccountNotEnabled extends ExchangeError { }
402
class AccountSuspended extends ExchangeError { }
403
404
// Request errors
405
class ArgumentsRequired extends ExchangeError { }
406
class BadRequest extends ExchangeError { }
407
class BadSymbol extends BadRequest { }
408
class InvalidAddress extends ExchangeError { }
409
410
// Order errors
411
class InvalidOrder extends ExchangeError { }
412
class OrderNotFound extends ExchangeError { }
413
class OrderNotCached extends ExchangeError { }
414
class InsufficientFunds extends ExchangeError { }
415
416
// Network errors
417
class NetworkError extends BaseError { }
418
class DDoSProtection extends NetworkError { }
419
class RateLimitExceeded extends NetworkError { }
420
class ExchangeNotAvailable extends NetworkError { }
421
class RequestTimeout extends NetworkError { }
422
423
// Response errors
424
class BadResponse extends ExchangeError { }
425
class NullResponse extends BadResponse { }
426
```
427
428
[Error Handling](./error-handling.md)
429
430
## Types
431
432
```typescript { .api }
433
// Core data types
434
type Dict = { [key: string]: any };
435
type Strings = string[] | undefined;
436
type OrderBook = {
437
symbol: string;
438
bids: [number, number][];
439
asks: [number, number][];
440
timestamp: number;
441
datetime: string;
442
nonce?: number;
443
};
444
445
type OHLCV = [number, number, number, number, number, number]; // [timestamp, open, high, low, close, volume]
446
447
// Exchange capabilities
448
interface ExchangeCapabilities {
449
CORS?: boolean;
450
spot?: boolean;
451
margin?: boolean;
452
swap?: boolean;
453
future?: boolean;
454
option?: boolean;
455
addMargin?: boolean;
456
cancelAllOrders?: boolean;
457
cancelOrder?: boolean;
458
cancelOrders?: boolean;
459
createDepositAddress?: boolean;
460
createLimitOrder?: boolean;
461
createMarketOrder?: boolean;
462
createOrder?: boolean;
463
deposit?: boolean;
464
editOrder?: boolean;
465
fetchBalance?: boolean;
466
fetchClosedOrders?: boolean;
467
fetchCurrencies?: boolean;
468
fetchDepositAddress?: boolean;
469
fetchDeposits?: boolean;
470
fetchMarkets?: boolean;
471
fetchMyTrades?: boolean;
472
fetchOHLCV?: boolean;
473
fetchOpenOrders?: boolean;
474
fetchOrder?: boolean;
475
fetchOrderBook?: boolean;
476
fetchOrders?: boolean;
477
fetchStatus?: boolean;
478
fetchTicker?: boolean;
479
fetchTickers?: boolean;
480
fetchTime?: boolean;
481
fetchTrades?: boolean;
482
fetchTradingFee?: boolean;
483
fetchTradingFees?: boolean;
484
fetchWithdrawals?: boolean;
485
reduceMargin?: boolean;
486
setLeverage?: boolean;
487
setMargin?: boolean;
488
setMarginMode?: boolean;
489
setPositionMode?: boolean;
490
signIn?: boolean;
491
withdraw?: boolean;
492
}
493
```