返回目录
开源项目数字货币类新手

GitHub - ccxt/ccxt: A unified trading API with more than 100 crypto exchanges and prediction markets in JavaScript / TypeScript / Python / C

CCXT – CryptoCurrency eXchange Trading Library A crypto trading API with more than 100 exchanges and prediction markets in JavaScript / TypeScript / Python / C# / PHP / Go / Java / Rust. Install · Usage · Manual · FAQ · Examples · Contributing · Disclaimer ·

0 次阅读2026/09/10 发布
GitHub - ccxt/ccxt: A unified trading API with more than 100 crypto exchanges and prediction markets in JavaScript / TypeScript / Python / C 来源图片

社区作者 · zZz

它解决什么问题

CCXT – CryptoCurrency eXchange Trading Library

A crypto trading API with more than 100 exchanges and prediction markets in JavaScript / TypeScript / Python / C# / PHP / Go / Java / Rust.

Install · Usage · Manual · FAQ · Examples · Contributing · Disclaimer · Social

The CCXT library is used to connect and trade with cryptocurrency exchanges worldwide.

It provides quick access to market data for storage, analysis, visualization, indicator development, algorithmic trading, strategy backtesting, bot programming, and related software engineering.

It is intended to be used by coders, developers, technically-skilled traders, data-scientists and financial analysts for building trading algorithms.

Current feature list:

  • supports 100+ cryptocurrency exchanges and prediction markets:
  • Polymarket
  • Kalshi
  • Hyperliquid
  • Limitless
  • Myriad
  • more coming soon!
  • implements public and private APIs, both REST and WebSocket
  • optionally normalizes data for cross-exchange analytics and arbitrage
  • has an out of the box unified API that is extremely easy to integrate
  • ideal for AI agents, LLMs and vibe coding
  • works in Node 18+, Python 3, PHP 8.1+, netstandard2.0/2.1, Go 1.20+, Java 21+ and web browsers

Sponsored Promotion

See Also

  • Freqtrade – leading opensource cryptocurrency algorithmic trading software!
  • OctoBot – cryptocurrency trading bot with an advanced web interface.
  • TokenBot – discover and copy the best algorithmic traders in the world.

Certified Cryptocurrency Exchanges

logo id name ver type certified pro discount

binance Binance

binanceusdm Binance USDⓈ-M

binancecoinm Binance COIN-M

bybit Bybit

okx OKX

gate Gate

kucoin KuCoin

kucoinfutures KuCoin Futures

bitget Bitget

hyperliquid Hyperliquid

bitmex BitMEX

bingx BingX

htx HTX

mexc MEXC Global

cryptocom Crypto.com

coinex CoinEx

hashkey HashKey Global

woo WOO X

woofipro WOOFI PRO

Supported Cryptocurrency Exchanges

The CCXT library currently supports the following 104 cryptocurrency exchange markets and trading APIs:

logo id name ver type certified pro

alpaca Alpaca

apex Apex

aster Aster

backpack Backpack

bequant Bequant

bigone BigONE

binance Binance

binancecoinm Binance COIN-M

binanceus Binance US

binanceusdm Binance USDⓈ-M

bingx BingX

bit2c Bit2C

bitbank bitbank

bitbns Bitbns

bitfinex Bitfinex

bitflyer bitFlyer

bitget Bitget

bithumb Bithumb

bitmex BitMEX

bitopro BitoPro

bitrue Bitrue

bitso Bitso

bitstamp Bitstamp

bitteam BIT.TEAM

bittrade BitTrade

bitvavo Bitvavo

blockchaincom Blockchain.com

blofin BloFin

btcbox BtcBox

btcmarkets BTC Markets

btcturk BTCTurk

btse BTSE

bullish Bullish

bybit Bybit

bybiteu Bybit EU

bydfi BYDFi

cex CEX.IO

coinbase Coinbase Advanced

coinbaseexchange Coinbase Exchange

coinbaseinternational Coinbase International

coincheck Coincheck

coinex CoinEx

coinmate CoinMate

coinone CoinOne

coinsph Coins.ph

coinspot CoinSpot

cryptocom Crypto.com

cryptomus Cryptomus

deepcoin DeepCoin

delta Delta Exchange

deribit Deribit

derive Derive

digifinex DigiFinex

dydx dYdX

extended Extended

