ccxt-typescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCCXT for TypeScript/JavaScript
面向TypeScript/JavaScript的CCXT库
A comprehensive guide to using CCXT in TypeScript and JavaScript projects for cryptocurrency exchange integration.
一份关于在TypeScript和JavaScript项目中使用CCXT对接加密货币交易所的全面指南。
Installation
安装
REST API (Standard CCXT)
REST API(标准CCXT)
bash
npm install ccxtbash
npm install ccxtWebSocket API (Real-time, ccxt.pro)
WebSocket API(实时版,ccxt.pro)
bash
npm install ccxtBoth REST and WebSocket APIs are included in the same package.
bash
npm install ccxtREST和WebSocket API已包含在同一个包中。
Quick Start
快速开始
REST API - TypeScript
REST API - TypeScript示例
typescript
import ccxt from 'ccxt'
const exchange = new ccxt.binance()
await exchange.loadMarkets()
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker)typescript
import ccxt from 'ccxt'
const exchange = new ccxt.binance()
await exchange.loadMarkets()
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker)REST API - JavaScript (CommonJS)
REST API - JavaScript(CommonJS)示例
javascript
const ccxt = require('ccxt')
(async () => {
const exchange = new ccxt.binance()
await exchange.loadMarkets()
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker)
})()javascript
const ccxt = require('ccxt')
(async () => {
const exchange = new ccxt.binance()
await exchange.loadMarkets()
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker)
})()WebSocket API - Real-time Updates
WebSocket API - 实时更新示例
typescript
import ccxt from 'ccxt'
const exchange = new ccxt.pro.binance()
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT')
console.log(ticker) // Live updates!
}
await exchange.close()typescript
import ccxt from 'ccxt'
const exchange = new ccxt.pro.binance()
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT')
console.log(ticker) // 实时更新!
}
await exchange.close()REST vs WebSocket
REST与WebSocket对比
| Feature | REST API | WebSocket API |
|---|---|---|
| Use for | One-time queries, placing orders | Real-time monitoring, live price feeds |
| Method prefix | | |
| Speed | Slower (HTTP request/response) | Faster (persistent connection) |
| Rate limits | Strict (1-2 req/sec) | More lenient (continuous stream) |
| Import | | |
| Best for | Trading, account management | Price monitoring, arbitrage detection |
When to use REST:
- Placing orders
- Fetching account balance
- One-time data queries
- Order management (cancel, fetch orders)
When to use WebSocket:
- Real-time price monitoring
- Live orderbook updates
- Arbitrage detection
- Portfolio tracking with live updates
| 特性 | REST API | WebSocket API |
|---|---|---|
| 适用场景 | 一次性查询、下单 | 实时监控、实时价格推送 |
| 方法前缀 | | |
| 速度 | 较慢(HTTP请求/响应模式) | 更快(长连接模式) |
| 请求限制 | 严格(1-2次请求/秒) | 更宽松(持续数据流) |
| 导入方式 | | |
| 最佳用途 | 交易操作、账户管理 | 价格监控、套利检测 |
何时使用REST:
- 下单操作
- 查询账户余额
- 一次性数据查询
- 订单管理(取消、查询订单)
何时使用WebSocket:
- 实时价格监控
- 订单簿实时更新
- 套利机会检测
- 投资组合实时追踪
Creating Exchange Instance
创建交易所实例
REST API
REST API
typescript
// Public API (no authentication)
const exchange = new ccxt.binance({
enableRateLimit: true // Recommended!
})
// Private API (with authentication)
const exchange = new ccxt.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET',
enableRateLimit: true
})typescript
// 公开API(无需身份验证)
const exchange = new ccxt.binance({
enableRateLimit: true // 推荐启用!
})
// 私有API(需身份验证)
const exchange = new ccxt.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET',
enableRateLimit: true
})WebSocket API
WebSocket API
typescript
// Public WebSocket
const exchange = new ccxt.pro.binance()
// Private WebSocket (with authentication)
const exchange = new ccxt.pro.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET'
})
// Always close when done
await exchange.close()typescript
// 公开WebSocket
const exchange = new ccxt.pro.binance()
// 私有WebSocket(需身份验证)
const exchange = new ccxt.pro.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET'
})
// 使用完成后务必关闭连接
await exchange.close()Common REST Operations
常见REST操作
Loading Markets
加载交易市场
typescript
// Load all available trading pairs
await exchange.loadMarkets()
// Access market information
const btcMarket = exchange.market('BTC/USDT')
console.log(btcMarket.limits.amount.min) // Minimum order amounttypescript
// 加载所有可用交易对
await exchange.loadMarkets()
// 访问交易市场信息
const btcMarket = exchange.market('BTC/USDT')
console.log(btcMarket.limits.amount.min) // 最小下单量Fetching Ticker
获取行情数据
typescript
// Single ticker
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker.last) // Last price
console.log(ticker.bid) // Best bid
console.log(ticker.ask) // Best ask
console.log(ticker.volume) // 24h volume
// Multiple tickers (if supported)
const tickers = await exchange.fetchTickers(['BTC/USDT', 'ETH/USDT'])typescript
// 单个交易对行情
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker.last) // 最新成交价
console.log(ticker.bid) // 最优买价
console.log(ticker.ask) // 最优卖价
console.log(ticker.volume) // 24小时成交量
// 多个交易对行情(若交易所支持)
const tickers = await exchange.fetchTickers(['BTC/USDT', 'ETH/USDT'])Fetching Order Book
获取订单簿
typescript
// Full orderbook
const orderbook = await exchange.fetchOrderBook('BTC/USDT')
console.log(orderbook.bids[0]) // [price, amount]
console.log(orderbook.asks[0]) // [price, amount]
// Limited depth
const orderbook = await exchange.fetchOrderBook('BTC/USDT', 5) // Top 5 levelstypescript
// 完整订单簿
const orderbook = await exchange.fetchOrderBook('BTC/USDT')
console.log(orderbook.bids[0]) // [价格, 数量]
console.log(orderbook.asks[0]) // [价格, 数量]
// 限定深度的订单簿
const orderbook = await exchange.fetchOrderBook('BTC/USDT', 5) // 前5档数据Creating Orders
创建订单
Limit Order
限价单
typescript
// Buy limit order
const order = await exchange.createLimitBuyOrder('BTC/USDT', 0.01, 50000)
console.log(order.id)
// Sell limit order
const order = await exchange.createLimitSellOrder('BTC/USDT', 0.01, 60000)
// Generic limit order
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)typescript
// 买入限价单
const order = await exchange.createLimitBuyOrder('BTC/USDT', 0.01, 50000)
console.log(order.id)
// 卖出限价单
const order = await exchange.createLimitSellOrder('BTC/USDT', 0.01, 60000)
// 通用限价单
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)Market Order
市价单
typescript
// Buy market order
const order = await exchange.createMarketBuyOrder('BTC/USDT', 0.01)
// Sell market order
const order = await exchange.createMarketSellOrder('BTC/USDT', 0.01)
// Generic market order
const order = await exchange.createOrder('BTC/USDT', 'market', 'sell', 0.01)typescript
// 买入市价单
const order = await exchange.createMarketBuyOrder('BTC/USDT', 0.01)
// 卖出市价单
const order = await exchange.createMarketSellOrder('BTC/USDT', 0.01)
// 通用市价单
const order = await exchange.createOrder('BTC/USDT', 'market', 'sell', 0.01)Fetching Balance
获取账户余额
typescript
const balance = await exchange.fetchBalance()
console.log(balance.BTC.free) // Available balance
console.log(balance.BTC.used) // Balance in orders
console.log(balance.BTC.total) // Total balancetypescript
const balance = await exchange.fetchBalance()
console.log(balance.BTC.free) // 可用余额
console.log(balance.BTC.used) // 订单占用余额
console.log(balance.BTC.total) // 总余额Fetching Orders
查询订单
typescript
// Open orders
const openOrders = await exchange.fetchOpenOrders('BTC/USDT')
// Closed orders
const closedOrders = await exchange.fetchClosedOrders('BTC/USDT')
// All orders (open + closed)
const allOrders = await exchange.fetchOrders('BTC/USDT')
// Single order by ID
const order = await exchange.fetchOrder(orderId, 'BTC/USDT')typescript
// 未成交订单
const openOrders = await exchange.fetchOpenOrders('BTC/USDT')
// 已成交订单
const closedOrders = await exchange.fetchClosedOrders('BTC/USDT')
// 所有订单(未成交+已成交)
const allOrders = await exchange.fetchOrders('BTC/USDT')
// 通过订单ID查询单个订单
const order = await exchange.fetchOrder(orderId, 'BTC/USDT')Fetching Trades
查询交易记录
typescript
// Recent public trades
const trades = await exchange.fetchTrades('BTC/USDT', undefined, 10)
// Your trades (requires authentication)
const myTrades = await exchange.fetchMyTrades('BTC/USDT')typescript
// 最新公开交易记录
const trades = await exchange.fetchTrades('BTC/USDT', undefined, 10)
// 个人交易记录(需身份验证)
const myTrades = await exchange.fetchMyTrades('BTC/USDT')Canceling Orders
取消订单
typescript
// Cancel single order
await exchange.cancelOrder(orderId, 'BTC/USDT')
// Cancel all orders for a symbol
await exchange.cancelAllOrders('BTC/USDT')typescript
// 取消单个订单
await exchange.cancelOrder(orderId, 'BTC/USDT')
// 取消某个交易对的所有订单
await exchange.cancelAllOrders('BTC/USDT')WebSocket Operations (Real-time)
WebSocket实时操作
Watching Ticker (Live Price Updates)
监控行情(实时价格更新)
typescript
const exchange = new ccxt.pro.binance()
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT')
console.log(ticker.last, ticker.timestamp)
}
await exchange.close()typescript
const exchange = new ccxt.pro.binance()
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT')
console.log(ticker.last, ticker.timestamp)
}
await exchange.close()Watching Order Book (Live Depth Updates)
监控订单簿(实时深度更新)
typescript
const exchange = new ccxt.pro.binance()
while (true) {
const orderbook = await exchange.watchOrderBook('BTC/USDT')
console.log('Best bid:', orderbook.bids[0])
console.log('Best ask:', orderbook.asks[0])
}
await exchange.close()typescript
const exchange = new ccxt.pro.binance()
while (true) {
const orderbook = await exchange.watchOrderBook('BTC/USDT')
console.log('最优买价:', orderbook.bids[0])
console.log('最优卖价:', orderbook.asks[0])
}
await exchange.close()Watching Trades (Live Trade Stream)
监控交易记录(实时交易流)
typescript
const exchange = new ccxt.pro.binance()
while (true) {
const trades = await exchange.watchTrades('BTC/USDT')
for (const trade of trades) {
console.log(trade.price, trade.amount, trade.side)
}
}
await exchange.close()typescript
const exchange = new ccxt.pro.binance()
while (true) {
const trades = await exchange.watchTrades('BTC/USDT')
for (const trade of trades) {
console.log(trade.price, trade.amount, trade.side)
}
}
await exchange.close()Watching Your Orders (Live Order Updates)
监控个人订单(实时订单更新)
typescript
const exchange = new ccxt.pro.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET'
})
while (true) {
const orders = await exchange.watchOrders('BTC/USDT')
for (const order of orders) {
console.log(order.id, order.status, order.filled)
}
}
await exchange.close()typescript
const exchange = new ccxt.pro.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET'
})
while (true) {
const orders = await exchange.watchOrders('BTC/USDT')
for (const order of orders) {
console.log(order.id, order.status, order.filled)
}
}
await exchange.close()Watching Balance (Live Balance Updates)
监控账户余额(实时余额更新)
typescript
const exchange = new ccxt.pro.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET'
})
while (true) {
const balance = await exchange.watchBalance()
console.log('BTC:', balance.BTC)
console.log('USDT:', balance.USDT)
}
await exchange.close()typescript
const exchange = new ccxt.pro.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET'
})
while (true) {
const balance = await exchange.watchBalance()
console.log('BTC余额:', balance.BTC)
console.log('USDT余额:', balance.USDT)
}
await exchange.close()Watching Multiple Symbols
监控多个交易对
typescript
const exchange = new ccxt.pro.binance()
const symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT']
while (true) {
// Watch all symbols concurrently
const tickers = await exchange.watchTickers(symbols)
for (const symbol in tickers) {
console.log(symbol, tickers[symbol].last)
}
}
await exchange.close()typescript
const exchange = new ccxt.pro.binance()
const symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT']
while (true) {
// 同时监控所有交易对
const tickers = await exchange.watchTickers(symbols)
for (const symbol in tickers) {
console.log(symbol, tickers[symbol].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])
- - 获取单个交易对行情
fetchTicker(symbol) - - 批量获取多个交易对行情
fetchTickers([symbols]) - - 获取多个交易对的最优买卖价
fetchBidsAsks([symbols]) - - 获取多个交易对的最新成交价
fetchLastPrices([symbols]) - - 获取多个交易对的标记价格(衍生品)
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)
- - 获取订单簿
fetchOrderBook(symbol, limit) - - 批量获取多个交易对的订单簿
fetchOrderBooks([symbols]) - - 获取Level 2订单簿
fetchL2OrderBook(symbol) - - 获取Level 3订单簿(若交易所支持)
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)
- - 获取公开交易记录
fetchTrades(symbol, since, limit) - - 获取个人交易记录(需身份验证)
fetchMyTrades(symbol, since, limit) - - 获取指定订单的交易记录
fetchOrderTrades(orderId, symbol)
OHLCV (Candlesticks)
K线数据(蜡烛图)
- - 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)
- - 获取K线数据
fetchOHLCV(symbol, timeframe, since, limit) - - 获取指数价格K线数据
fetchIndexOHLCV(symbol, timeframe) - - 获取标记价格K线数据
fetchMarkOHLCV(symbol, timeframe) - - 获取溢价指数K线数据
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)
- - 获取账户余额(需身份验证)
fetchBalance() - - 获取子账户信息
fetchAccounts() - - 获取账户流水
fetchLedger(code, since, limit) - - 获取指定流水记录
fetchLedgerEntry(id, code) - - 获取交易记录
fetchTransactions(code, since, limit) - - 获取充值记录
fetchDeposits(code, since, limit) - - 获取提现记录
fetchWithdrawals(code, since, limit) - - 同时获取充值和提现记录
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)
- - 通用创建订单方法
createOrder(symbol, type, side, amount, price, params) - - 创建限价单
createLimitOrder(symbol, side, amount, price) - - 创建市价单
createMarketOrder(symbol, side, amount) - - 创建买入限价单
createLimitBuyOrder(symbol, amount, price) - - 创建卖出限价单
createLimitSellOrder(symbol, amount, price) - - 创建买入市价单
createMarketBuyOrder(symbol, amount) - - 创建卖出市价单
createMarketSellOrder(symbol, amount) - - 按指定金额买入
createMarketBuyOrderWithCost(symbol, cost) - - 创建止损限价单
createStopLimitOrder(symbol, side, amount, price, stopPrice) - - 创建止损市价单
createStopMarketOrder(symbol, side, amount, stopPrice) - - 创建止损单
createStopLossOrder(symbol, side, amount, stopPrice) - - 创建止盈单
createTakeProfitOrder(symbol, side, amount, takeProfitPrice) - - 创建追踪止损单(固定金额)
createTrailingAmountOrder(symbol, side, amount, trailingAmount) - - 创建追踪止损单(百分比)
createTrailingPercentOrder(symbol, side, amount, trailingPercent) - - 创建触发单
createTriggerOrder(symbol, side, amount, triggerPrice) - - 创建只做市单
createPostOnlyOrder(symbol, side, amount, price) - - 创建只减仓单
createReduceOnlyOrder(symbol, side, amount, price) - - 批量创建订单
createOrders([orders]) - - 创建OCO订单(止盈止损单)
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)
- - 查询单个订单
fetchOrder(orderId, symbol) - - 查询所有订单
fetchOrders(symbol, since, limit) - - 查询未成交订单
fetchOpenOrders(symbol, since, limit) - - 查询已成交订单
fetchClosedOrders(symbol, since, limit) - - 查询已取消订单
fetchCanceledOrders(symbol, since, limit) - - 查询指定未成交订单
fetchOpenOrder(orderId, symbol) - - 按状态查询订单
fetchOrdersByStatus(status, symbol) - - 取消单个订单
cancelOrder(orderId, symbol) - - 批量取消订单
cancelOrders([orderIds], symbol) - - 取消某个交易对的所有订单
cancelAllOrders(symbol) - - 修改订单
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)
- - 获取保证金借贷利率
fetchBorrowRate(code) - - 批量获取多个币种的借贷利率
fetchBorrowRates([codes]) - - 获取借贷利率历史数据
fetchBorrowRateHistory(code, since, limit) - - 获取全仓保证金借贷利率
fetchCrossBorrowRate(code) - - 获取逐仓保证金借贷利率
fetchIsolatedBorrowRate(symbol, code) - - 借入保证金
borrowMargin(code, amount, symbol) - - 归还保证金
repayMargin(code, amount, symbol) - - 获取杠杆倍数
fetchLeverage(symbol) - - 设置杠杆倍数
setLeverage(leverage, symbol) - - 获取杠杆等级
fetchLeverageTiers(symbols) - - 获取指定交易对的杠杆等级
fetchMarketLeverageTiers(symbol) - - 设置保证金模式(全仓/逐仓)
setMarginMode(marginMode, symbol) - - 查询保证金模式
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()
- - 获取单个持仓
fetchPosition(symbol) - - 获取所有持仓
fetchPositions([symbols]) - - 获取指定交易对的持仓
fetchPositionsForSymbol(symbol) - - 获取持仓历史
fetchPositionHistory(symbol, since, limit) - - 批量获取多个交易对的持仓历史
fetchPositionsHistory(symbols, since, limit) - - 查询持仓模式(单向/双向)
fetchPositionMode(symbol) - - 设置持仓模式
setPositionMode(hedged, symbol) - - 平仓
closePosition(symbol, side) - - 全部平仓
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)
- - 获取当前资金费率
fetchFundingRate(symbol) - - 批量获取多个交易对的资金费率
fetchFundingRates([symbols]) - - 获取资金费率历史数据
fetchFundingRateHistory(symbol, since, limit) - - 获取个人资金费用记录
fetchFundingHistory(symbol, since, limit) - - 获取资金费用收取间隔
fetchFundingInterval(symbol) - - 获取结算历史
fetchSettlementHistory(symbol, since, limit) - - 获取个人结算历史
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)
- - 获取持仓量
fetchOpenInterest(symbol) - - 批量获取多个交易对的持仓量
fetchOpenInterests([symbols]) - - 获取持仓量历史数据
fetchOpenInterestHistory(symbol, timeframe, since, limit) - - 获取公开强平记录
fetchLiquidations(symbol, since, limit) - - 获取个人强平记录
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()
- - 获取期权信息
fetchOption(symbol) - - 获取期权链
fetchOptionChain(code) - - 获取期权希腊值
fetchGreeks(symbol) - - 获取波动率历史数据
fetchVolatilityHistory(code, since, limit) - - 获取标的资产
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])
- - 获取交易手续费
fetchTradingFee(symbol) - - 批量获取多个交易对的交易手续费
fetchTradingFees([symbols]) - - 获取交易限制
fetchTradingLimits([symbols]) - - 获取转账/提现手续费
fetchTransactionFee(code) - - 批量获取多个币种的转账/提现手续费
fetchTransactionFees([codes]) - - 获取充值/提现手续费
fetchDepositWithdrawFee(code) - - 批量获取多个币种的充值/提现手续费
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)
- - 获取充值地址
fetchDepositAddress(code, params) - - 批量获取多个币种的充值地址
fetchDepositAddresses([codes]) - - 获取指定币种不同网络的充值地址
fetchDepositAddressesByNetwork(code) - - 创建新的充值地址
createDepositAddress(code, params) - - 查询单个充值记录
fetchDeposit(id, code) - - 查询单个提现记录
fetchWithdrawal(id, code) - - 获取提现地址
fetchWithdrawAddresses(code) - - 获取提现白名单
fetchWithdrawalWhitelist(code) - - 提现
withdraw(code, amount, address, tag, params) - - 充值(若交易所支持)
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)
- - 内部转账
transfer(code, amount, fromAccount, toAccount) - - 查询转账记录
fetchTransfer(id, code) - - 查询转账历史
fetchTransfers(code, since, limit) - - 获取支持兑换的币种
fetchConvertCurrencies() - - 获取兑换报价
fetchConvertQuote(fromCode, toCode, amount) - - 执行兑换
createConvertTrade(fromCode, toCode, amount) - - 查询兑换记录
fetchConvertTrade(id) - - 查询兑换历史
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)
- - 获取所有交易市场
fetchMarkets() - - 获取所有币种
fetchCurrencies() - - 获取交易所服务器时间
fetchTime() - - 获取交易所状态
fetchStatus() - - 获取借贷利息记录
fetchBorrowInterest(code, symbol, since, limit) - - 获取多空比
fetchLongShortRatio(symbol, timeframe, since, limit) - - 获取多空比历史数据
fetchLongShortRatioHistory(symbol, timeframe, since, limit)
WebSocket Methods (ccxt.pro)
WebSocket方法(ccxt.pro)
All REST methods have WebSocket equivalents with prefix:
watch*所有REST方法都有对应的WebSocket方法,前缀为:
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])
- - 监控单个交易对行情
watchTicker(symbol) - - 监控多个交易对行情
watchTickers([symbols]) - - 监控订单簿更新
watchOrderBook(symbol) - - 监控多个交易对的订单簿
watchOrderBookForSymbols([symbols]) - - 监控公开交易记录
watchTrades(symbol) - - 监控K线数据更新
watchOHLCV(symbol, timeframe) - - 监控最优买卖价更新
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)
- - 监控账户余额更新
watchBalance() - - 监控个人订单更新
watchOrders(symbol) - - 监控个人交易记录更新
watchMyTrades(symbol) - - 监控持仓更新
watchPositions([symbols]) - - 监控指定交易对的持仓更新
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
标记为🔒的方法需要API凭证:
- 所有方法(创建订单、地址等)
create* - 所有方法(取消订单等)
cancel* - 所有方法(修改订单等)
edit* - 所有方法(个人交易记录、订单等)
fetchMy* - 、
fetchBalance、fetchLedgerfetchAccounts - 、
withdraw、transferdeposit - 杠杆/保证金相关方法
- 持仓相关方法
- 、
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,
// ...
// }并非所有交易所都支持全部方法,使用前请检查:
// 检查方法是否支持
if (exchange.has['fetchOHLCV']) {
const candles = await exchange.fetchOHLCV('BTC/USDT', '1h')
}
// 检查多个功能
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
- - REST API方法(HTTP请求)
fetch* - - WebSocket方法(实时流)
watch* - - 创建新资源(订单、地址等)
create* - - 取消现有资源
cancel* - - 修改现有资源
edit* - - 配置设置(杠杆、保证金模式等)
set* - 后缀 - WebSocket变体(部分交易所支持)
*Ws
Proxy Configuration
代理配置
CCXT supports HTTP, HTTPS, and SOCKS proxies for both REST and WebSocket connections.
CCXT支持HTTP、HTTPS和SOCKS代理,适用于REST和WebSocket连接。
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'// HTTP代理
exchange.httpProxy = 'http://your-proxy-host:port'
// HTTPS代理
exchange.httpsProxy = 'https://your-proxy-host:port'
// SOCKS代理
exchange.socksProxy = 'socks://your-proxy-host:port'
// 带身份验证的代理
exchange.httpProxy = 'http://user:pass@proxy-host:port'Proxy for WebSocket
WebSocket代理
WebSocket connections also respect proxy settings:
exchange.httpsProxy = 'https://proxy:8080'
// WebSocket connections will use this proxyWebSocket连接同样会遵循代理设置:
exchange.httpsProxy = 'https://proxy:8080'
// WebSocket连接将使用此代理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)
}exchange.httpProxy = 'http://localhost:8080'
try {
await exchange.fetchTicker('BTC/USDT')
console.log('代理可用!')
} catch (error) {
console.error('代理连接失败:', error)
}WebSocket-Specific Methods
WebSocket专属方法
Some exchanges provide WebSocket variants of REST methods for faster order placement and management. These use the suffix:
*Ws部分交易所提供了REST方法的WebSocket变体,用于更快地下单和管理订单,这些方法以为后缀:
*WsTrading via WebSocket
通过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
创建订单:
- - 通过WebSocket创建订单(比REST更快)
createOrderWs - - 通过WebSocket创建限价单
createLimitOrderWs - - 通过WebSocket创建市价单
createMarketOrderWs - - 通过WebSocket创建买入限价单
createLimitBuyOrderWs - - 通过WebSocket创建卖出限价单
createLimitSellOrderWs - - 通过WebSocket创建买入市价单
createMarketBuyOrderWs - - 通过WebSocket创建卖出市价单
createMarketSellOrderWs - - 通过WebSocket创建止损限价单
createStopLimitOrderWs - - 通过WebSocket创建止损市价单
createStopMarketOrderWs - - 通过WebSocket创建止损单
createStopLossOrderWs - - 通过WebSocket创建止盈单
createTakeProfitOrderWs - - 通过WebSocket创建追踪止损单(固定金额)
createTrailingAmountOrderWs - - 通过WebSocket创建追踪止损单(百分比)
createTrailingPercentOrderWs - - 通过WebSocket创建只做市单
createPostOnlyOrderWs - - 通过WebSocket创建只减仓单
createReduceOnlyOrderWs
订单管理:
- - 通过WebSocket修改订单
editOrderWs - - 通过WebSocket取消订单(比REST更快)
cancelOrderWs - - 通过WebSocket批量取消订单
cancelOrdersWs - - 通过WebSocket取消所有订单
cancelAllOrdersWs
数据查询:
- - 通过WebSocket查询订单
fetchOrderWs - - 通过WebSocket查询订单
fetchOrdersWs - - 通过WebSocket查询未成交订单
fetchOpenOrdersWs - - 通过WebSocket查询已成交订单
fetchClosedOrdersWs - - 通过WebSocket查询个人交易记录
fetchMyTradesWs - - 通过WebSocket查询账户余额
fetchBalanceWs - - 通过WebSocket查询持仓
fetchPositionWs - - 通过WebSocket查询所有持仓
fetchPositionsWs - - 通过WebSocket查询指定交易对的持仓
fetchPositionsForSymbolWs - - 通过WebSocket查询交易手续费
fetchTradingFeesWs
When to Use WebSocket Methods
何时使用WebSocket方法
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
当以下情况时使用方法:
*Ws- 你需要更快的下单速度(更低延迟)
- 已经通过WebSocket连接到交易所
- 你想减少REST API的请求限制消耗
- 交易策略要求延迟低于100毫秒
当以下情况时使用REST方法:
- 你需要确保执行确认
- 你正在进行一次性请求
- 交易所不支持对应的WebSocket变体
- 你需要详细的错误响应
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)REST API(速度较慢,更可靠):
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)WebSocket API(速度更快,延迟更低):
const order = await exchange.createOrderWs('BTC/USDT', 'limit', 'buy', 0.01, 50000)Checking WebSocket Method Availability
检查WebSocket方法可用性
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)
}并非所有交易所都支持WebSocket交易方法:
if (exchange.has['createOrderWs']) {
// 交易所支持通过WebSocket创建订单
const order = await exchange.createOrderWs('BTC/USDT', 'limit', 'buy', 0.01, 50000)
} else {
// 回退到REST方法
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)
}Authentication
身份验证
Setting API Keys
设置API密钥
typescript
// During instantiation
const exchange = new ccxt.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET',
enableRateLimit: true
})
// After instantiation
exchange.apiKey = 'YOUR_API_KEY'
exchange.secret = 'YOUR_SECRET'typescript
// 实例化时设置
const exchange = new ccxt.binance({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_SECRET',
enableRateLimit: true
})
// 实例化后设置
exchange.apiKey = 'YOUR_API_KEY'
exchange.secret = 'YOUR_SECRET'Environment Variables (Recommended)
环境变量(推荐方式)
typescript
const exchange = new ccxt.binance({
apiKey: process.env.BINANCE_API_KEY,
secret: process.env.BINANCE_SECRET,
enableRateLimit: true
})typescript
const exchange = new ccxt.binance({
apiKey: process.env.BINANCE_API_KEY,
secret: process.env.BINANCE_SECRET,
enableRateLimit: true
})Testing Authentication
测试身份验证
typescript
try {
const balance = await exchange.fetchBalance()
console.log('Authentication successful!')
} catch (error) {
if (error instanceof ccxt.AuthenticationError) {
console.error('Invalid API credentials')
}
}typescript
try {
const balance = await exchange.fetchBalance()
console.log('身份验证成功!')
} catch (error) {
if (error instanceof ccxt.AuthenticationError) {
console.error('无效的API凭证')
}
}Error Handling
错误处理
Exception Hierarchy
异常层级
BaseError
├─ NetworkError (recoverable - retry)
│ ├─ RequestTimeout
│ ├─ ExchangeNotAvailable
│ ├─ RateLimitExceeded
│ └─ DDoSProtection
└─ ExchangeError (non-recoverable - don't retry)
├─ AuthenticationError
├─ InsufficientFunds
├─ InvalidOrder
└─ NotSupportedBaseError
├─ NetworkError(可恢复 - 重试)
│ ├─ RequestTimeout
│ ├─ ExchangeNotAvailable
│ ├─ RateLimitExceeded
│ └─ DDoSProtection
└─ ExchangeError(不可恢复 - 请勿重试)
├─ AuthenticationError
├─ InsufficientFunds
├─ InvalidOrder
└─ NotSupportedBasic Error Handling
基础错误处理
typescript
import ccxt from 'ccxt'
try {
const ticker = await exchange.fetchTicker('BTC/USDT')
} catch (error) {
if (error instanceof ccxt.NetworkError) {
console.error('Network error - retry:', error.message)
} else if (error instanceof ccxt.ExchangeError) {
console.error('Exchange error - do not retry:', error.message)
} else {
console.error('Unknown error:', error)
}
}typescript
import ccxt from 'ccxt'
try {
const ticker = await exchange.fetchTicker('BTC/USDT')
} catch (error) {
if (error instanceof ccxt.NetworkError) {
console.error('网络错误 - 重试:', error.message)
} else if (error instanceof ccxt.ExchangeError) {
console.error('交易所错误 - 请勿重试:', error.message)
} else {
console.error('未知错误:', error)
}
}Specific Exception Handling
特定异常处理
typescript
try {
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)
} catch (error) {
if (error instanceof ccxt.InsufficientFunds) {
console.error('Not enough balance')
} else if (error instanceof ccxt.InvalidOrder) {
console.error('Invalid order parameters')
} else if (error instanceof ccxt.RateLimitExceeded) {
console.error('Rate limit hit - wait before retrying')
await exchange.sleep(1000) // Wait 1 second
} else if (error instanceof ccxt.AuthenticationError) {
console.error('Check your API credentials')
}
}typescript
try {
const order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)
} catch (error) {
if (error instanceof ccxt.InsufficientFunds) {
console.error('余额不足')
} else if (error instanceof ccxt.InvalidOrder) {
console.error('订单参数无效')
} else if (error instanceof ccxt.RateLimitExceeded) {
console.error('触发请求限制 - 请稍后重试')
await exchange.sleep(1000) // 等待1秒
} else if (error instanceof ccxt.AuthenticationError) {
console.error('请检查你的API凭证')
}
}Retry Logic for Network Errors
网络错误重试逻辑
typescript
async function fetchWithRetry(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await exchange.fetchTicker('BTC/USDT')
} catch (error) {
if (error instanceof ccxt.NetworkError && i < maxRetries - 1) {
console.log(`Retry ${i + 1}/${maxRetries}`)
await exchange.sleep(1000 * (i + 1)) // Exponential backoff
} else {
throw error
}
}
}
}typescript
async function fetchWithRetry(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await exchange.fetchTicker('BTC/USDT')
} catch (error) {
if (error instanceof ccxt.NetworkError && i < maxRetries - 1) {
console.log(`第${i + 1}/${maxRetries}次重试`)
await exchange.sleep(1000 * (i + 1)) // 指数退避
} else {
throw error
}
}
}
}Rate Limiting
请求限制
Built-in Rate Limiter (Recommended)
内置请求限制器(推荐)
typescript
const exchange = new ccxt.binance({
enableRateLimit: true // Automatically throttles requests
})typescript
const exchange = new ccxt.binance({
enableRateLimit: true // 自动限制请求频率
})Manual Delays
手动延迟
typescript
await exchange.fetchTicker('BTC/USDT')
await exchange.sleep(1000) // Wait 1 second
await exchange.fetchTicker('ETH/USDT')typescript
await exchange.fetchTicker('BTC/USDT')
await exchange.sleep(1000) // 等待1秒
await exchange.fetchTicker('ETH/USDT')Checking Rate Limit
查看请求限制
typescript
console.log(exchange.rateLimit) // Milliseconds between requeststypescript
console.log(exchange.rateLimit) // 请求间隔(毫秒)Common Pitfalls
常见陷阱
Forgetting await
await忘记使用await
awaittypescript
// Wrong - returns Promise, not data
const ticker = exchange.fetchTicker('BTC/USDT')
console.log(ticker.last) // ERROR: ticker is a Promise!
// Correct
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker.last) // Works!typescript
// 错误 - 返回Promise,而非数据
const ticker = exchange.fetchTicker('BTC/USDT')
console.log(ticker.last) // 错误:ticker是Promise对象!
// 正确
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker.last) // 正常工作!Using REST for Real-time Monitoring
使用REST进行实时监控
typescript
// Wrong - wastes rate limits, slow
while (true) {
const ticker = await exchange.fetchTicker('BTC/USDT') // REST
console.log(ticker.last)
await exchange.sleep(1000)
}
// Correct - use WebSocket
const exchange = new ccxt.pro.binance()
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT') // WebSocket
console.log(ticker.last)
}typescript
// 错误 - 浪费请求限制,速度慢
while (true) {
const ticker = await exchange.fetchTicker('BTC/USDT') // REST
console.log(ticker.last)
await exchange.sleep(1000)
}
// 正确 - 使用WebSocket
const exchange = new ccxt.pro.binance()
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT') // WebSocket
console.log(ticker.last)
}Not Closing WebSocket Connections
未关闭WebSocket连接
typescript
// Wrong - memory leak
const exchange = new ccxt.pro.binance()
const ticker = await exchange.watchTicker('BTC/USDT')
// Forgot to close!
// Correct
const exchange = new ccxt.pro.binance()
try {
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT')
console.log(ticker)
}
} finally {
await exchange.close()
}typescript
// 错误 - 内存泄漏
const exchange = new ccxt.pro.binance()
const ticker = await exchange.watchTicker('BTC/USDT')
// 忘记关闭连接!
// 正确
const exchange = new ccxt.pro.binance()
try {
while (true) {
const ticker = await exchange.watchTicker('BTC/USDT')
console.log(ticker)
}
} finally {
await exchange.close()
}Multiple Instances with Same API Keys
使用相同API密钥创建多个实例
typescript
// Wrong - nonce conflicts
const ex1 = new ccxt.binance({ apiKey: 'key', secret: 'secret' })
const ex2 = new ccxt.binance({ apiKey: 'key', secret: 'secret' })
await ex1.fetchBalance()
await ex2.fetchBalance() // May fail due to nonce issues!
// Correct - reuse single instance
const exchange = new ccxt.binance({ apiKey: 'key', secret: 'secret' })
await exchange.fetchBalance()
await exchange.fetchBalance()typescript
// 错误 - 随机数冲突
const ex1 = new ccxt.binance({ apiKey: 'key', secret: 'secret' })
const ex2 = new ccxt.binance({ apiKey: 'key', secret: 'secret' })
await ex1.fetchBalance()
await ex2.fetchBalance() // 可能因随机数问题失败!
// 正确 - 复用单个实例
const exchange = new ccxt.binance({ apiKey: 'key', secret: 'secret' })
await exchange.fetchBalance()
await exchange.fetchBalance()Not Enabling Rate Limiter
未启用请求限制器
typescript
// Wrong - may hit rate limits
const exchange = new ccxt.binance()
for (let i = 0; i < 100; i++) {
await exchange.fetchTicker('BTC/USDT') // May fail!
}
// Correct
const exchange = new ccxt.binance({ enableRateLimit: true })
for (let i = 0; i < 100; i++) {
await exchange.fetchTicker('BTC/USDT') // Automatically throttled
}typescript
// 错误 - 可能触发请求限制
const exchange = new ccxt.binance()
for (let i = 0; i < 100; i++) {
await exchange.fetchTicker('BTC/USDT') // 可能失败!
}
// 正确
const exchange = new ccxt.binance({ enableRateLimit: true })
for (let i = 0; i < 100; i++) {
await exchange.fetchTicker('BTC/USDT') // 自动限制请求频率
}Browser Usage
浏览器端使用
Via CDN
通过CDN引入
html
<script src="https://cdn.jsdelivr.net/npm/ccxt@latest/dist/ccxt.browser.js"></script>
<script>
const exchange = new ccxt.binance()
exchange.loadMarkets().then(() => {
return exchange.fetchTicker('BTC/USDT')
}).then(ticker => {
console.log(ticker)
})
</script>html
<script src="https://cdn.jsdelivr.net/npm/ccxt@latest/dist/ccxt.browser.js"></script>
<script>
const exchange = new ccxt.binance()
exchange.loadMarkets().then(() => {
return exchange.fetchTicker('BTC/USDT')
}).then(ticker => {
console.log(ticker)
})
</script>ES Modules
ES模块方式
javascript
import ccxt from 'https://cdn.jsdelivr.net/npm/ccxt@latest/dist/ccxt.browser.js'
const exchange = new ccxt.binance()
await exchange.loadMarkets()
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker)javascript
import ccxt from 'https://cdn.jsdelivr.net/npm/ccxt@latest/dist/ccxt.browser.js'
const exchange = new ccxt.binance()
await exchange.loadMarkets()
const ticker = await exchange.fetchTicker('BTC/USDT')
console.log(ticker)Troubleshooting
故障排除
Common Issues
常见问题
1. "Cannot find module 'ccxt'"
- Solution: Run
npm install ccxt
2. "RateLimitExceeded"
- Solution: Enable rate limiter:
enableRateLimit: true - Or add manual delays between requests
3. "AuthenticationError"
- Solution: Check API key and secret
- Verify API key permissions on exchange
- Check system clock is synced (use NTP)
4. "InvalidNonce"
- Solution: Sync system clock
- Use only one exchange instance per API key
- Don't run multiple bots with same credentials
5. "InsufficientFunds"
- Solution: Check available balance ()
balance.BTC.free - Account for trading fees
6. "ExchangeNotAvailable"
- Solution: Check exchange status/maintenance
- Retry after a delay
- Use different exchange endpoint if available
7. WebSocket connection drops
- Solution: Implement reconnection logic
- Use try-catch and restart methods
watch* - Check network stability
1. "Cannot find module 'ccxt'"
- 解决方案:执行
npm install ccxt
2. "RateLimitExceeded"
- 解决方案:启用请求限制器:
enableRateLimit: true - 或在请求之间添加手动延迟
3. "AuthenticationError"
- 解决方案:检查API密钥和密钥
- 验证API密钥在交易所的权限
- 检查系统时钟是否同步(使用NTP)
4. "InvalidNonce"
- 解决方案:同步系统时钟
- 每个API密钥仅使用一个交易所实例
- 不要使用相同凭证运行多个机器人
5. "InsufficientFunds"
- 解决方案:检查可用余额()
balance.BTC.free - 考虑交易手续费
6. "ExchangeNotAvailable"
- 解决方案:检查交易所状态/维护公告
- 延迟后重试
- 若有可用,使用其他交易所节点
7. WebSocket连接断开
- 解决方案:实现重连逻辑
- 使用try-catch并重启方法
watch* - 检查网络稳定性
Debugging
调试
typescript
// Enable verbose logging
exchange.verbose = true
// Check exchange capabilities
console.log(exchange.has)
// {
// fetchTicker: true,
// fetchOrderBook: true,
// createOrder: true,
// ...
// }
// Check market information
console.log(exchange.markets['BTC/USDT'])
// Check last request/response
console.log(exchange.last_http_response)
console.log(exchange.last_json_response)typescript
// 启用详细日志
exchange.verbose = true
// 检查交易所功能
console.log(exchange.has)
// {
// fetchTicker: true,
// fetchOrderBook: true,
// createOrder: true,
// ...
// }
// 检查市场信息
console.log(exchange.markets['BTC/USDT'])
// 检查最近的请求/响应
console.log(exchange.last_http_response)
console.log(exchange.last_json_response)