ccxt-python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CCXT for Python

面向Python的CCXT库

A comprehensive guide to using CCXT in Python projects for cryptocurrency exchange integration.
一份关于在Python项目中使用CCXT对接加密货币交易所的全面指南。

Installation

安装

REST API (Standard)

REST API(标准型)

bash
pip install ccxt
bash
pip install ccxt

WebSocket API (Real-time, ccxt.pro)

WebSocket API(实时型,ccxt.pro)

bash
pip install ccxt
bash
pip install ccxt

Optional Performance Enhancements

可选性能增强

bash
pip install orjson      # Faster JSON parsing
pip install coincurve   # Faster ECDSA signing (45ms → 0.05ms)
Both REST and WebSocket APIs are included in the same package.
bash
pip install orjson      # 更快的JSON解析
pip install coincurve   # 更快的ECDSA签名(从45ms优化至0.05ms)
REST和WebSocket API都包含在同一个包中。

Quick Start

快速入门

REST API - Synchronous

REST API - 同步方式

python
import ccxt

exchange = ccxt.binance()
exchange.load_markets()
ticker = exchange.fetch_ticker('BTC/USDT')
print(ticker)
python
import ccxt

exchange = ccxt.binance()
exchange.load_markets()
ticker = exchange.fetch_ticker('BTC/USDT')
print(ticker)

REST API - Asynchronous

REST API - 异步方式

python
import asyncio
import ccxt.async_support as ccxt

async def main():
    exchange = ccxt.binance()
    await exchange.load_markets()
    ticker = await exchange.fetch_ticker('BTC/USDT')
    print(ticker)
    await exchange.close()  # Important!

asyncio.run(main())
python
import asyncio
import ccxt.async_support as ccxt

async def main():
    exchange = ccxt.binance()
    await exchange.load_markets()
    ticker = await exchange.fetch_ticker('BTC/USDT')
    print(ticker)
    await exchange.close()  # 重要!使用后需关闭

asyncio.run(main())

WebSocket API - Real-time Updates

WebSocket API - 实时更新

python
import asyncio
import ccxt.pro as ccxtpro

async def main():
    exchange = ccxtpro.binance()
    while True:
        ticker = await exchange.watch_ticker('BTC/USDT')
        print(ticker)  # Live updates!
    await exchange.close()

asyncio.run(main())
python
import asyncio
import ccxt.pro as ccxtpro

async def main():
    exchange = ccxtpro.binance()
    while True:
        ticker = await exchange.watch_ticker('BTC/USDT')
        print(ticker)  # 实时更新!
    await exchange.close()

asyncio.run(main())

REST vs WebSocket

REST与WebSocket对比

ImportFor RESTFor WebSocket
Sync
import ccxt
(WebSocket requires async)
Async
import ccxt.async_support as ccxt
import ccxt.pro as ccxtpro
FeatureREST APIWebSocket API
Use forOne-time queries, placing ordersReal-time monitoring, live price feeds
Method prefix
fetch_*
(fetch_ticker, fetch_order_book)
watch_*
(watch_ticker, watch_order_book)
SpeedSlower (HTTP request/response)Faster (persistent connection)
Rate limitsStrict (1-2 req/sec)More lenient (continuous stream)
Best forTrading, account managementPrice 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用于WebSocket
同步
import ccxt
(WebSocket需使用异步)
异步
import ccxt.async_support as ccxt
import ccxt.pro as ccxtpro
特性REST APIWebSocket API
适用场景一次性查询、下单实时监控、实时价格推送
方法前缀
fetch_*
(如fetch_ticker、fetch_order_book)
watch_*
(如watch_ticker、watch_order_book)
速度较慢(HTTP请求/响应模式)较快(长连接模式)
请求限制严格(1-2次请求/秒)宽松(持续流推送)
最佳用途交易操作、账户管理价格监控、套利检测
何时使用REST:
  • 下单操作
  • 获取账户余额
  • 一次性数据查询
  • 订单管理(取消、查询订单)
何时使用WebSocket:
  • 实时价格监控
  • 订单簿实时更新
  • 套利机会检测
  • 投资组合实时跟踪

Creating Exchange Instance

创建交易所实例

REST API - Synchronous

REST API - 同步方式

python
import ccxt
python
import ccxt

Public API (no authentication)

公开API(无需身份验证)

exchange = ccxt.binance({ 'enableRateLimit': True # Recommended! })
exchange = ccxt.binance({ 'enableRateLimit': True # 推荐启用! })

Private API (with authentication)

私有API(需身份验证)

exchange = ccxt.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', 'enableRateLimit': True })
undefined
exchange = ccxt.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', 'enableRateLimit': True })
undefined

REST API - Asynchronous

REST API - 异步方式

python
import ccxt.async_support as ccxt

exchange = ccxt.binance({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET',
    'enableRateLimit': True
})
python
import ccxt.async_support as ccxt

exchange = ccxt.binance({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET',
    'enableRateLimit': True
})

Always close when done

使用后务必关闭

await exchange.close()
undefined
await exchange.close()
undefined

WebSocket API

WebSocket API

python
import ccxt.pro as ccxtpro
python
import ccxt.pro as ccxtpro

Public WebSocket

公开WebSocket

exchange = ccxtpro.binance()
exchange = ccxtpro.binance()

Private WebSocket (with authentication)

私有WebSocket(需身份验证)

exchange = ccxtpro.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET' })
exchange = ccxtpro.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET' })

Always close when done

使用后务必关闭

await exchange.close()
undefined
await exchange.close()
undefined

Common REST Operations

常见REST操作

Loading Markets

加载市场信息

python
undefined
python
undefined

Load all available trading pairs

加载所有可用交易对

exchange.load_markets()
exchange.load_markets()

Access market information

访问市场详情

btc_market = exchange.market('BTC/USDT') print(btc_market['limits']['amount']['min']) # Minimum order amount
undefined
btc_market = exchange.market('BTC/USDT') print(btc_market['limits']['amount']['min']) # 最小下单量
undefined

Fetching Ticker

获取行情数据

python
undefined
python
undefined

Single ticker

单个交易对行情

ticker = exchange.fetch_ticker('BTC/USDT') print(ticker['last']) # Last price print(ticker['bid']) # Best bid print(ticker['ask']) # Best ask print(ticker['volume']) # 24h volume
ticker = exchange.fetch_ticker('BTC/USDT') print(ticker['last']) # 最新成交价 print(ticker['bid']) # 最优买价 print(ticker['ask']) # 最优卖价 print(ticker['volume']) # 24小时成交量

Multiple tickers (if supported)

多个交易对行情(若交易所支持)

tickers = exchange.fetch_tickers(['BTC/USDT', 'ETH/USDT'])
undefined
tickers = exchange.fetch_tickers(['BTC/USDT', 'ETH/USDT'])
undefined

Fetching Order Book

获取订单簿

python
undefined
python
undefined

Full orderbook

完整订单簿

orderbook = exchange.fetch_order_book('BTC/USDT') print(orderbook['bids'][0]) # [price, amount] print(orderbook['asks'][0]) # [price, amount]
orderbook = exchange.fetch_order_book('BTC/USDT') print(orderbook['bids'][0]) # [价格, 数量] print(orderbook['asks'][0]) # [价格, 数量]

Limited depth

限定深度的订单簿

orderbook = exchange.fetch_order_book('BTC/USDT', 5) # Top 5 levels
undefined
orderbook = exchange.fetch_order_book('BTC/USDT', 5) # 前5档深度
undefined

Creating Orders

创建订单

Limit Order

限价单

python
undefined
python
undefined

Buy limit order

买入限价单

order = exchange.create_limit_buy_order('BTC/USDT', 0.01, 50000) print(order['id'])
order = exchange.create_limit_buy_order('BTC/USDT', 0.01, 50000) print(order['id'])

Sell limit order

卖出限价单

order = exchange.create_limit_sell_order('BTC/USDT', 0.01, 60000)
order = exchange.create_limit_sell_order('BTC/USDT', 0.01, 60000)

Generic limit order

通用限价单

order = exchange.create_order('BTC/USDT', 'limit', 'buy', 0.01, 50000)
undefined
order = exchange.create_order('BTC/USDT', 'limit', 'buy', 0.01, 50000)
undefined

Market Order

市价单

python
undefined
python
undefined

Buy market order

买入市价单

order = exchange.create_market_buy_order('BTC/USDT', 0.01)
order = exchange.create_market_buy_order('BTC/USDT', 0.01)

Sell market order

卖出市价单

order = exchange.create_market_sell_order('BTC/USDT', 0.01)
order = exchange.create_market_sell_order('BTC/USDT', 0.01)

Generic market order

通用市价单

order = exchange.create_order('BTC/USDT', 'market', 'sell', 0.01)
undefined
order = exchange.create_order('BTC/USDT', 'market', 'sell', 0.01)
undefined

Fetching Balance

获取账户余额

python
balance = exchange.fetch_balance()
print(balance['BTC']['free'])   # Available balance
print(balance['BTC']['used'])   # Balance in orders
print(balance['BTC']['total'])  # Total balance
python
balance = exchange.fetch_balance()
print(balance['BTC']['free'])   # 可用余额
print(balance['BTC']['used'])   # 订单占用余额
print(balance['BTC']['total'])  # 总余额

Fetching Orders

查询订单

python
undefined
python
undefined

Open orders

未成交订单

open_orders = exchange.fetch_open_orders('BTC/USDT')
open_orders = exchange.fetch_open_orders('BTC/USDT')

Closed orders

已成交订单

closed_orders = exchange.fetch_closed_orders('BTC/USDT')
closed_orders = exchange.fetch_closed_orders('BTC/USDT')

All orders (open + closed)

所有订单(未成交+已成交)

all_orders = exchange.fetch_orders('BTC/USDT')
all_orders = exchange.fetch_orders('BTC/USDT')

Single order by ID

通过ID查询单个订单

order = exchange.fetch_order(order_id, 'BTC/USDT')
undefined
order = exchange.fetch_order(order_id, 'BTC/USDT')
undefined

Fetching Trades

查询交易记录

python
undefined
python
undefined

Recent public trades

近期公开交易记录

trades = exchange.fetch_trades('BTC/USDT', limit=10)
trades = exchange.fetch_trades('BTC/USDT', limit=10)

Your trades (requires authentication)

个人交易记录(需身份验证)

my_trades = exchange.fetch_my_trades('BTC/USDT')
undefined
my_trades = exchange.fetch_my_trades('BTC/USDT')
undefined

Canceling Orders

取消订单

python
undefined
python
undefined

Cancel single order

取消单个订单

exchange.cancel_order(order_id, 'BTC/USDT')
exchange.cancel_order(order_id, 'BTC/USDT')

Cancel all orders for a symbol

取消某交易对的所有订单

exchange.cancel_all_orders('BTC/USDT')
undefined
exchange.cancel_all_orders('BTC/USDT')
undefined

WebSocket Operations (Real-time)

WebSocket实时操作

Watching Ticker (Live Price Updates)

监控行情(实时价格更新)

python
import asyncio
import ccxt.pro as ccxtpro

async def main():
    exchange = ccxtpro.binance()
    while True:
        ticker = await exchange.watch_ticker('BTC/USDT')
        print(ticker['last'], ticker['timestamp'])
    await exchange.close()

asyncio.run(main())
python
import asyncio
import ccxt.pro as ccxtpro

async def main():
    exchange = ccxtpro.binance()
    while True:
        ticker = await exchange.watch_ticker('BTC/USDT')
        print(ticker['last'], ticker['timestamp'])
    await exchange.close()

asyncio.run(main())

Watching Order Book (Live Depth Updates)

监控订单簿(实时深度更新)

python
async def main():
    exchange = ccxtpro.binance()
    while True:
        orderbook = await exchange.watch_order_book('BTC/USDT')
        print('Best bid:', orderbook['bids'][0])
        print('Best ask:', orderbook['asks'][0])
    await exchange.close()

asyncio.run(main())
python
async def main():
    exchange = ccxtpro.binance()
    while True:
        orderbook = await exchange.watch_order_book('BTC/USDT')
        print('最优买价:', orderbook['bids'][0])
        print('最优卖价:', orderbook['asks'][0])
    await exchange.close()

asyncio.run(main())

Watching Trades (Live Trade Stream)

监控交易记录(实时交易流)

python
async def main():
    exchange = ccxtpro.binance()
    while True:
        trades = await exchange.watch_trades('BTC/USDT')
        for trade in trades:
            print(trade['price'], trade['amount'], trade['side'])
    await exchange.close()

asyncio.run(main())
python
async def main():
    exchange = ccxtpro.binance()
    while True:
        trades = await exchange.watch_trades('BTC/USDT')
        for trade in trades:
            print(trade['price'], trade['amount'], trade['side'])
    await exchange.close()

asyncio.run(main())

Watching Your Orders (Live Order Updates)

监控个人订单(实时订单更新)

python
async def main():
    exchange = ccxtpro.binance({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET'
    })
    while True:
        orders = await exchange.watch_orders('BTC/USDT')
        for order in orders:
            print(order['id'], order['status'], order['filled'])
    await exchange.close()

asyncio.run(main())
python
async def main():
    exchange = ccxtpro.binance({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET'
    })
    while True:
        orders = await exchange.watch_orders('BTC/USDT')
        for order in orders:
            print(order['id'], order['status'], order['filled'])
    await exchange.close()

asyncio.run(main())

Watching Balance (Live Balance Updates)

监控账户余额(实时余额更新)

python
async def main():
    exchange = ccxtpro.binance({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET'
    })
    while True:
        balance = await exchange.watch_balance()
        print('BTC:', balance['BTC'])
        print('USDT:', balance['USDT'])
    await exchange.close()

asyncio.run(main())
python
async def main():
    exchange = ccxtpro.binance({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET'
    })
    while True:
        balance = await exchange.watch_balance()
        print('BTC:', balance['BTC'])
        print('USDT:', balance['USDT'])
    await exchange.close()

asyncio.run(main())

Watching Multiple Symbols

监控多个交易对

python
async def main():
    exchange = ccxtpro.binance()
    symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT']

    while True:
        # Watch all symbols concurrently
        tickers = await exchange.watch_tickers(symbols)
        for symbol, ticker in tickers.items():
            print(symbol, ticker['last'])
    await exchange.close()

asyncio.run(main())
python
async def main():
    exchange = ccxtpro.binance()
    symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT']

    while True:
        # 并发监控所有交易对
        tickers = await exchange.watch_tickers(symbols)
        for symbol, ticker in tickers.items():
            print(symbol, ticker['last'])
    await exchange.close()

asyncio.run(main())

Complete Method Reference

完整方法参考

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
  • fetchMarkPrices([symbols])
    - Fetch mark prices (derivatives)
  • fetchTicker(symbol)
    - 获取单个交易对行情
  • fetchTickers([symbols])
    - 批量获取多个交易对行情
  • fetchBidsAsks([symbols])
    - 获取多个交易对的最优买卖价
  • fetchLastPrices([symbols])
    - 获取多个交易对的最新成交价
  • fetchMarkPrices([symbols])
    - 获取标记价格(衍生品)

Order Books

订单簿

  • fetchOrderBook(symbol, limit)
    - Fetch order book
  • fetchOrderBooks([symbols])
    - Fetch multiple order books
  • fetchL2OrderBook(symbol)
    - Fetch level 2 order book
  • fetchL3OrderBook(symbol)
    - Fetch level 3 order book (if supported)
  • fetchOrderBook(symbol, limit)
    - 获取订单簿
  • fetchOrderBooks([symbols])
    - 批量获取多个订单簿
  • fetchL2OrderBook(symbol)
    - 获取Level 2订单簿
  • fetchL3OrderBook(symbol)
    - 获取Level 3订单簿(若交易所支持)

Trades

交易记录

  • fetchTrades(symbol, since, limit)
    - Fetch public trades
  • fetchMyTrades(symbol, since, limit)
    - Fetch your trades (auth required)
  • fetchOrderTrades(orderId, symbol)
    - Fetch trades for specific order
  • fetchTrades(symbol, since, limit)
    - 获取公开交易记录
  • fetchMyTrades(symbol, since, limit)
    - 获取个人交易记录(需身份验证)
  • fetchOrderTrades(orderId, symbol)
    - 获取指定订单的交易明细

OHLCV (Candlesticks)

K线数据(蜡烛图)

  • fetchOHLCV(symbol, timeframe, since, limit)
    - Fetch candlestick data
  • fetchIndexOHLCV(symbol, timeframe)
    - Fetch index price OHLCV
  • fetchMarkOHLCV(symbol, timeframe)
    - Fetch mark price OHLCV
  • fetchPremiumIndexOHLCV(symbol, timeframe)
    - Fetch premium index OHLCV
  • fetchOHLCV(symbol, timeframe, since, limit)
    - 获取K线数据
  • fetchIndexOHLCV(symbol, timeframe)
    - 获取指数价格K线
  • fetchMarkOHLCV(symbol, timeframe)
    - 获取标记价格K线
  • fetchPremiumIndexOHLCV(symbol, timeframe)
    - 获取溢价指数K线

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
  • fetchTransactions(code, since, limit)
    - Fetch transactions
  • fetchDeposits(code, since, limit)
    - Fetch deposit history
  • fetchWithdrawals(code, since, limit)
    - Fetch withdrawal history
  • fetchDepositsWithdrawals(code, since, limit)
    - Fetch both deposits and withdrawals
  • 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

创建订单

  • createOrder(symbol, type, side, amount, price, params)
    - Create order (generic)
  • 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
  • createMarketBuyOrderWithCost(symbol, cost)
    - Buy with specific cost
  • createStopLimitOrder(symbol, side, amount, price, stopPrice)
    - Stop-limit order
  • createStopMarketOrder(symbol, side, amount, stopPrice)
    - Stop-market order
  • createStopLossOrder(symbol, side, amount, stopPrice)
    - Stop-loss order
  • createTakeProfitOrder(symbol, side, amount, takeProfitPrice)
    - Take-profit order
  • createTrailingAmountOrder(symbol, side, amount, trailingAmount)
    - Trailing stop
  • createTrailingPercentOrder(symbol, side, amount, trailingPercent)
    - Trailing stop %
  • createTriggerOrder(symbol, side, amount, triggerPrice)
    - Trigger order
  • createPostOnlyOrder(symbol, side, amount, price)
    - Post-only order
  • createReduceOnlyOrder(symbol, side, amount, price)
    - Reduce-only order
  • createOrders([orders])
    - Create multiple orders at once
  • createOrderWithTakeProfitAndStopLoss(symbol, type, side, amount, price, tpPrice, slPrice)
    - OCO order
  • 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])
    - 批量创建订单
  • createOrderWithTakeProfitAndStopLoss(symbol, type, side, amount, price, tpPrice, slPrice)
    - 创建OCO订单(止盈止损单)

Managing Orders

订单管理

  • fetchOrder(orderId, 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
  • fetchOpenOrder(orderId, symbol)
    - Fetch specific open order
  • fetchOrdersByStatus(status, symbol)
    - Fetch orders by status
  • cancelOrder(orderId, symbol)
    - Cancel single order
  • cancelOrders([orderIds], symbol)
    - Cancel multiple orders
  • cancelAllOrders(symbol)
    - Cancel all orders for symbol
  • editOrder(orderId, symbol, type, side, amount, price)
    - Modify order
  • 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

保证金与杠杆

  • fetchBorrowRate(code)
    - Fetch borrow rate for margin
  • fetchBorrowRates([codes])
    - Fetch multiple borrow rates
  • fetchBorrowRateHistory(code, since, limit)
    - Historical borrow rates
  • fetchCrossBorrowRate(code)
    - Cross margin borrow rate
  • fetchIsolatedBorrowRate(symbol, code)
    - Isolated margin borrow rate
  • borrowMargin(code, amount, symbol)
    - Borrow margin
  • repayMargin(code, amount, symbol)
    - Repay margin
  • fetchLeverage(symbol)
    - Fetch leverage
  • setLeverage(leverage, symbol)
    - Set leverage
  • fetchLeverageTiers(symbols)
    - Fetch leverage tiers
  • fetchMarketLeverageTiers(symbol)
    - Leverage tiers for market
  • setMarginMode(marginMode, symbol)
    - Set margin mode (cross/isolated)
  • fetchMarginMode(symbol)
    - Fetch margin mode
  • 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)
    - 获取杠杆 tiers 信息
  • fetchMarketLeverageTiers(symbol)
    - 获取指定交易对的杠杆 tiers 信息
  • setMarginMode(marginMode, symbol)
    - 设置保证金模式(全仓/逐仓)
  • fetchMarginMode(symbol)
    - 查询保证金模式

Derivatives & Futures

衍生品与期货

Positions

仓位管理

  • fetchPosition(symbol)
    - Fetch single position
  • fetchPositions([symbols])
    - Fetch all positions
  • fetchPositionsForSymbol(symbol)
    - Fetch positions for symbol
  • fetchPositionHistory(symbol, since, limit)
    - Position history
  • fetchPositionsHistory(symbols, since, limit)
    - Multiple position history
  • fetchPositionMode(symbol)
    - Fetch position mode (one-way/hedge)
  • setPositionMode(hedged, symbol)
    - Set position mode
  • closePosition(symbol, side)
    - Close position
  • closeAllPositions()
    - Close all positions
  • 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

资金费用与结算

  • 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)
    - Funding interval
  • fetchSettlementHistory(symbol, since, limit)
    - Settlement history
  • fetchMySettlementHistory(symbol, since, limit)
    - Your settlement history
  • 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

持仓量与强平记录

  • 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
  • fetchOpenInterest(symbol)
    - 获取持仓量
  • fetchOpenInterests([symbols])
    - 批量获取多个交易对的持仓量
  • fetchOpenInterestHistory(symbol, timeframe, since, limit)
    - 获取持仓量历史数据
  • fetchLiquidations(symbol, since, limit)
    - 获取公开强平记录
  • fetchMyLiquidations(symbol, since, limit)
    - 获取个人强平记录

Options

期权

  • fetchOption(symbol)
    - Fetch option info
  • fetchOptionChain(code)
    - Fetch option chain
  • fetchGreeks(symbol)
    - Fetch option greeks
  • fetchVolatilityHistory(code, since, limit)
    - Volatility history
  • fetchUnderlyingAssets()
    - Fetch underlying assets
  • fetchOption(symbol)
    - 获取期权信息
  • fetchOptionChain(code)
    - 获取期权链
  • fetchGreeks(symbol)
    - 获取期权希腊值
  • fetchVolatilityHistory(code, since, limit)
    - 获取波动率历史数据
  • fetchUnderlyingAssets()
    - 获取标的资产信息

Fees & Limits

手续费与限制

  • fetchTradingFee(symbol)
    - Trading fee for symbol
  • fetchTradingFees([symbols])
    - Trading fees for multiple symbols
  • fetchTradingLimits([symbols])
    - Trading limits
  • fetchTransactionFee(code)
    - Transaction/withdrawal fee
  • fetchTransactionFees([codes])
    - Multiple transaction fees
  • fetchDepositWithdrawFee(code)
    - Deposit/withdrawal fee
  • fetchDepositWithdrawFees([codes])
    - Multiple deposit/withdraw fees
  • fetchTradingFee(symbol)
    - 获取交易手续费
  • fetchTradingFees([symbols])
    - 批量获取多个交易对的手续费
  • fetchTradingLimits([symbols])
    - 获取交易限制
  • fetchTransactionFee(code)
    - 获取转账/提现手续费
  • fetchTransactionFees([codes])
    - 批量获取多个币种的转账/提现手续费
  • fetchDepositWithdrawFee(code)
    - 获取充值/提现手续费
  • fetchDepositWithdrawFees([codes])
    - 批量获取多个币种的充值/提现手续费

Deposits & Withdrawals

充值与提现

  • fetchDepositAddress(code, params)
    - Get deposit address
  • fetchDepositAddresses([codes])
    - Multiple deposit addresses
  • fetchDepositAddressesByNetwork(code)
    - Addresses by network
  • createDepositAddress(code, params)
    - Create new deposit address
  • fetchDeposit(id, code)
    - Fetch single deposit
  • fetchWithdrawal(id, code)
    - Fetch single withdrawal
  • fetchWithdrawAddresses(code)
    - Fetch withdrawal addresses
  • fetchWithdrawalWhitelist(code)
    - Fetch whitelist
  • withdraw(code, amount, address, tag, params)
    - Withdraw funds
  • deposit(code, amount, params)
    - Deposit funds (if supported)
  • 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

转账与兑换

  • transfer(code, amount, fromAccount, toAccount)
    - Internal transfer
  • 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
  • createConvertTrade(fromCode, toCode, amount)
    - Execute conversion
  • fetchConvertTrade(id)
    - Fetch convert trade
  • fetchConvertTradeHistory(code, since, limit)
    - Convert history
  • 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

市场信息

  • fetchMarkets()
    - Fetch all markets
  • fetchCurrencies()
    - Fetch all currencies
  • fetchTime()
    - Fetch exchange server time
  • fetchStatus()
    - Fetch exchange status
  • fetchBorrowInterest(code, symbol, since, limit)
    - Borrow interest paid
  • fetchLongShortRatio(symbol, timeframe, since, limit)
    - Long/short ratio
  • fetchLongShortRatioHistory(symbol, timeframe, since, limit)
    - L/S ratio history
  • 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
watch*
prefix:
所有REST方法都有对应的WebSocket方法,前缀为
watch*

Real-time Market Data

实时市场数据

  • watchTicker(symbol)
    - Watch single ticker
  • watchTickers([symbols])
    - Watch multiple tickers
  • watchOrderBook(symbol)
    - Watch order book updates
  • watchOrderBookForSymbols([symbols])
    - Watch multiple order books
  • watchTrades(symbol)
    - Watch public trades
  • watchOHLCV(symbol, timeframe)
    - Watch candlestick updates
  • watchBidsAsks([symbols])
    - Watch best bid/ask
  • watchTicker(symbol)
    - 监控单个交易对行情
  • watchTickers([symbols])
    - 批量监控多个交易对行情
  • watchOrderBook(symbol)
    - 监控订单簿更新
  • watchOrderBookForSymbols([symbols])
    - 批量监控多个订单簿
  • watchTrades(symbol)
    - 监控公开交易记录
  • watchOHLCV(symbol, timeframe)
    - 监控K线更新
  • watchBidsAsks([symbols])
    - 监控最优买卖价

Real-time Account Data (Auth Required)

实时账户数据(需身份验证)

  • watchBalance()
    - Watch balance updates
  • watchOrders(symbol)
    - Watch your order updates
  • watchMyTrades(symbol)
    - Watch your trade updates
  • watchPositions([symbols])
    - Watch position updates
  • watchPositionsForSymbol(symbol)
    - Watch positions for symbol
  • watchBalance()
    - 监控账户余额更新
  • watchOrders(symbol)
    - 监控个人订单更新
  • watchMyTrades(symbol)
    - 监控个人交易记录更新
  • watchPositions([symbols])
    - 监控仓位更新
  • watchPositionsForSymbol(symbol)
    - 监控指定交易对的仓位

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
    ,
    deposit
  • Margin/leverage methods
  • Position methods
  • watchBalance
    ,
    watchOrders
    ,
    watchMyTrades
    ,
    watchPositions
标记为🔒的方法需要API凭证:
  • 所有
    create*
    方法(创建订单、地址等)
  • 所有
    cancel*
    方法(取消订单等)
  • 所有
    edit*
    方法(修改订单等)
  • 所有
    fetchMy*
    方法(个人交易、订单等)
  • fetchBalance
    ,
    fetchLedger
    ,
    fetchAccounts
  • withdraw
    ,
    transfer
    ,
    deposit
  • 保证金/杠杆相关方法
  • 仓位相关方法
  • 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,
//   ...
// }
并非所有交易所都支持所有方法,使用前请检查:
// 检查方法是否支持
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

方法命名规范

  • 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)
  • fetch*
    - REST API方法(HTTP请求)
  • watch*
    - WebSocket方法(实时流)
  • create*
    - 创建新资源(订单、地址等)
  • cancel*
    - 取消现有资源
  • edit*
    - 修改现有资源
  • set*
    - 配置设置(杠杆、保证金模式等)
  • *Ws
    后缀 - WebSocket变体(部分交易所支持)

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 proxy
WebSocket连接同样遵循代理设置:
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
*Ws
suffix:
部分交易所提供了REST方法的WebSocket变体,用于更快地下单和管理订单,这些方法以
*Ws
为后缀:

Trading via WebSocket

通过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
创建订单:
  • createOrderWs
    - 通过WebSocket创建订单(比REST更快)
  • 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修改订单
  • cancelOrderWs
    - 通过WebSocket取消订单(比REST更快)
  • cancelOrdersWs
    - 通过WebSocket批量取消订单
  • cancelAllOrdersWs
    - 通过WebSocket取消所有订单
数据查询:
  • fetchOrderWs
    - 通过WebSocket查询订单
  • fetchOrdersWs
    - 通过WebSocket查询订单
  • fetchOpenOrdersWs
    - 通过WebSocket查询未成交订单
  • fetchClosedOrdersWs
    - 通过WebSocket查询已成交订单
  • fetchMyTradesWs
    - 通过WebSocket查询个人交易记录
  • fetchBalanceWs
    - 通过WebSocket查询账户余额
  • fetchPositionWs
    - 通过WebSocket查询仓位
  • fetchPositionsWs
    - 通过WebSocket查询所有仓位
  • fetchPositionsForSymbolWs
    - 通过WebSocket查询指定交易对的仓位
  • fetchTradingFeesWs
    - 通过WebSocket查询交易手续费

When to Use WebSocket Methods

何时使用WebSocket方法

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
使用
*Ws
方法的场景:
  • 需要更快的下单速度(更低延迟)
  • 已通过WebSocket连接到交易所
  • 希望减少REST API的请求限制消耗
  • 交易策略要求延迟低于100ms
使用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密钥

python
import os
python
import os

During instantiation (recommended)

实例化时设置(推荐)

exchange = ccxt.binance({ 'apiKey': os.environ.get('BINANCE_API_KEY'), 'secret': os.environ.get('BINANCE_SECRET'), 'enableRateLimit': True })
exchange = ccxt.binance({ 'apiKey': os.environ.get('BINANCE_API_KEY'), 'secret': os.environ.get('BINANCE_SECRET'), 'enableRateLimit': True })

After instantiation

实例化后设置

exchange.apiKey = os.environ.get('BINANCE_API_KEY') exchange.secret = os.environ.get('BINANCE_SECRET')
undefined
exchange.apiKey = os.environ.get('BINANCE_API_KEY') exchange.secret = os.environ.get('BINANCE_SECRET')
undefined

Testing Authentication

测试身份验证

python
try:
    balance = exchange.fetch_balance()
    print('Authentication successful!')
except ccxt.AuthenticationError:
    print('Invalid API credentials')
python
try:
    balance = exchange.fetch_balance()
    print('身份验证成功!')
except ccxt.AuthenticationError:
    print('API凭证无效')

Error Handling

错误处理

Exception Hierarchy

异常层级

BaseError
├─ NetworkError (recoverable - retry)
│  ├─ RequestTimeout
│  ├─ ExchangeNotAvailable
│  ├─ RateLimitExceeded
│  └─ DDoSProtection
└─ ExchangeError (non-recoverable - don't retry)
   ├─ AuthenticationError
   ├─ InsufficientFunds
   ├─ InvalidOrder
   └─ NotSupported
BaseError
├─ NetworkError(可恢复 - 可重试)
│  ├─ RequestTimeout
│  ├─ ExchangeNotAvailable
│  ├─ RateLimitExceeded
│  └─ DDoSProtection
└─ ExchangeError(不可恢复 - 请勿重试)
   ├─ AuthenticationError
   ├─ InsufficientFunds
   ├─ InvalidOrder
   └─ NotSupported

Basic Error Handling

基础错误处理

python
import ccxt

try:
    ticker = exchange.fetch_ticker('BTC/USDT')
except ccxt.NetworkError as e:
    print('Network error - retry:', str(e))
except ccxt.ExchangeError as e:
    print('Exchange error - do not retry:', str(e))
except Exception as e:
    print('Unknown error:', str(e))
python
import ccxt

try:
    ticker = exchange.fetch_ticker('BTC/USDT')
except ccxt.NetworkError as e:
    print('网络错误 - 可重试:', str(e))
except ccxt.ExchangeError as e:
    print('交易所错误 - 请勿重试:', str(e))
except Exception as e:
    print('未知错误:', str(e))

Specific Exception Handling

特定异常处理

python
try:
    order = exchange.create_order('BTC/USDT', 'limit', 'buy', 0.01, 50000)
except ccxt.InsufficientFunds:
    print('Not enough balance')
except ccxt.InvalidOrder:
    print('Invalid order parameters')
except ccxt.RateLimitExceeded:
    print('Rate limit hit - wait before retrying')
    exchange.sleep(1000)  # Wait 1 second
except ccxt.AuthenticationError:
    print('Check your API credentials')
python
try:
    order = exchange.create_order('BTC/USDT', 'limit', 'buy', 0.01, 50000)
except ccxt.InsufficientFunds:
    print('余额不足')
except ccxt.InvalidOrder:
    print('订单参数无效')
except ccxt.RateLimitExceeded:
    print('触发请求限制 - 请等待后重试')
    exchange.sleep(1000)  # 等待1秒
except ccxt.AuthenticationError:
    print('请检查API凭证')

Retry Logic for Network Errors

网络错误重试逻辑

python
def fetch_with_retry(max_retries=3):
    for i in range(max_retries):
        try:
            return exchange.fetch_ticker('BTC/USDT')
        except ccxt.NetworkError:
            if i < max_retries - 1:
                print(f'Retry {i + 1}/{max_retries}')
                exchange.sleep(1000 * (i + 1))  # Exponential backoff
            else:
                raise
python
def fetch_with_retry(max_retries=3):
    for i in range(max_retries):
        try:
            return exchange.fetch_ticker('BTC/USDT')
        except ccxt.NetworkError:
            if i < max_retries - 1:
                print(f'重试 {i + 1}/{max_retries}')
                exchange.sleep(1000 * (i + 1))  # 指数退避
            else:
                raise

Async vs Sync

同步与异步对比

When to Use Sync

何时使用同步

  • Simple scripts
  • Single exchange operations
  • Jupyter notebooks
  • Quick testing
  • 简单脚本
  • 单个交易所操作
  • Jupyter笔记本
  • 快速测试

When to Use Async

何时使用异步

  • Multiple concurrent operations
  • WebSocket connections (required)
  • High-performance trading bots
  • Multiple exchange monitoring
  • 多个并发操作
  • WebSocket连接(必须使用异步)
  • 高性能交易机器人
  • 多交易所监控

Sync Example

同步示例

python
import ccxt

exchange = ccxt.binance({'enableRateLimit': True})
ticker = exchange.fetch_ticker('BTC/USDT')
print(ticker['last'])
python
import ccxt

exchange = ccxt.binance({'enableRateLimit': True})
ticker = exchange.fetch_ticker('BTC/USDT')
print(ticker['last'])

Async Example

异步示例

python
import asyncio
import ccxt.async_support as ccxt

async def main():
    exchange = ccxt.binance({'enableRateLimit': True})
    ticker = await exchange.fetch_ticker('BTC/USDT')
    print(ticker['last'])
    await exchange.close()

asyncio.run(main())
python
import asyncio
import ccxt.async_support as ccxt

async def main():
    exchange = ccxt.binance({'enableRateLimit': True})
    ticker = await exchange.fetch_ticker('BTC/USDT')
    print(ticker['last'])
    await exchange.close()

asyncio.run(main())

Multiple Exchanges Async

多交易所异步示例

python
async def fetch_all():
    exchanges = [
        ccxt.binance({'enableRateLimit': True}),
        ccxt.coinbase({'enableRateLimit': True}),
        ccxt.kraken({'enableRateLimit': True})
    ]

    # Fetch concurrently
    tasks = [ex.fetch_ticker('BTC/USDT') for ex in exchanges]
    tickers = await asyncio.gather(*tasks, return_exceptions=True)

    for ex, ticker in zip(exchanges, tickers):
        if isinstance(ticker, Exception):
            print(f'{ex.id}: ERROR - {ticker}')
        else:
            print(f'{ex.id}: ${ticker["last"]}')
        await ex.close()

asyncio.run(fetch_all())
python
async def fetch_all():
    exchanges = [
        ccxt.binance({'enableRateLimit': True}),
        ccxt.coinbase({'enableRateLimit': True}),
        ccxt.kraken({'enableRateLimit': True})
    ]

    # 并发获取
    tasks = [ex.fetch_ticker('BTC/USDT') for ex in exchanges]
    tickers = await asyncio.gather(*tasks, return_exceptions=True)

    for ex, ticker in zip(exchanges, tickers):
        if isinstance(ticker, Exception):
            print(f'{ex.id}: 错误 - {ticker}')
        else:
            print(f'{ex.id}: ${ticker["last"]}')
        await ex.close()

asyncio.run(fetch_all())

Rate Limiting

请求限制

Built-in Rate Limiter (Recommended)

内置请求限制器(推荐)

python
exchange = ccxt.binance({
    'enableRateLimit': True  # Automatically throttles requests
})
python
exchange = ccxt.binance({
    'enableRateLimit': True  # 自动节流请求
})

Manual Delays

手动延迟

python
exchange.fetch_ticker('BTC/USDT')
exchange.sleep(1000)  # Wait 1 second (milliseconds)
exchange.fetch_ticker('ETH/USDT')
python
exchange.fetch_ticker('BTC/USDT')
exchange.sleep(1000)  # 等待1秒(毫秒单位)
exchange.fetch_ticker('ETH/USDT')

Checking Rate Limit

查看请求限制

python
print(exchange.rateLimit)  # Milliseconds between requests
python
print(exchange.rateLimit)  # 请求间隔(毫秒)

Common Pitfalls

常见陷阱

Forgetting
await
in Async Mode

异步模式下忘记使用
await

python
undefined
python
undefined

Wrong - returns coroutine, not data

错误 - 返回协程对象,而非数据

async def wrong(): ticker = exchange.fetch_ticker('BTC/USDT') # Missing await! print(ticker['last']) # ERROR
async def wrong(): ticker = exchange.fetch_ticker('BTC/USDT') # 缺少await! print(ticker['last']) # 错误

Correct

正确

async def correct(): ticker = await exchange.fetch_ticker('BTC/USDT') print(ticker['last']) # Works!
undefined
async def correct(): ticker = await exchange.fetch_ticker('BTC/USDT') print(ticker['last']) # 正常运行
undefined

Using Sync for WebSocket

使用同步方式处理WebSocket

python
undefined
python
undefined

Wrong - WebSocket requires async

错误 - WebSocket必须使用异步

import ccxt.pro as ccxtpro exchange = ccxtpro.binance() ticker = exchange.watch_ticker('BTC/USDT') # ERROR: Need await!
import ccxt.pro as ccxtpro exchange = ccxtpro.binance() ticker = exchange.watch_ticker('BTC/USDT') # 错误:需要await!

Correct

正确

import asyncio import ccxt.pro as ccxtpro
async def main(): exchange = ccxtpro.binance() ticker = await exchange.watch_ticker('BTC/USDT') await exchange.close()
asyncio.run(main())
undefined
import asyncio import ccxt.pro as ccxtpro
async def main(): exchange = ccxtpro.binance() ticker = await exchange.watch_ticker('BTC/USDT') await exchange.close()
asyncio.run(main())
undefined

Not Closing Async Exchange

异步实例未关闭

python
undefined
python
undefined

Wrong - resource leak

错误 - 资源泄漏

async def wrong(): exchange = ccxt.binance() await exchange.fetch_ticker('BTC/USDT') # Forgot to close!
async def wrong(): exchange = ccxt.binance() await exchange.fetch_ticker('BTC/USDT') # 忘记关闭!

Correct

正确

async def correct(): exchange = ccxt.binance() try: await exchange.fetch_ticker('BTC/USDT') finally: await exchange.close()
undefined
async def correct(): exchange = ccxt.binance() try: await exchange.fetch_ticker('BTC/USDT') finally: await exchange.close()
undefined

Using Sync in Async Code

异步代码中使用同步实例

python
undefined
python
undefined

Wrong - blocks event loop

错误 - 阻塞事件循环

async def wrong(): exchange = ccxt.binance() # Sync import! ticker = exchange.fetch_ticker('BTC/USDT') # Blocking!
async def wrong(): exchange = ccxt.binance() # 同步导入! ticker = exchange.fetch_ticker('BTC/USDT') # 阻塞操作!

Correct

正确

import ccxt.async_support as ccxt
async def correct(): exchange = ccxt.binance() ticker = await exchange.fetch_ticker('BTC/USDT') await exchange.close()
undefined
import ccxt.async_support as ccxt
async def correct(): exchange = ccxt.binance() ticker = await exchange.fetch_ticker('BTC/USDT') await exchange.close()
undefined

Using REST for Real-time Monitoring

使用REST进行实时监控

python
undefined
python
undefined

Wrong - wastes rate limits

错误 - 浪费请求限制

while True: ticker = exchange.fetch_ticker('BTC/USDT') # REST print(ticker['last']) exchange.sleep(1000)
while True: ticker = exchange.fetch_ticker('BTC/USDT') # REST请求 print(ticker['last']) exchange.sleep(1000)

Correct - use WebSocket

正确 - 使用WebSocket

import ccxt.pro as ccxtpro
async def correct(): exchange = ccxtpro.binance() while True: ticker = await exchange.watch_ticker('BTC/USDT') # WebSocket print(ticker['last']) await exchange.close()
undefined
import ccxt.pro as ccxtpro
async def correct(): exchange = ccxtpro.binance() while True: ticker = await exchange.watch_ticker('BTC/USDT') # WebSocket print(ticker['last']) await exchange.close()
undefined

Troubleshooting

故障排除

Common Issues

常见问题

1. "ModuleNotFoundError: No module named 'ccxt'"
  • Solution: Run
    pip 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
5. "InsufficientFunds"
  • Solution: Check available balance (
    balance['BTC']['free']
    )
  • Account for trading fees
6. "ExchangeNotAvailable"
  • Solution: Check exchange status/maintenance
  • Retry after a delay
7. SSL/Certificate errors
  • Solution: Update certifi:
    pip install --upgrade certifi
8. Slow performance
  • Solution: Install performance enhancements:
    • pip install orjson
      (faster JSON)
    • pip install coincurve
      (faster signing)
1. "ModuleNotFoundError: No module named 'ccxt'"
  • 解决方案:执行
    pip install ccxt
2. "RateLimitExceeded"
  • 解决方案:启用请求限制器:
    'enableRateLimit': True
  • 或在请求之间添加手动延迟
3. "AuthenticationError"
  • 解决方案:检查API密钥和密钥
  • 验证API密钥在交易所的权限
  • 检查系统时钟是否同步(使用NTP)
4. "InvalidNonce"
  • 解决方案:同步系统时钟
  • 每个API密钥仅使用一个交易所实例
5. "InsufficientFunds"
  • 解决方案:检查可用余额(
    balance['BTC']['free']
  • 考虑交易手续费
6. "ExchangeNotAvailable"
  • 解决方案:检查交易所状态/维护公告
  • 延迟后重试
7. SSL/证书错误
  • 解决方案:更新certifi:
    pip install --upgrade certifi
8. 性能缓慢
  • 解决方案:安装性能增强包:
    • pip install orjson
      (更快的JSON解析)
    • pip install coincurve
      (更快的签名)

Debugging

调试

python
undefined
python
undefined

Enable verbose logging

启用详细日志

exchange.verbose = True
exchange.verbose = True

Check exchange capabilities

检查交易所功能支持

print(exchange.has)
print(exchange.has)

{

{

'fetchTicker': True,

'fetchTicker': True,

'fetchOrderBook': True,

'fetchOrderBook': True,

'createOrder': True,

'createOrder': True,

...

...

}

}

Check market information

检查市场信息

print(exchange.markets['BTC/USDT'])
print(exchange.markets['BTC/USDT'])

Check last request/response

检查最后一次请求/响应

print(exchange.last_http_response) print(exchange.last_json_response)
undefined
print(exchange.last_http_response) print(exchange.last_json_response)
undefined

Learn More

更多资源