fmfwio FMFW.io

foxbit Foxbit

gate Gate

gateeu Gate EU

gemini Gemini

grvt GRVT

hashkey HashKey Global

hibachi Hibachi

hitbtc HitBTC

hollaex HollaEx

htx HTX

hyperliquid Hyperliquid

independentreserve Independent Reserve

indodax INDODAX

kraken Kraken

krakenfutures Kraken Futures

kucoin KuCoin

kucoinfutures KuCoin Futures

latoken Latoken

lbank LBank

lighter Lighter

luno Luno

mercado Mercado Bitcoin

mexc MEXC Global

modetrade Mode Trade

mudrex Mudrex

myokx MyOKX (EEA)

nado Nado

ndax NDAX

okx OKX

okxus OKX (US)

onetrading One Trading

p2b p2b

pacifica Pacifica

paradex Paradex

paymium Paymium

phemex Phemex

poloniex Poloniex

revolutx Revolut X

tokocrypto Tokocrypto

toobit Toobit

upbit Upbit

weex Weex

whitebit WhiteBit

woo WOO X

woofipro WOOFI PRO

xt XT

zaif Zaif

zebpay Zebpay

The list above is updated frequently, new crypto markets, exchanges, bug fixes, and API endpoints are introduced on a regular basis. See the Manual for more details.

If you can't find a cryptocurrency exchange in the list above and want it to be added, post a link to it by opening an issue here on GitHub or send us an email.

The library is under MIT license , that means it's absolutely free for any developer to build commercial and opensource software on top of it, but use it at your own risk with no warranties, as is.

Prediction Market Exchanges

The CCXT library currently supports the following 7 prediction market exchanges and trading APIs:

logo id name ver

binance Binance

hyperliquid Hyperliquid

kalshi Kalshi

limitless Limitless

myriad Myriad

opinion Opinion

polymarket Polymarket

Builder Code Exchanges

logo id name ver type certified pro

aster Aster

extended Extended

grvt GRVT

hyperliquid Hyperliquid

lighter Lighter

nado Nado

pacifica Pacifica

CCXT participates in builder programs with the exchanges listed above, which means that in order to support the CCXT project users pay a small fee (1 bps) on top of the exchanges' fees when using the exchanges' API through CCXT.

This is optional and can be disabled by setting exchange.options['builderFee'] = False . For all other exchanges no additional fee is charged and in some cases you receive discounts or special conditions by using CCXT.

Install

The easiest way to install the CCXT library is to use a package manager:

  • ccxt in NPM (JavaScript / Node v7.6+)
  • ccxt in PyPI (Python 3.7.0+)
  • ccxt in Packagist/Composer (PHP 8.1+)
  • ccxt in Nuget (netstandard 2.0)
  • ccxt in GO
  • ccxt in Java (Java 21+, Gradle)
  • ccxt in Crates.io (Rust, Cargo)

This library is shipped as an all-in-one module implementation with minimalistic dependencies and requirements:

  • js/ in JavaScript
  • python/ in Python (generated from TS)
  • php/ in PHP (generated from TS)
  • cs/ in C# (generated from TS)
  • go/ in Go (generated from TS)
  • java/ in Java (generated from TS)
  • rust/ in Rust (generated from TS)

You can also clone it into your project directory from ccxt GitHub repository :

命令
git clone https://github.com/ccxt/ccxt.git # including 1GB of commit history

or

命令
git clone https://github.com/ccxt/ccxt.git --depth 1 # avoid downloading 1GB of commit history

JavaScript (NPM)

JavaScript version of CCXT works in both Node and web browsers. Requires ES6 and async/await syntax support (Node 7.6.0+). When compiling with Rspack (or Webpack) and Babel, make sure it is not excluded in your babel-loader config.

ccxt in NPM

命令
npm install ccxt

//cjs var ccxt = require ( 'ccxt' ) console . log ( ccxt . exchanges ) // print all available exchanges

//esm import { version , exchanges } from 'ccxt' ; console . log ( version , Object . keys ( exchanges ) ) ;

JavaScript (for use with the <script> tag):

All-in-one browser bundle (dependencies included), served from a CDN of your choice:

CDNs are not updated in real-time and may have delays. Defaulting to the most recent version without specifying the version number is not recommended. Please, keep in mind that we are not responsible for the correct operation of those CDN servers.

< script type =" text/javascript " src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/ccxt.browser.min.js " > </ script >

Creates a global ccxt object:

console . log ( ccxt . exchanges ) // print all available exchanges

命令
Python

ccxt in PyPI

命令
pip install ccxt

import ccxt print ( ccxt . exchanges ) # print a list of all available exchange classes

The library supports concurrent asynchronous mode with asyncio and async/await in Python 3.7.0+

import ccxt . async_support as ccxt # link against the asynchronous version of ccxt

orjson support

CCXT also supports orjson for parsing JSON since it is much faster than the builtin library. This is especially important when using websockets because some exchanges return big messages that need to be parsed and dispatched as quickly as possible.

However, orjson is not enabled by default because it is not supported by every python interpreter. If you want to opt-in, you just need to install it ( pip install orjson ) on your local environment. CCXT will detect the installion and pick it up automatically.

ECDSA Support

Some exchanges, such as Hyperliquid, Binance, and Paradex use ECDSA for request signing. By default, CCXT includes a pure Python ECDSA implementation that ensures compatibility across all environments.

However, this implementation may not meet the performance requirements of latency-sensitive applications.

To address this, CCXT also supports the Coincurve library, which dramatically reduces signing time from approximately 45 ms to under 0.05 ms.

For optimal performance, we recommend installing Coincurve via:

命令
pip install coincurve

Once installed, CCXT will automatically detect and use it.

PHP

ccxt in PHP with Packagist/Composer (PHP 8.1+)

It requires common PHP modules:

可复制命令
cURL
  • mbstring (using UTF-8 is highly recommended)
  • PCRE
  • iconv
  • gmp

include " ccxt.php " ; var_dump (\ ccxt \Exchange:: $ exchanges ); // print a list of all available exchange classes

The library supports concurrent asynchronous mode using tools from ReactPHP in PHP 8.1+. Read the Manual for more details.

.net/C#

ccxt in C# with Nuget (netstandard 2.0 and netstandard 2.1)

using ccxt ; Console . WriteLine ( ccxt . Exchanges ) // check this later

命令
Go

ccxt in GO with PKG

命令
go install github.com/ccxt/ccxt/go/v4@latest

import "ccxt" fmt . Println ( ccxt . Exchanges )

Java

Java version of CCXT requires Java 21+ and uses Gradle as its build system.

Add the CCXT library as a local dependency in your build.gradle.kts :

dependencies { implementation( " io.github.ccxt:ccxt:4.5.52 " ) }

Or clone and build from source:

命令
git clone https://github.com/ccxt/ccxt.git --depth 1
命令
cd ccxt/java
命令
./gradlew :lib:build

import io . github . ccxt . exchanges . Binance ; import io . github . ccxt . types . Ticker ;

Binance exchange = new Binance (); exchange . loadMarkets ( false );

Ticker ticker = exchange . fetchTicker ( "BTC/USDT" ); System . out . println ( ticker . symbol + " " + ticker . last );

Each exchange has its own typed subclass with strongly-typed return values. Every typed method ships both a blocking sync and a non-blocking CompletableFuture -returning async overload — pick the idiom that fits your call site:

// Sync — blocks until the response arrives Ticker ticker = exchange . fetchTicker ( "BTC/USDT" );

// Async — returns immediately, completes when the response arrives CompletableFuture < Ticker > future = exchange . fetchTickerAsync ( "BTC/USDT" , null ); future . thenAccept ( t -> System . out . println ( t . last ));

WebSocket support is available via the pro exchange classes, with the same sync/async symmetry — watchTicker blocks for one update; watchTickerAsync returns a CompletableFuture<Ticker> you can compose:

import io . github . ccxt . exchanges . pro . Binance ;

var exchange = new Binance (); exchange . loadMarkets ( false );

// Sync — blocks for one update Ticker tick = exchange . watchTicker ( "BTC/USDT" );

// Async — returns a typed CompletableFuture (composable with allOf, anyOf, etc.) CompletableFuture < Ticker > future = exchange . watchTickerAsync ( "BTC/USDT" , null );

See java/examples/ for more usage examples.

Rust

ccxt in Rust with crates.io ( docs.rs )

命令
cargo add ccxt tokio --features tokio/full
命令
cargo add ccxt-pro

[ dependencies ] ccxt = " 4.5.75 " ccxt-pro = " 4.5.75 " tokio = { version = " 1 " , features = [ " full " ] }

ccxt carries the REST exchanges; ccxt-pro adds the WebSocket ( watch* ) ones and is only needed if you stream. Both are async and expect a Tokio runtime.

use ccxt :: { Binance , Params } ;

let mut exchange = Binance :: new ( None ) ; exchange . load_markets ( false ) . await ;

let ticker = exchange . fetch_ticker ( "BTC/USDT" , Params :: none ( ) ) . await ? ; println ! ( "{} {:?}" , ticker . symbol , ticker . last ) ;

命令
Docker

You can get CCXT installed in a container along with all the supported languages and dependencies. This may be useful if you want to contribute to CCXT (e.g. run the build scripts and tests — please see the Contributing document for the details on that).

Using docker-compose (in the cloned CCXT repository):

docker-compose run --rm ccxt

You don't need the Docker image if you're not going to develop CCXT. If you just want to use CCXT – just install it as a regular package into your project.

AI Assistant Support

CCXT provides language-specific skills for AI coding assistants (Claude Code, Cursor, Copilot, Windsurf, Codex, and 30+ others):

命令
npx skills add ccxt/ccxt

See AI Skills documentation and llms.txt for more details.

Usage

Intro

The CCXT library consists of a public part and a private part. Anyone can use the public part immediately after installation. Public APIs provide unrestricted access to public information for all exchange markets without the need to register a user account or have an API key.

Public APIs include the following:

  • market data
  • instruments/trading pairs
  • price feeds (exchange rates)
  • order books
  • trade history
  • tickers
  • OHLC(V) for charting
  • other public endpoints

In order to trade with private APIs you need to obtain API keys from an exchange's website. It usually means signing up to the exchange and creating API keys for your account. Some exchanges require personal info or identification.

Sometimes verification may be necessary as well. In this case you will need to register yourself, this library will not create accounts or API keys for you. Some exchanges expose API endpoints for registering an account, but most exchanges don't.

You will have to sign up and create API keys on their websites.

Private APIs allow the following:

  • manage personal account info
  • query account balances
  • trade by making market and limit orders
  • deposit and withdraw fiat and crypto funds
  • query personal orders
  • get ledger history
  • transfer funds between accounts
  • use merchant services

This library implements full public and private REST and WebSocket APIs for all exchanges in TypeScript, JavaScript, PHP and Python.

The CCXT library supports both camelcase notation (preferred in TypeScript and JavaScript) and underscore notation (preferred in Python and PHP), therefore all methods can be called in either notation or coding style in any language.

// both of these notations work in JavaScript/Python/PHP exchange . methodName ( ) // camelcase pseudocode exchange . method_name ( ) // underscore pseudocode

Read the Manual and see examples for more details.

JavaScript

CCXT now supports ESM and CJS modules

CJS

// cjs example 'use strict' ; const ccxt = require ( 'ccxt' ) ;

( async function ( ) { let kraken = new ccxt . kraken ( ) let bitfinex = new ccxt . bitfinex ( { verbose : true } ) let huobipro = new ccxt . huobipro ( ) let okcoinusd = new ccxt . okcoin ( { apiKey : 'YOUR_PUBLIC_API_KEY' , secret : 'YOUR_SECRET_PRIVATE_KEY' , } )

const exchangeId = 'binance' , exchangeClass = ccxt [ exchangeId ] , exchange = new exchangeClass ( { 'apiKey' : 'YOUR_API_KEY' , 'secret' : 'YOUR_SECRET' , } )

console . log ( kraken . id , await kraken . loadMarkets ( ) ) console . log ( bitfinex . id , await bitfinex . loadMarkets ( ) ) console . log ( huobipro . id , await huobipro . loadMarkets ( ) )

console . log ( kraken . id , await kraken . fetchOrderBook ( kraken . symbols [ 0 ] ) ) console . log ( bitfinex . id , await bitfinex . fetchTicker ( 'BTC/USD' ) ) console . log ( huobipro . id , await huobipro . fetchTrades ( 'ETH/USDT' ) )

console . log ( okcoinusd . id , await okcoinusd . fetchBalance ( ) )

// sell 1 BTC/USD for market price, sell a bitcoin for dollars immediately console . log ( okcoinusd . id , await okcoinusd . createMarketSellOrder ( 'BTC/USD' , 1 ) )

// buy 1 BTC/USD for $2500, you pay $2500 and receive ฿1 when the order is closed console . log ( okcoinusd . id , await okcoinusd . createLimitBuyOrder ( 'BTC/USD' , 1 , 2500.00 ) )

// pass/redefine custom exchange-specific order params: type, amount, price or whatever // use a custom order type bitfinex . createLimitSellOrder ( 'BTC/USD' , 1 , 10 , { 'type' : 'trailing-stop' } )

} ) ( ) ;

ESM

//esm example import { version , binance } from 'ccxt' ;

console . log ( version ) ; const exchange = new binance ( ) ; const ticker = await exchange . fetchTicker ( 'BTC/USDT' ) ; console . log ( ticker ) ;

命令
Python

coding=utf-8

import ccxt

hitbtc = ccxt . hitbtc ({ 'verbose' : True }) bitmex = ccxt . bitmex () huobipro = ccxt . huobipro () exmo = ccxt . exmo ({ 'apiKey' : 'YOUR_PUBLIC_API_KEY' , 'secret' : 'YOUR_SECRET_PRIVATE_KEY' , }) kraken = ccxt .

kraken ({ 'apiKey' : 'YOUR_PUBLIC_API_KEY' , 'secret' : 'YOUR_SECRET_PRIVATE_KEY' , })

exchange_id = 'binance' exchange_class = getattr ( ccxt , exchange_id ) exchange = exchange_class ({ 'apiKey' : 'YOUR_API_KEY' , 'secret' : 'YOUR_SECRET' , })

hitbtc_markets = hitbtc . load_markets ()

print ( hitbtc . id , hitbtc_markets ) print ( bitmex . id , bitmex . load_markets ()) print ( huobipro . id , huobipro . load_markets ())

print ( hitbtc . fetch_order_book ( hitbtc . symbols [ 0 ])) print ( bitmex . fetch_ticker ( 'BTC/USD' )) print ( huobipro . fetch_trades ( 'LTC/USDT' ))

print ( exmo . fetch_balance ())

sell one ฿ for market price and receive $ right now

print ( exmo . id , exmo . create_market_sell_order ( 'BTC/USD' , 1 ))

limit buy BTC/EUR, you pay €2500 and receive ฿1 when the order is closed

print ( exmo . id , exmo . create_limit_buy_order ( 'BTC/EUR' , 1 , 2500.00 ))

pass/redefine custom exchange-specific order params: type, amount, price, flags, etc...

kraken . create_market_buy_order ( 'BTC/USD' , 1 , { 'trading_agreement' : 'agree' })

PHP

include ' ccxt.php ' ;

$ poloniex = new \ ccxt \ poloniex (); $ bittrex = new \ ccxt \ bittrex ( array ( ' verbose ' => true )); $ quoinex = new \ ccxt \ quoinex (); $ zaif = new \ ccxt \ zaif ( array ( ' apiKey ' => ' YOUR_PUBLIC_API_KEY ' , ' secret ' => ' YOUR_SECRET_PRIVATE_KEY ' , )); $ hitbtc = new \ ccxt \ hitbtc ( array ( ' apiKey ' => ' YOUR_PUBLIC_API_KEY ' , ' secret ' => ' YOUR_SECRET_PRIVATE_KEY ' , ));

$ exchange_id = ' binance ' ; $ exchange_class = "\\ ccxt \\ $ exchange_id " ; $ exchange = new $ exchange_class ( array ( ' apiKey ' => ' YOUR_API_KEY ' , ' secret ' => ' YOUR_SECRET ' , ));

$ poloniex_markets = $ poloniex -> load_markets ();

var_dump ( $ poloniex_markets ); var_dump ( $ bittrex -> load_markets ()); var_dump ( $ quoinex -> load_markets ());

var_dump ( $ poloniex -> fetch_order_book ( $ poloniex -> symbols [ 0 ])); var_dump ( $ bittrex -> fetch_trades ( ' BTC/USD ' )); var_dump ( $ quoinex -> fetch_ticker ( ' ETH/EUR ' )); var_dump ( $ zaif -> fetch_ticker ( ' BTC/JPY ' ));

var_dump ( $ zaif -> fetch_balance ());

// sell 1 BTC/JPY for market price, you pay ¥ and receive ฿ immediately var_dump ( $ zaif -> id , $ zaif -> create_market_sell_order ( ' BTC/JPY ' , 1 ));

// buy BTC/JPY, you receive ฿1 for ¥285000 when the order closes var_dump ( $ zaif -> id , $ zaif -> create_limit_buy_order ( ' BTC/JPY ' , 1 , 285000 ));

// set a custom user-defined id to your order $ hitbtc -> create_order ( ' BTC/USD ' , ' limit ' , ' buy ' , 1 , 3000 , array ( ' clientOrderId ' => ' 123 ' ));

.net/C#

using ccxt ; // importing ccxt namespace Project ; class Project { public async static Task CreateOrder ( ) { var exchange = new Binance ( ) ; exchange . apiKey = "my api key" ; exchange .

secret = "my secret" ; // always use the capitalized method (CreateOrder instead of createOrder) var order = await exchange . CreateOrder ( "BTC/USDT" , "limit" , "buy" , 1 , 50 ) ; Console . WriteLine ( "Placed Order, order id: " + order . id ) ; } }

命令
Go

package main import ( "github.com/ccxt/ccxt/go/v4/go" "fmt" )

func main () { exchange := ccxt . NewBinance ( map [ string ] interface {}{ "apiKey" : "MY KEY" , "secret" : "MY SECRET" , }) orderParams := map [ string ] interface {}{ "clientOrderId" : "myOrderId68768678" , }

exchange . LoadMarkets ()

order , err := exchange . CreateOrder ( "BTC/USDT" , "limit" , "buy" , 0.001 , ccxt . WithCreateOrderPrice ( 6000 ), ccxt . WithCreateOrderParams ( orderParams )) if err != nil { if ccxtError , ok := err .( * ccxt. Error ); ok { if ccxtError .

Type == "InvalidOrder" { fmt . Println ( "Invalid order" ) } else { fmt . Println ( "Some other error" ) } } } else { fmt . Println ( * order . Id ) }

// fetching OHLCV ohlcv , err := exchange . FetchOHLCV ( "BTC/USDT" , ccxt . WithFetchOHLCVTimeframe ( "5m" ), ccxt . WithFetchOHLCVLimit ( 100 ))

if err != nil { fmt . Println ( "Error: " , err ) } else { fmt . Println ( "Got OHLCV!" ) } }

Optional parameters

Unlike Javascript/Python/PHP/C# Go does not support "traditional" optional parameters like function a(optional = false) .

However, the CCXT language and structure have some methods with optional params, and since the Go language is transpiled from the Typescript source, we had to find a way of representing them.

We have decided to "go" (pun intended) with Option structs and the WithX methods.

For example, this function FetchMyTrades supports 4 different "optional" parameters, symbol, since, limit, and params.

func ( this * Binance ) FetchMyTrades ( options ... FetchMyTradesOptions ) ([] Trade , error )

And we can provide them by doing

trades , error := exchange . FetchMyTrades ( ccxt . withFetchMyTradesSymbol ( "BTC/USDT" ), ccxt . WithFetchOHLCVLimit ( 5 ), ccxt . WithFetchMyTradesParams ( orderParams ))

Lastly, just because the signature dictates that some argument like symbol is optional, it will depend from exchange to exchange and you might need to provide it to avoid getting a SymbolRequired error.

You can check different examples in the examples/go folder.

Java

import io . github . ccxt . exchanges . Kraken ; import io . github . ccxt . exchanges . Bitfinex ; import io . github . ccxt . exchanges . Binance ; import io . github . ccxt . types .*;

import java . util . HashMap ; import java . util . Map ;

public class Example { public static void main ( String [] args ) { // Create exchange instances Kraken kraken = new Kraken (); Bitfinex bitfinex = new Bitfinex ();

Map < String , Object > config = new HashMap <>(); config . put ( "apiKey" , "YOUR_API_KEY" ); config . put ( "secret" , "YOUR_SECRET" ); Binance binance = new Binance ( config );

// Load markets kraken . loadMarkets ( false ); binance . loadMarkets ( false );

// Public API OrderBook orderBook = kraken . fetchOrderBook ( "BTC/USDT" ); Ticker ticker = bitfinex . fetchTicker ( "BTC/USD" ); System . out . println ( ticker . symbol + " last=" + ticker . last );

// Fetch OHLCV var candles = binance . fetchOHLCV ( "BTC/USDT" , "1h" , null , 10L , null ); System . out . println ( "Got " + candles . size () + " candles" );

// Private API (requires API keys) Balances balance = binance . fetchBalance (); System . out . println ( "BTC free: " + balance . free . get ( "BTC" ));

// Place a limit buy order Order order = binance . createLimitBuyOrder ( "BTC/USDT" , 0.001 , 50000.0 ); System . out . println ( "Order id: " + order . id + " status: " + order . status );

// Cancel it binance . cancelOrder ( order . id , "BTC/USDT" , null ); } }

Async

All methods are also available as async variants returning CompletableFuture :

import java . util . concurrent . CompletableFuture ;

// Fire multiple requests concurrently CompletableFuture < Ticker > btc = binance . fetchTickerAsync ( "BTC/USDT" , null ); CompletableFuture < Ticker > eth = binance . fetchTickerAsync ( "ETH/USDT" , null ); CompletableFuture . allOf ( btc , eth ).

join (); System . out . println ( "BTC: " + btc . get (). last + " ETH: " + eth . get (). last );

Error handling

Typed sync methods throw the underlying ccxt error directly — no CompletionException unwrap needed. Catch exceptions in standard JDK order (most-specific first), like you would with any other Java library:

import io . github . ccxt . errors .*; import io . github . ccxt . exchanges . Binance ; import io . github . ccxt . types . Order ;

Binance binance = new Binance ( Map . of ( "apiKey" , "." , "secret" , "." )); try { Order order = binance . createOrder ( "BTC/USDT" , "limit" , "buy" , 0.001 , 50000.

0 ); } catch ( InsufficientFunds e ) { // user error — show balance, don't retry } catch ( InvalidOrder e ) { // covers OrderNotFound, DuplicateOrderId, … // user error — fix params } catch ( AuthenticationError e ) { // covers PermissionDenied, AccountSuspended // refresh credentials } catch ( RateLimitExceeded | DDoSProtection e ) { // multi-catch (Java 7+) Thread .

sleep ( 30_000 ); } catch ( NetworkError e ) { // RequestTimeout, ExchangeNotAvailable, … Thread .

sleep ( 2_000 ); // transient — retry } catch ( ExchangeError e ) { // any other exchange-side error // exchange refused } catch ( BaseError e ) { // ccxt catch-all // unknown ccxt error }

For async methods, CompletableFuture wraps thrown errors in CompletionException (JDK behaviour). Use Helpers.unwrap() inside .exceptionally(...) to peel the wrap and pattern-match the real cause:

import io . github . ccxt . Helpers ;

binance . createOrderAsync ( "BTC/USDT" , "limit" , "buy" , 0.001 , 50000.0 ) . thenAccept ( order -> log . info ( "placed " + order . id )) . exceptionally ( throwable -> { Throwable cause = Helpers .

unwrap ( throwable ); return switch ( cause ) { case InsufficientFunds e -> { notifyUser ( e ); yield null ; } case AuthenticationError e -> { refreshCreds (); yield null ; } case RateLimitExceeded e -> { scheduleRetry (); yield null ; } case NetworkError e -> { scheduleRetry (); yield null ; } case BaseError e -> { log .

error ( "ccxt" , e ); yield null ; } default -> throw new java . util . concurrent . CompletionException ( cause ); }; });

The full hierarchy lives under io.github.ccxt.errors — see the Error Handling section of the Manual for the complete tree (NetworkError vs ExchangeError, retry-safe vs user-error categories, etc.).

WebSocket

WebSocket support is available via the pro exchange classes:

import io . github . ccxt . Exchange ; import io . github . ccxt . exchanges . pro . Binance ;

import java . util . concurrent . TimeUnit ;

Exchange exchange = new Binance (); exchange . loadMarkets (). join ();

// stream live ticker updates for ( int i = 0 ; i < 10 ; i ++) { Object ticker = exchange . watchTicker ( "BTC/USDT" ). get ( 30 , TimeUnit . SECONDS ); System . out . println ( ticker ); }

You can check different examples in the java/examples folder.

Rust

Every exchange has a typed wrapper returning native Rust types — Ticker , Order , Market , OrderBook — instead of a dynamic value. Methods are async and return Result<T, ExchangeError> .

use ccxt :: { Binance , Config , Params } ;

[ tokio :: main ]

async fn main ( ) -> Result < ( ) , Box < dyn std :: error :: Error > > { let mut exchange = Binance :: with_config ( Config :: new ( ) . api_key ( "MY KEY" ) . secret ( "MY SECRET" ) , ) ; exchange . load_markets ( false ) . await ;

let order = exchange . create_order ( "BTC/USDT" , "limit" , "buy" , 0.001 , Some ( 50000.0 ) , Params :: none ( ) ) . await ? ; println ! ( "{:?}" , order . id ) ; Ok ( ( ) ) }

Configuration and parameters

Neither construction nor the trailing params argument requires touching a dynamic value — both are builders over Rust primitives. Config nests options exactly as the other bindings do.

use ccxt :: { Binance , Config , Params } ;

let mut exchange = Binance :: with_config ( Config :: new ( ) . api_key ( "MY KEY" ) . secret ( "MY SECRET" ) . sandbox ( true ) . enable_rate_limit ( true ) . option_str ( "defaultType" , "swap" ) . option ( "fetchMarkets" , Params :: new ( ) .

with_strs ( "types" , & [ "spot" , "line

— 本文由 AI 根据公开来源辅助整理,命令、版本与许可证请在使用前到原始页面复核。

安装 / 开始使用

Install · Usage · Manual · FAQ · Examples · Contributing · Disclaimer · Social The CCXT library is used to connect and trade with cryptocurrency exchanges worldwide.

It provides quick access to market data for storage, analysis, visualization, indicator development, algorithmic trading, strategy backtesting, bot programming, and related software engineering.

It is intended to be used by coders, developers, technically-skilled traders, data-scientists and financial analysts for building trading algorithms. Current feature list:

Sponsored Promotion See Also

Certified Cryptocurrency Exchanges logo id name ver type certified pro discount binance Binance binanceusdm Binance USDⓈ-M binancecoinm Binance COIN-M bybit Bybit okx OKX gate Gate kucoin KuCoin kucoinfutures KuCoin Futures bitget Bitget hyperliquid Hyperliquid bitmex BitMEX bingx BingX htx HTX mexc MEXC Global cryptocom Crypto.

com coinex CoinEx hashkey HashKey Global woo WOO X woofipro WOOFI PRO Supported Cryptocurrency Exchanges The CCXT library currently supports the following 104 cryptocurrency exchange markets and trading APIs: logo id name ver type certified pro alpaca Alpaca apex Apex aster Aster backpack Backpack bequant Bequant bigone BigONE binance

  • supports 100+ cryptocurrency exchanges and prediction markets:
  • Polymarket
  • Kalshi
  • Hyperliquid
  • Limitless
  • Myriad
  • more coming soon!
  • implements public and private APIs, both REST and WebSocket
  • optionally normalizes data for cross-exchange analytics and arbitrage
  • has an out of the box unified API that is extremely easy to integrate
  • ideal for AI agents, LLMs and vibe coding
  • works in Node 18+, Python 3, PHP 8.1+, netstandard2.0/2.1, Go 1.20+, Java 21+ and web browsers
  • Freqtrade – leading opensource cryptocurrency algorithmic trading software!
  • OctoBot – cryptocurrency trading bot with an advanced web interface.
  • TokenBot – discover and copy the best algorithmic traders in the world.

来源教程配图

Enjoy VIP+2 tier on Bitget when migrating from BitMEX
配图 1 · Enjoy VIP+2 tier on Bitget when migrating from BitMEX查看原图
Unlock VIP3 on BTSE and earn up to $2,500 in the BTSE × CCXT Trading Competition
配图 2 · Unlock VIP3 on BTSE and earn up to $2,500 in the BTSE × CCXT Trading Competition查看原图
Freqtrade
配图 3 · Freqtrade查看原图
OctoBot
配图 4 · OctoBot查看原图
TokenBot
配图 5 · TokenBot查看原图
binance
配图 6 · binance查看原图
binanceusdm
配图 7 · binanceusdm查看原图
binancecoinm
配图 8 · binancecoinm查看原图

适用场景

学习研究
开源项目实践