ccxt-php — Claude Code skill: features and installation
ccxt-php is a Claude Code skill for using CCXT with PHP cryptocurrency exchange integrations. It covers market queries, order handling, and live data streams.
MIT ★ 44,950 updated 2026-11-18
npx skills add ccxt/ccxt --skill ccxt-php -a claude-codeWhat ccxt-php does
The skill explains how to use CCXT from PHP to load markets, read tickers and order books, place or cancel orders, and retrieve balances and trades. It also covers WebSocket streams for live updates. REST calls can run synchronously or asynchronously with ReactPHP.
Install the library with composer require ccxt/ccxt. The project needs PHP 8.1 or later plus cURL, mbstring, PCRE, and iconv extensions; some exchanges also require gmp. ReactPHP is installed along with CCXT. The examples set the timezone to UTC. Private exchange requests need apiKey and secret.
What it helps with
- connect a PHP project to a cryptocurrency exchange
- retrieve ticker or order-book data through REST
- place limit or market orders and cancel them
- subscribe to live ticker and trade streams
Example prompts for the agent
- Show me how to fetch the
BTC/USDTticker with CCXT in this PHP project. - Write a CCXT example that streams
BTC/USDTupdates over WebSocket. - How do I place a limit order and retrieve the account balance with CCXT?
How to install ccxt-php
1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-php -a claude-code2Manually: put the files in place
~/.claude/skills/ccxt-php/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/ccxt-php/
1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-php -a codex2Manually: put the files in place
.agents/skills/ccxt-php/SKILL.mdFor all projects use ~/.agents/skills/
1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-php -a cursor2Manually: put the files in place
.cursor/skills/ccxt-php/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install ccxt/ccxt .claude/skills/ccxt-php2Manually: put the files in place
.github/skills/ccxt-php/SKILL.md1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-php -a gemini-cli2Platform CLI
gemini skills install https://github.com/ccxt/ccxt --path .claude/skills/ccxt-phpManually: put the files in place
.devin/skills/ccxt-php/SKILL.mdThe legacy .windsurf/skills/ path still works
Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-php -a opencodeClaude.ai
Zip the folder and upload it in Settings → Capabilities → Skills
Step by step, with commands for each platform: How to install skills in Claude Code: five ways
Questions about ccxt-php
How do I install ccxt-php in Claude Code?
Run npx skills add ccxt/ccxt --skill ccxt-php -a claude-code. The skill file is installed at ~/.claude/skills/ccxt-php/SKILL.md.
What does ccxt-php do?
It guides PHP developers through CCXT exchange calls, including REST market data and order operations, plus WebSocket streams for live updates.
What does ccxt-php need to work?
It requires PHP 8.1 or later and the cURL, mbstring, PCRE, and iconv extensions. Some exchanges need gmp, and private requests use apiKey and secret.
Source text
SKILL.md · MIT
---
name: ccxt-php
description: 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.
---
# CCXT for PHP
A comprehensive guide to using CCXT in PHP projects for cryptocurrency exchange integration.
## Installation
### Via Composer (REST and WebSocket)
```bash
composer require ccxt/ccxt
```
### Required PHP Extensions
- cURL
- mbstring (UTF-8)
- PCRE
- iconv
- gmp (for some exchanges)
### Optional for Async/WebSocket
- ReactPHP (installed automatically with ccxt)
## Quick Start
### REST API - Synchronous
```php
<?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);
```
### REST API - Asynchronous (ReactPHP)
```php
<?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);
```
### WebSocket API - Real-time Updates
```php
<?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());
```
## REST vs WebSocket
| Mode | REST | WebSocket |
|------|------|-----------|
| **Sync** | `\ccxt\binance()` | (WebSocket requires async) |
| **Async** | `\ccxt\async\binance()` | `\ccxt\pro\binance()` |
| Feature | REST API | WebSocket API |
|---------|----------|---------------|
| **Use for** | One-time queries, placing orders | Real-time monitoring, live price feeds |
| **Method prefix** | `fetch_*` (fetch_ticker, fetch_order_book) | `watch_*` (watch_ticker, watch_order_book) |
| **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 |
## Creating Exchange Instance
### REST API - Synchronous
```php
<?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
]);
```
### REST API - Asynchronous
```php
<?php
use function React\Async\await;
$exchange = new \ccxt\async\binance([
'enableRateLimit' => true
]);
$ticker = await($exchange->fetch_ticker('BTC/USDT'));
```
### WebSocket API
```php
<?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());
```
## Common REST Operations
### Loading Markets
```php
// 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
```
### Fetching Ticker
```php
// 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['baseVolume']); // 24h volume in base currency (quoteVolume for quote)
// Multiple tickers (if supported)
$tickers = $exchange->fetch_tickers(['BTC/USDT', 'ETH/USDT']);
```
### Fetching Order Book
```php
// 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
```
### Creating Orders
#### Limit Order
```php
// 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);
```
#### Market Order
```php
// 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);
```
### Fetching Balance
```php
$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
```
### Fetching Orders
```php
// 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');
```
### Fetching Trades
```php
// Recent public trades
$trades = $exchange->fetch_trades('BTC/USDT', null, 10);
// Your trades (requires authentication)
$my_trades = $exchange->fetch_my_trades('BTC/USDT');
```
### Canceling Orders
```php
// Cancel single order
$exchange->cancel_order($order_id, 'BTC/USDT');
// Cancel all orders for a symbol
$exchange->cancel_all_orders('BTC/USDT');
```
## WebSocket Operations (Real-time)
### Watching Ticker (Live Price Updates)
```php
<?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());
```
### Watching Order Book (Live Depth Updates)
```php
<?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());
```
### Watching Trades (Live Trade Stream)
```php
<?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());
```
### Watching Your Orders (Live Order Updates)
```php
<?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());
```
### Watching Balance (Live Balance Updates)
```php
<?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());
```
## Testnet, Capabilities, Precision and Pagination
### Testnet / sandbox first
```php
$exchange = new \ccxt\binance(array('apiKey' => '...', 'secret' => '...'));
$exchange->set_sandbox_mode(true); // call right after construction; throws NotSupported if there is no testnet
```
Some venues (binance, bybit, okx, gate, ...) also offer demo trading inside the live API. Always try orders on a testnet (or with the minimum size) before going live.
### Check what an exchange supports
```php
if ($exchange->has['fetchOHLCV']) { /* true | false | 'emulated' */ }
print_r($exchange->features['spot']['createOrder']); // triggerPrice, stopLoss, takeProfit, timeInForce, ...
print_r($exchange->features['swap']['linear']['fetchOHLCV']); // e.g. array('limit' => 500, ...)
```
Note: `has` and `features` keys stay camelCase in every language.
### Respect market precision and limits
```php
$exchange->load_markets();
$market = $exchange->market('BTC/USDT');
echo $market['limits']['amount']['min'], ' ', $market['precision']['amount'], "\n";
$amount = $exchange->amount_to_precision('BTC/USDT', 0.0012345); // returns a string
$price = $exchange->price_to_precision('BTC/USDT', 64123.456789);
$exchange->create_order('BTC/USDT', 'limit', 'buy', (float) $amount, (float) $price);
```
### Pagination
```php
$candles = $exchange->fetch_ohlcv('BTC/USDT', '1h', $since, null, array('paginate' => true));
$trades = $exchange->fetch_my_trades('BTC/USDT', $since, null, array('paginate' => true, 'paginationCalls' => 20));
```
### Unsubscribing and closing (ccxt.pro)
```php
use function React\Async\await;
await($exchange->un_watch_ticker('BTC/USDT')); // stop one stream; check $exchange->has['unWatchTicker'] first
await($exchange->close()); // stop every stream and close the socket
```
## Complete Method Reference
Names below are the canonical camelCase unified names; use your language's casing (`fetch_ohlcv` in Python/PHP, `FetchOHLCV` in C#/Go). Arguments are **positional in this order** — trailing ones are optional and `params` (exchange-specific extras) is always last and omitted here. Signatures mirror `ts/src/base/Exchange.ts`. Support varies per exchange: check `exchange.has['<method>']` (and `exchange.features` for finer options) before calling.
### 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
- `fetchMarkPrice(symbol)` - Fetch mark price (derivatives)
- `fetchMarkPrices([symbols])` - Fetch mark prices (derivatives)
#### Order Books
- `fetchOrderBook(symbol, limit)` - Fetch order book
- `fetchOrderBooks([symbols], limit)` - Fetch multiple order books
- `fetchL2OrderBook(symbol, limit)` - Fetch level 2 order book
- `fetchL3OrderBook(symbol, limit)` - Fetch level 3 order book (if supported)
#### Trades
- `fetchTrades(symbol, since, limit)` - Fetch public trades
- `fetchMyTrades(symbol, since, limit)` - Fetch your trades (auth required)
- `fetchOrderTrades(id, symbol, since, limit)` - Fetch trades for specific order
#### OHLCV (Candlesticks)
- `fetchOHLCV(symbol, timeframe, since, limit)` - Fetch candlestick data
- `fetchIndexOHLCV(symbol, timeframe, since, limit)` - Fetch index price OHLCV
- `fetchMarkOHLCV(symbol, timeframe, since, limit)` - Fetch mark price OHLCV
- `fetchPremiumIndexOHLCV(symbol, timeframe, since, limit)` - Fetch premium index OHLCV
### 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
- `fetchDeposits(code, since, limit)` - Fetch deposit history
- `fetchWithdrawals(code, since, limit)` - Fetch withdrawal history
- `fetchDepositsWithdrawals(code, since, limit)` - Fetch both deposits and withdrawals (replaces the older `fetchTransactions`)
### Trading Methods
#### Creating Orders
- `createOrder(symbol, type, side, amount, price)` - Create order (generic; `price` is `undefined`/`None`/`null` for market orders)
- `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
- `createMarketOrderWithCost(symbol, side, cost)` - Market order sized in quote currency
- `createMarketBuyOrderWithCost(symbol, cost)` - Buy spending a quote amount (e.g. 100 USDT)
- `createMarketSellOrderWithCost(symbol, cost)` - Sell for a quote amount
- `createStopLimitOrder(symbol, side, amount, price, triggerPrice)` - Stop-limit order
- `createStopMarketOrder(symbol, side, amount, triggerPrice)` - Stop-market order
- `createStopLossOrder(symbol, type, side, amount, price, stopLossPrice)` - Stop-loss order
- `createTakeProfitOrder(symbol, type, side, amount, price, takeProfitPrice)` - Take-profit order
- `createTriggerOrder(symbol, type, side, amount, price, triggerPrice)` - Trigger (conditional) order
- `createTrailingAmountOrder(symbol, type, side, amount, price, trailingAmount, trailingTriggerPrice)` - Trailing stop (absolute)
- `createTrailingPercentOrder(symbol, type, side, amount, price, trailingPercent, trailingTriggerPrice)` - Trailing stop (%)
- `createPostOnlyOrder(symbol, type, side, amount, price)` - Post-only (maker-only) order
- `createReduceOnlyOrder(symbol, type, side, amount, price)` - Reduce-only order
- `createOrderWithTakeProfitAndStopLoss(symbol, type, side, amount, price, takeProfit, stopLoss)` - Order with attached TP/SL
- `createOrders([orders])` - Create multiple orders at once
The unified way to attach conditions to any `createOrder` call is through `params`: `triggerPrice`, `stopLossPrice`, `takeProfitPrice`, `stopLoss: { triggerPrice, price }`, `takeProfit: { triggerPrice, price }`, `reduceOnly`, `postOnly`, `timeInForce`, `clientOrderId`, `marginMode`, `hedged`. Which ones an exchange accepts is declared in `exchange.features[marketType][subType].createOrder`. (`stopPrice` is a legacy alias; prefer `triggerPrice`.)
#### Managing Orders
- `fetchOrder(id, 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
- `fetchCanceledAndClosedOrders(symbol, since, limit)` - Fetch canceled + closed orders
- `fetchOrderWithClientOrderId(clientOrderId, symbol)` - Fetch by your client order id
- `cancelOrder(id, symbol)` - Cancel single order
- `cancelOrderWithClientOrderId(clientOrderId, symbol)` - Cancel by your client order id
- `cancelOrders([ids], symbol)` - Cancel multiple orders
- `cancelOrdersForSymbols([{ id, symbol }])` - Cancel orders across symbols
- `cancelAllOrders(symbol)` - Cancel all orders for symbol
- `cancelAllOrdersAfter(timeout)` - Dead-man switch: cancel everything after `timeout` ms (0 disables)
- `editOrder(id, symbol, type, side, amount, price)` - Modify order
- `editOrders([orders])` - Modify multiple orders
### Margin & Leverage
- `fetchCrossBorrowRate(code)` - Cross-margin borrow rate
- `fetchCrossBorrowRates()` - All cross-margin borrow rates
- `fetchIsolatedBorrowRate(symbol)` - Isolated-margin borrow rate
- `fetchIsolatedBorrowRates()` - All isolated-margin borrow rates
- `fetchBorrowInterest(code, symbol, since, limit)` - Borrow interest paid
- `borrowCrossMargin(code, amount)` / `repayCrossMargin(code, amount)` - Cross-margin loans
- `borrowIsolatedMargin(symbol, code, amount)` / `repayIsolatedMargin(symbol, code, amount)` - Isolated-margin loans
- `fetchLeverage(symbol)` / `fetchLeverages([symbols])` - Current leverage
- `setLeverage(leverage, symbol)` - Set leverage
- `fetchLeverageTiers([symbols])` - Leverage tiers
- `fetchMarketLeverageTiers(symbol)` - Leverage tiers for one market
- `fetchMarginMode(symbol)` / `fetchMarginModes([symbols])` - Margin mode (cross/isolated)
- `setMarginMode(marginMode, symbol)` - Set margin mode
- `addMargin(symbol, amount)` / `reduceMargin(symbol, amount)` / `setMargin(symbol, amount)` - Adjust isolated position margin
- `fetchMarginAdjustmentHistory(symbol, type, since, limit)` - Margin adjustment history
Deprecated and always throw `NotSupported`: `fetchBorrowRate`, `borrowMargin`, `repayMargin` — use the cross/isolated variants above (there is no `fetchBorrowRates`; use `fetchCrossBorrowRates` / `fetchIsolatedBorrowRates`).
### Derivatives & Futures
#### Positions
- `fetchPosition(symbol)` - Fetch single position
- `fetchPositions([symbols])` - Fetch all positions
- `fetchPositionsForSymbol(symbol)` - All positions for one symbol (e.g. both hedge sides)
- `fetchPositionHistory(symbol, since, limit)` - Position history for one symbol
- `fetchPositionsHistory([symbols], since, limit)` - Position history for many symbols
- `fetchPositionsRisk([symbols])` - Position risk info
- `fetchPositionMode(symbol)` - Fetch position mode (one-way/hedge)
- `setPositionMode(hedged, symbol)` - Set position mode
- `closePosition(symbol, side)` - Close position
- `closeAllPositions()` - Close all positions
#### 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)` / `fetchFundingIntervals([symbols])` - Funding interval
#### Open Interest, Liquidations & Sentiment
- `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
- `fetchLongShortRatioHistory(symbol, timeframe, since, limit)` - Long/short ratio history
#### Options
- `fetchOption(symbol)` - Fetch option info
- `fetchOptionChain(code)` - Fetch option chain
- `fetchGreeks(symbol)` - Fetch option greeks
- `fetchAllGreeks([symbols])` - Greeks for many options
Exchange-specific (implemented by only a few venues, not in the base class): `fetchSettlementHistory`, `fetchMySettlementHistory`, `fetchVolatilityHistory`, `fetchUnderlyingAssets`, `fetchBorrowRateHistory`, `fetchOpenOrder`, `fetchOrdersByStatus`, `fetchDeposit`, `fetchWithdrawal`. Always gate them on `exchange.has`.
### Fees
- `fetchTradingFee(symbol)` - Trading fee for symbol
- `fetchTradingFees()` - Trading fees for all symbols
- `fetchDepositWithdrawFee(code)` - Deposit/withdrawal fee
- `fetchDepositWithdrawFees([codes])` - Multiple deposit/withdraw fees
- `fetchTransactionFee(code)` / `fetchTransactionFees([codes])` - Older fee API, prefer `fetchDepositWithdrawFees`
### Deposits & Withdrawals
- `fetchDepositAddress(code)` - Get deposit address (pass `{ network: 'TRC20' }` in params to choose a chain)
- `fetchDepositAddresses([codes])` - Multiple deposit addresses
- `fetchDepositAddressesByNetwork(code)` - Addresses by network
- `createDepositAddress(code)` - Create new deposit address
- `withdraw(code, amount, address)` - Withdraw funds; pass the memo/tag and network in params: `{ tag: '...', network: 'ERC20' }`
### Transfer & Convert
- `transfer(code, amount, fromAccount, toAccount)` - Internal transfer between accounts (`'spot'`, `'swap'`, `'funding'`, ...)
- `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 (returns a quote `id`)
- `createConvertTrade(id, fromCode, toCode, amount)` - Execute a conversion using the quote `id`
- `fetchConvertTrade(id, code)` - Fetch convert trade
- `fetchConvertTradeHistory(code, since, limit)` - Convert history
### Market Info
- `loadMarkets(reload)` - Load and cache markets (call once; most methods do it for you)
- `fetchMarkets()` - Fetch all markets (raw, uncached)
- `fetchCurrencies()` - Fetch all currencies
- `fetchTime()` - Fetch exchange server time
- `fetchStatus()` - Fetch exchange status
### Precision & Market Helpers (synchronous, no network)
- `market(symbol)` - Market structure: `precision`, `limits` (`amount.min`, `cost.min`, ...), `contractSize`, `type`, ...
- `amountToPrecision(symbol, amount)` - Round an amount to the market's step (returns a string)
- `priceToPrecision(symbol, price)` - Round a price to the market's tick (returns a string)
- `costToPrecision(symbol, cost)` - Round a cost
- `currencyToPrecision(code, fee)` - Round a currency amount (e.g. a fee)
- `milliseconds()` / `iso8601(ts)` / `parse8601(str)` - Time helpers
- `setSandboxMode(true)` - Switch to the exchange's testnet (call right after construction)
### WebSocket Methods (ccxt.pro)
Most market-data and account methods have a `watch*` equivalent; each returns the next update when awaited, so call it in a loop. Every `watch*` subscription has a matching `unWatch*` to unsubscribe without closing the whole connection.
#### Real-time Market Data
- `watchTicker(symbol)` / `watchTickers([symbols])` - Ticker updates
- `watchOrderBook(symbol, limit)` / `watchOrderBookForSymbols([symbols], limit)` - Order book updates
- `watchTrades(symbol, since, limit)` / `watchTradesForSymbols([symbols], since, limit)` - Public trades
- `watchOHLCV(symbol, timeframe, since, limit)` / `watchOHLCVForSymbols([[symbol, timeframe]], since, limit)` - Candles
- `watchBidsAsks([symbols])` - Best bid/ask
- `watchMarkPrice(symbol)` / `watchMarkPrices([symbols])` - Mark price (derivatives)
- `watchFundingRate(symbol)` / `watchFundingRates([symbols])` - Funding rate (derivatives)
- `watchLiquidations(symbol, since, limit)` / `watchLiquidationsForSymbols([symbols], since, limit)` - Public liquidations
#### Real-time Account Data (Auth Required)
- `watchBalance()` - Balance updates
- `watchOrders(symbol, since, limit)` / `watchOrdersForSymbols([symbols], since, limit)` - Your order updates
- `watchMyTrades(symbol, since, limit)` / `watchMyTradesForSymbols([symbols], since, limit)` - Your fills
- `watchPositions([symbols], since, limit)` - Position updates
- `watchPosition(symbol)` - One position
- `watchMyLiquidations(symbol, since, limit)` - Your liquidations
#### Unsubscribing
- `unWatchTicker(symbol)`, `unWatchTickers([symbols])`, `unWatchOrderBook(symbol)`, `unWatchOrderBookForSymbols([symbols])`, `unWatchTrades(symbol)`, `unWatchTradesForSymbols([symbols])`, `unWatchOHLCV(symbol, timeframe)`, `unWatchOHLCVForSymbols([[symbol, timeframe]])`, `unWatchBidsAsks([symbols])`, `unWatchMarkPrice(symbol)`, `unWatchMarkPrices([symbols])`, `unWatchFundingRate(symbol)`, `unWatchFundingRates([symbols])`, `unWatchOrders(symbol)`, `unWatchMyTrades(symbol)`, `unWatchPositions([symbols])`
- Check support first: `exchange.has['unWatchTicker']`. Use `close()` to drop every subscription and the socket.
#### Trading over WebSocket (lower latency, where supported)
- `createOrderWs(symbol, type, side, amount, price)`, `editOrderWs(id, symbol, type, side, amount, price)`, `cancelOrderWs(id, symbol)`, `cancelOrdersWs([ids], symbol)`, `cancelAllOrdersWs(symbol)`, `fetchOrderBookWs(symbol, limit)`
### 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`
- Margin/leverage methods
- Position methods
- `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,
// ...
// }
```
### 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)
## Proxy Configuration
CCXT supports HTTP, HTTPS, and SOCKS proxies for both REST and WebSocket connections.
### 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'
```
### Proxy for WebSocket
WebSocket connections also respect proxy settings:
```
exchange.httpsProxy = 'https://proxy:8080'
// WebSocket connections will use this proxy
```
### 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)
}
```
## WebSocket-Specific Methods
Some exchanges provide WebSocket variants of REST methods for faster order placement and management. These use the `*Ws` suffix:
### Trading via 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
### When to Use WebSocket Methods
**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
### 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)
```
### Checking WebSocket Method Availability
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)
}
```
## Authentication
### Setting API Keys
```php
<?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');
```
### Testing Authentication
```php
try {
$balance = $exchange->fetch_balance();
print_r('Authentication successful!');
} catch (\ccxt\AuthenticationError $e) {
print_r('Invalid API credentials');
}
```
## Error Handling
### Exception Hierarchy
```
BaseError
├─ NetworkError (recoverable - retry)
│ ├─ RequestTimeout
│ ├─ ExchangeNotAvailable
│ ├─ RateLimitExceeded
│ └─ DDoSProtection
└─ ExchangeError (non-recoverable - don't retry)
├─ AuthenticationError
├─ InsufficientFunds
├─ InvalidOrder
└─ NotSupported
```
### Basic Error Handling
```php
<?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();
}
```
##...
© ccxt · MIT · ccxt/ccxt