Loading...
Loading...
CCXT cryptocurrency exchange library for PHP developers. Covers both REST API (standard) and WebSocket API (real-time). Helps install CCXT, connect to exchanges, fetch market data, place orders, stream live tickers/orderbooks, handle authentication, and manage errors in PHP 8.1+. Use when working with crypto exchanges in PHP projects, trading bots, or web applications. Supports both sync and async (ReactPHP) usage.
npx skill4agent add ccxt/ccxt ccxt-phpcomposer require ccxt/ccxt<?php
date_default_timezone_set('UTC'); // Required!
require_once 'vendor/autoload.php';
$exchange = new \ccxt\binance();
$exchange->load_markets();
$ticker = $exchange->fetch_ticker('BTC/USDT');
print_r($ticker);<?php
use function React\Async\await;
date_default_timezone_set('UTC');
require_once 'vendor/autoload.php';
$exchange = new \ccxt\async\binance();
$ticker = await($exchange->fetch_ticker('BTC/USDT'));
print_r($ticker);<?php
use function React\Async\await;
use function React\Async\async;
date_default_timezone_set('UTC');
require_once 'vendor/autoload.php';
$exchange = new \ccxt\pro\binance();
while (true) {
$ticker = await($exchange->watch_ticker('BTC/USDT'));
print_r($ticker); // Live updates!
}
await($exchange->close());| Mode | REST | WebSocket |
|---|---|---|
| Sync | | (WebSocket requires async) |
| Async | | |
| 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) |
| Best for | Trading, account management | Price monitoring, arbitrage detection |
<?php
date_default_timezone_set('UTC');
require_once 'vendor/autoload.php';
// Public API (no authentication)
$exchange = new \ccxt\binance([
'enableRateLimit' => true // Recommended!
]);
// Private API (with authentication)
$exchange = new \ccxt\binance([
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
'enableRateLimit' => true
]);<?php
use function React\Async\await;
$exchange = new \ccxt\async\binance([
'enableRateLimit' => true
]);
$ticker = await($exchange->fetch_ticker('BTC/USDT'));<?php
use function React\Async\await;
// Public WebSocket
$exchange = new \ccxt\pro\binance();
// Private WebSocket (with authentication)
$exchange = new \ccxt\pro\binance([
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET'
]);
// Always close when done
await($exchange->close());// Load all available trading pairs
$exchange->load_markets();
// Access market information
$btc_market = $exchange->market('BTC/USDT');
print_r($btc_market['limits']['amount']['min']); // Minimum order amount// Single ticker
$ticker = $exchange->fetch_ticker('BTC/USDT');
print_r($ticker['last']); // Last price
print_r($ticker['bid']); // Best bid
print_r($ticker['ask']); // Best ask
print_r($ticker['volume']); // 24h volume
// Multiple tickers (if supported)
$tickers = $exchange->fetch_tickers(['BTC/USDT', 'ETH/USDT']);// Full orderbook
$orderbook = $exchange->fetch_order_book('BTC/USDT');
print_r($orderbook['bids'][0]); // [price, amount]
print_r($orderbook['asks'][0]); // [price, amount]
// Limited depth
$orderbook = $exchange->fetch_order_book('BTC/USDT', 5); // Top 5 levels// Buy limit order
$order = $exchange->create_limit_buy_order('BTC/USDT', 0.01, 50000);
print_r($order['id']);
// Sell limit order
$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);// Buy market order
$order = $exchange->create_market_buy_order('BTC/USDT', 0.01);
// Sell market order
$order = $exchange->create_market_sell_order('BTC/USDT', 0.01);
// Generic market order
$order = $exchange->create_order('BTC/USDT', 'market', 'sell', 0.01);$balance = $exchange->fetch_balance();
print_r($balance['BTC']['free']); // Available balance
print_r($balance['BTC']['used']); // Balance in orders
print_r($balance['BTC']['total']); // Total balance// Open orders
$open_orders = $exchange->fetch_open_orders('BTC/USDT');
// Closed orders
$closed_orders = $exchange->fetch_closed_orders('BTC/USDT');
// All orders (open + closed)
$all_orders = $exchange->fetch_orders('BTC/USDT');
// Single order by ID
$order = $exchange->fetch_order($order_id, 'BTC/USDT');// Recent public trades
$trades = $exchange->fetch_trades('BTC/USDT', null, 10);
// Your trades (requires authentication)
$my_trades = $exchange->fetch_my_trades('BTC/USDT');// Cancel single order
$exchange->cancel_order($order_id, 'BTC/USDT');
// Cancel all orders for a symbol
$exchange->cancel_all_orders('BTC/USDT');<?php
use function React\Async\await;
$exchange = new \ccxt\pro\binance();
while (true) {
$ticker = await($exchange->watch_ticker('BTC/USDT'));
print_r($ticker['last']);
}
await($exchange->close());<?php
use function React\Async\await;
$exchange = new \ccxt\pro\binance();
while (true) {
$orderbook = await($exchange->watch_order_book('BTC/USDT'));
print_r('Best bid: ' . $orderbook['bids'][0][0]);
print_r('Best ask: ' . $orderbook['asks'][0][0]);
}
await($exchange->close());<?php
use function React\Async\await;
$exchange = new \ccxt\pro\binance();
while (true) {
$trades = await($exchange->watch_trades('BTC/USDT'));
foreach ($trades as $trade) {
print_r($trade['price'] . ' ' . $trade['amount'] . ' ' . $trade['side']);
}
}
await($exchange->close());<?php
use function React\Async\await;
$exchange = new \ccxt\pro\binance([
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET'
]);
while (true) {
$orders = await($exchange->watch_orders('BTC/USDT'));
foreach ($orders as $order) {
print_r($order['id'] . ' ' . $order['status'] . ' ' . $order['filled']);
}
}
await($exchange->close());<?php
use function React\Async\await;
$exchange = new \ccxt\pro\binance([
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET'
]);
while (true) {
$balance = await($exchange->watch_balance());
print_r('BTC: ' . $balance['BTC']['total']);
}
await($exchange->close());fetchTicker(symbol)fetchTickers([symbols])fetchBidsAsks([symbols])fetchLastPrices([symbols])fetchMarkPrices([symbols])fetchOrderBook(symbol, limit)fetchOrderBooks([symbols])fetchL2OrderBook(symbol)fetchL3OrderBook(symbol)fetchTrades(symbol, since, limit)fetchMyTrades(symbol, since, limit)fetchOrderTrades(orderId, symbol)fetchOHLCV(symbol, timeframe, since, limit)fetchIndexOHLCV(symbol, timeframe)fetchMarkOHLCV(symbol, timeframe)fetchPremiumIndexOHLCV(symbol, timeframe)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)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)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)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)fetchPosition(symbol)fetchPositions([symbols])fetchPositionsForSymbol(symbol)fetchPositionHistory(symbol, since, limit)fetchPositionsHistory(symbols, since, limit)fetchPositionMode(symbol)setPositionMode(hedged, symbol)closePosition(symbol, side)closeAllPositions()fetchFundingRate(symbol)fetchFundingRates([symbols])fetchFundingRateHistory(symbol, since, limit)fetchFundingHistory(symbol, since, limit)fetchFundingInterval(symbol)fetchSettlementHistory(symbol, since, limit)fetchMySettlementHistory(symbol, since, limit)fetchOpenInterest(symbol)fetchOpenInterests([symbols])fetchOpenInterestHistory(symbol, timeframe, since, limit)fetchLiquidations(symbol, since, limit)fetchMyLiquidations(symbol, since, limit)fetchOption(symbol)fetchOptionChain(code)fetchGreeks(symbol)fetchVolatilityHistory(code, since, limit)fetchUnderlyingAssets()fetchTradingFee(symbol)fetchTradingFees([symbols])fetchTradingLimits([symbols])fetchTransactionFee(code)fetchTransactionFees([codes])fetchDepositWithdrawFee(code)fetchDepositWithdrawFees([codes])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(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)fetchMarkets()fetchCurrencies()fetchTime()fetchStatus()fetchBorrowInterest(code, symbol, since, limit)fetchLongShortRatio(symbol, timeframe, since, limit)fetchLongShortRatioHistory(symbol, timeframe, since, limit)watch*watchTicker(symbol)watchTickers([symbols])watchOrderBook(symbol)watchOrderBookForSymbols([symbols])watchTrades(symbol)watchOHLCV(symbol, timeframe)watchBidsAsks([symbols])watchBalance()watchOrders(symbol)watchMyTrades(symbol)watchPositions([symbols])watchPositionsForSymbol(symbol)create*cancel*edit*fetchMy*fetchBalancefetchLedgerfetchAccountswithdrawtransferdepositwatchBalancewatchOrderswatchMyTradeswatchPositions// 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,
// ...
// }fetch*watch*create*cancel*edit*set**Ws// 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'exchange.httpsProxy = 'https://proxy:8080'
// WebSocket connections will use this proxyexchange.httpProxy = 'http://localhost:8080'
try {
await exchange.fetchTicker('BTC/USDT')
console.log('Proxy working!')
} catch (error) {
console.error('Proxy connection failed:', error)
}*WscreateOrderWscreateLimitOrderWscreateMarketOrderWscreateLimitBuyOrderWscreateLimitSellOrderWscreateMarketBuyOrderWscreateMarketSellOrderWscreateStopLimitOrderWscreateStopMarketOrderWscreateStopLossOrderWscreateTakeProfitOrderWscreateTrailingAmountOrderWscreateTrailingPercentOrderWscreatePostOnlyOrderWscreateReduceOnlyOrderWseditOrderWscancelOrderWscancelOrdersWscancelAllOrdersWsfetchOrderWsfetchOrdersWsfetchOpenOrdersWsfetchClosedOrdersWsfetchMyTradesWsfetchBalanceWsfetchPositionWsfetchPositionsWsfetchPositionsForSymbolWsfetchTradingFeesWs*Wsconst order = await exchange.createOrder('BTC/USDT', 'limit', 'buy', 0.01, 50000)const order = await exchange.createOrderWs('BTC/USDT', 'limit', 'buy', 0.01, 50000)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)
}<?php
// During instantiation (recommended)
$exchange = new \ccxt\binance([
'apiKey' => getenv('BINANCE_API_KEY'),
'secret' => getenv('BINANCE_SECRET'),
'enableRateLimit' => true
]);
// After instantiation
$exchange->apiKey = getenv('BINANCE_API_KEY');
$exchange->secret = getenv('BINANCE_SECRET');try {
$balance = $exchange->fetch_balance();
print_r('Authentication successful!');
} catch (\ccxt\AuthenticationError $e) {
print_r('Invalid API credentials');
}BaseError
├─ NetworkError (recoverable - retry)
│ ├─ RequestTimeout
│ ├─ ExchangeNotAvailable
│ ├─ RateLimitExceeded
│ └─ DDoSProtection
└─ ExchangeError (non-recoverable - don't retry)
├─ AuthenticationError
├─ InsufficientFunds
├─ InvalidOrder
└─ NotSupported<?php
try {
$ticker = $exchange->fetch_ticker('BTC/USDT');
} catch (\ccxt\NetworkError $e) {
echo 'Network error - retry: ' . $e->getMessage();
} catch (\ccxt\ExchangeError $e) {
echo 'Exchange error - do not retry: ' . $e->getMessage();
} catch (\Exception $e) {
echo 'Unknown error: ' . $e->getMessage();
}<?php
try {
$order = $exchange->create_order('BTC/USDT', 'limit', 'buy', 0.01, 50000);
} catch (\ccxt\InsufficientFunds $e) {
echo 'Not enough balance';
} catch (\ccxt\InvalidOrder $e) {
echo 'Invalid order parameters';
} catch (\ccxt\RateLimitExceeded $e) {
echo 'Rate limit hit - wait before retrying';
sleep(1); // Wait 1 second
} catch (\ccxt\AuthenticationError $e) {
echo 'Check your API credentials';
}<?php
function fetch_with_retry($exchange, $max_retries = 3) {
for ($i = 0; $i < $max_retries; $i++) {
try {
return $exchange->fetch_ticker('BTC/USDT');
} catch (\ccxt\NetworkError $e) {
if ($i < $max_retries - 1) {
echo "Retry " . ($i + 1) . "/$max_retries\n";
sleep(1 * ($i + 1)); // Exponential backoff
} else {
throw $e;
}
}
}
}$exchange = new \ccxt\binance([
'enableRateLimit' => true // Automatically throttles requests
]);$exchange->fetch_ticker('BTC/USDT');
usleep($exchange->rateLimit * 1000); // Convert ms to microseconds
$exchange->fetch_ticker('ETH/USDT');print_r($exchange->rateLimit); // Milliseconds between requests// Wrong - will cause errors
<?php
require_once 'vendor/autoload.php';
$exchange = new \ccxt\binance(); // ERROR!
// Correct
<?php
date_default_timezone_set('UTC'); // Required!
require_once 'vendor/autoload.php';
$exchange = new \ccxt\binance();// Wrong - missing leading backslash
$exchange = new ccxt\binance(); // May fail!
// Correct
$exchange = new \ccxt\binance(); // Leading backslash!// Wrong - wastes rate limits
while (true) {
$ticker = $exchange->fetch_ticker('BTC/USDT'); // REST
print_r($ticker['last']);
sleep(1);
}
// Correct - use WebSocket
use function React\Async\await;
$exchange = new \ccxt\pro\binance();
while (true) {
$ticker = await($exchange->watch_ticker('BTC/USDT')); // WebSocket
print_r($ticker['last']);
}// Wrong - memory leak
$exchange = new \ccxt\pro\binance();
$ticker = await($exchange->watch_ticker('BTC/USDT'));
// Forgot to close!
// Correct
$exchange = new \ccxt\pro\binance();
try {
while (true) {
$ticker = await($exchange->watch_ticker('BTC/USDT'));
}
} finally {
await($exchange->close());
}// Check required extensions before running
<?php
$required = ['curl', 'mbstring', 'iconv', 'gmp'];
foreach ($required as $ext) {
if (!extension_loaded($ext)) {
die("Error: $ext extension is not loaded\n");
}
}date_default_timezone_set('UTC');composer require ccxt/ccxt\ccxt\binance'enableRateLimit' => trueapt-get install php-curl php-mbstring php-gmp// Enable verbose logging
$exchange->verbose = true;
// Check exchange capabilities
print_r($exchange->has);
// Array(
// 'fetchTicker' => true,
// 'fetchOrderBook' => true,
// 'createOrder' => true,
// ...
// )
// Check market information
print_r($exchange->markets['BTC/USDT']);
// Check last request/response
print_r($exchange->last_http_response);
print_r($exchange->last_json_response);