К основному содержанию
скилл CX Codex

ccxt-php — скилл для Claude Code: функции и установка

Скилл ccxt-php для Claude Code помогает подключить криптобиржи к PHP-проекту через CCXT. Он включается при работе с рыночными данными, ордерами и потоками котировок.

MIT ★ 44 950 обновлён 2026-11-18

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add ccxt/ccxt --skill ccxt-php -a claude-code
Открыть на GitHub

Что делает ccxt-php

Скилл показывает, как использовать CCXT в PHP: загружать рынки, получать тикеры и стаканы, отправлять и отменять ордера, проверять баланс и сделки. Для обновлений в реальном времени он описывает WebSocket-вызовы; REST-запросы доступны в синхронном и асинхронном вариантах через ReactPHP.

Для установки библиотеки используется composer require ccxt/ccxt. Нужен PHP 8.1 или новее, а также расширения cURL, mbstring, PCRE и iconv; для некоторых бирж требуется gmp. ReactPHP устанавливается вместе с CCXT. В примерах задан часовой пояс UTC. Для приватных запросов нужны apiKey и secret.

Какие задачи решает

  • подключить PHP-проект к криптобирже
  • получить тикер или стакан через REST API
  • передавать рыночные ордера и отменять заявки
  • читать котировки и сделки через WebSocket

Примеры запросов агенту

  • Покажи, как получить тикер BTC/USDT через CCXT в моём PHP-проекте.
  • Напиши пример для WebSocket-потока котировок BTC/USDT с CCXT.
  • Как отправить лимитный ордер и получить баланс через CCXT?

Как установить ccxt-php

1Через Skills CLI (Vercel)

npx skills add ccxt/ccxt --skill ccxt-php -a claude-code

2Вручную: положить файлы

~/.claude/skills/ccxt-php/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/ccxt-php/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о ccxt-php

Как установить ccxt-php в Claude Code?

Выполни npx skills add ccxt/ccxt --skill ccxt-php -a claude-code. Файл скилла появится по пути ~/.claude/skills/ccxt-php/SKILL.md.

Что делает ccxt-php?

Скилл объясняет работу с CCXT в PHP: REST-запросы к биржам, ордера и аккаунтные данные, а также WebSocket-потоки рыночных обновлений.

Что нужно для работы ccxt-php?

Нужен PHP 8.1 или новее и расширения cURL, mbstring, PCRE и iconv. Для некоторых бирж требуется gmp; приватные запросы используют apiKey и secret.

Исходный текст

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

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →
php-pro https://github.com/Jeffallan Скилл php-pro задаёт правила разработки на PHP 8.3+ для Laravel и Symfony: включает strict_types, анализ в PHPStan на уровне 9 и тесты PHPUnit или Pest. CX Codex +1 16 400установок php-best-practices php-community Скилл php-best-practices для Claude Code содержит 51 правило проверки PHP 8.0–8.5 по PSR, SOLID и строгой типизации. Используется при код-ревью и рефакторинге классов. CX Codex +1 3 900установок appwrite-php appwrite Скилл appwrite-php подсказывает агенту, как писать серверный PHP под Appwrite: пользователи, таблицы, файлы, функции. Пригодится в Laravel и Symfony. CX Codex +1 898установок php-expert personamanagmentlayer Скилл php-expert для Claude Code задаёт агенту правила работы с PHP 8+, Laravel, Composer и PHPUnit. Охватывает разработку, тестирование и ревью современного PHP-кода. CX Codex +1 269установок magento-php-specialist maxnorm Скилл magento-php-specialist для разработки под Magento 2 на PHP. Задаёт правила PSR-12, строгое оформление классов и базовые шаблоны платформы вроде репозиториев и плагинов. CX Codex +1 263установок php-lsp официальный Anthropic Плагин php-lsp подключает языковой сервер Intelephense к Claude Code. Помогает агенту разбирать файлы .php и находить ошибки в коде. ★ 47 914звёзд репо

Из того же набора9

ccxt-python Скилл ccxt-python для Claude Code интегрирует криптовалютную библиотеку CCXT для работы с REST и WebSocket API бирж на Python. Применяется в ботах для торговли и скриптах анализа данных. CX Codex +1 2 400установок ccxt-typescript Скилл ccxt-typescript для Claude Code интегрирует библиотеку CCXT для работы с криптовалютными биржами в проекты на TypeScript и JavaScript. CX Codex +1 985установок ccxt-cli Скилл ccxt-cli учит агента работать с криптовалютными биржами через утилиту ccxt: запрашивать тикеры, свечи, баланс и выставлять ордера прямо из терминала. CX Codex +1 739установок new-exchange Скилл new-exchange создаёт скелет интеграции новой криптобиржи в библиотеку CCXT на TypeScript по шаблону сертифицированных бирж. CX Codex +1 134установок ccxt-java Скилл ccxt-java для Claude Code помогает подключать криптобиржи к Java-проектам через CCXT. Он охватывает REST-запросы и WebSocket-потоки для рыночных данных и ордеров. CX Codex +1 106установок ccxt-go Скилл ccxt-go для Claude Code помогает интегрировать криптовалютные биржи в Go-проекты через REST и WebSocket. Включается при разработке торговых систем, ботов и микросервисов. CX Codex +1 ★ 44 950звёзд репо ccxt-csharp Скилл ccxt-csharp для Claude Code помогает подключить CCXT к проекту на C# и работать с криптобиржами через REST и WebSocket. Включается при настройке обмена и рыночных данных. CX Codex +1 ★ 44 950звёзд репо CCXT Подключает агентов к криптобиржам и рынкам предсказаний через библиотеку CCXT. Позволяет запрашивать котировки, проверять баланс и управлять ордерами. CX Codex +1 ★ 44 950звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой