ccxt-go — Claude Code skill: what it does, how to install
ccxt-go is a Claude Code skill that integrates crypto exchange APIs into Go applications using REST and WebSocket. Runs when writing trading logic, bots, or microservices.
MIT ★ 44,950 updated 2026-11-18
npx skills add ccxt/ccxt --skill ccxt-go -a claude-codeWhat ccxt-go does
The skill guides Go developers on integrating CCXT v4 across multiple cryptocurrency exchanges. All exchange clients reside in a single package, instantiated via typed functions like ccxt.NewBinance or dynamically through ccxt.CreateExchange. For live market data feeds, it wires up the ccxtpro package with methods such as WatchTicker and WatchOrderBook.
Required arguments follow positional order, while all optional arguments rely on functional options formatted as ccxt.With<Method><Arg>. Numeric and text fields in returned structs like ccxt.Ticker or ccxt.Order use pointers such as *float64 and *string because exchanges frequently omit optional payload fields. Direct dereferencing without nil-checks leads to runtime panics.
What it helps with
- connect to cryptocurrency exchanges via REST and WebSocket in Go
- fetch market tickers, OHLCV candle charts, and order books
- create market and limit buy or sell orders
- track balances and active orders across trading pairs
Example prompts for the agent
- Fetch the latest BTC/USDT ticker from Kraken using ccxt in Go
- Stream live order book updates with ccxtpro in Go
- Write a function to place a limit buy order on Binance using ccxt-go
How to install ccxt-go
1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-go -a claude-code2Manually: put the files in place
~/.claude/skills/ccxt-go/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/ccxt-go/
1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-go -a codex2Manually: put the files in place
.agents/skills/ccxt-go/SKILL.mdFor all projects use ~/.agents/skills/
1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-go -a cursor2Manually: put the files in place
.cursor/skills/ccxt-go/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install ccxt/ccxt .claude/skills/ccxt-go2Manually: put the files in place
.github/skills/ccxt-go/SKILL.md1Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-go -a gemini-cli2Platform CLI
gemini skills install https://github.com/ccxt/ccxt --path .claude/skills/ccxt-goManually: put the files in place
.devin/skills/ccxt-go/SKILL.mdThe legacy .windsurf/skills/ path still works
Skills CLI (Vercel)
npx skills add ccxt/ccxt --skill ccxt-go -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-go
How to install ccxt-go in Claude Code?
Run npx skills add ccxt/ccxt --skill ccxt-go -a claude-code. The skill file installs to ~/.claude/skills/ccxt-go/SKILL.md.
What does ccxt-go do?
It teaches the coding assistant the correct syntax, functional options, and patterns for CCXT v4 in Go.
What is required to use ccxt-go?
You need the Go dependency github.com/ccxt/ccxt/go/v4 (or go/v4/pro for WebSocket), plus exchange apiKey and secret for private endpoints.
Source text
SKILL.md · MIT
---
name: ccxt-go
description: CCXT cryptocurrency exchange library for Go 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 Go projects. Use when working with crypto exchanges in Go applications, microservices, or trading systems.
---
# CCXT for Go
A comprehensive guide to using CCXT in Go projects for cryptocurrency exchange integration.
## Installation
```bash
go get github.com/ccxt/ccxt/go/v4 # REST (package ccxt)
go get github.com/ccxt/ccxt/go/v4/pro # WebSocket (package ccxtpro) — same module
```
Every exchange lives in **one package**: there is no per-exchange import path. Construct with `ccxt.New<Exchange>(config)` (e.g. `ccxt.NewBinance`, `ccxt.NewOkx`, `ccxt.NewKraken`) or dynamically with `ccxt.CreateExchange("binance", config)`.
## Quick Start
### REST API
```go
package main
import (
"fmt"
ccxt "github.com/ccxt/ccxt/go/v4"
)
func main() {
exchange := ccxt.NewBinance(nil)
ticker, err := exchange.FetchTicker("BTC/USDT")
if err != nil {
panic(err)
}
fmt.Println(*ticker.Last)
}
```
### WebSocket API - Real-time Updates
```go
package main
import (
"fmt"
ccxtpro "github.com/ccxt/ccxt/go/v4/pro"
)
func main() {
exchange := ccxtpro.NewBinance(nil)
defer exchange.Close()
for {
ticker, err := exchange.WatchTicker("BTC/USDT")
if err != nil {
panic(err)
}
fmt.Println(*ticker.Last) // live updates
}
}
```
## REST vs WebSocket
| Feature | REST API | WebSocket API |
|---------|----------|---------------|
| **Use for** | One-time queries, placing orders | Real-time monitoring, live price feeds |
| **Import** | `ccxt "github.com/ccxt/ccxt/go/v4"` | `ccxtpro "github.com/ccxt/ccxt/go/v4/pro"` |
| **Constructor** | `ccxt.NewBinance(cfg)` | `ccxtpro.NewBinance(cfg)` |
| **Methods** | `Fetch*` (FetchTicker, FetchOrderBook) | `Watch*` (WatchTicker, WatchOrderBook) |
| **Best for** | Trading, account management | Price monitoring, arbitrage detection |
## How Go calls work (read this first)
- **Required arguments are positional; every optional argument is a functional option** named `ccxt.With<Method><Arg>(...)`: `exchange.FetchOHLCV("BTC/USDT", ccxt.WithFetchOHLCVTimeframe("1h"), ccxt.WithFetchOHLCVLimit(100))`. Do **not** pass `nil` placeholders.
- Methods whose first unified argument is optional (e.g. `FetchOpenOrders`, `FetchMyTrades`, `WatchOrders`, `CancelAllOrders`) take *only* options: `exchange.FetchOpenOrders(ccxt.WithFetchOpenOrdersSymbol("BTC/USDT"))`.
- Exchange-specific extras go in `ccxt.With<Method>Params(map[string]any{...})`.
- Every method returns `(value, error)`. Values are structs (`ccxt.Ticker`, `ccxt.Order`, `[]ccxt.Trade`), and most numeric/string fields are **pointers** (`*float64`, `*string`) because exchanges may omit them — nil-check before dereferencing.
- The pro package re-uses the REST types, so `WatchOrderBook` options are still `ccxt.WithWatchOrderBookLimit(...)`.
## Creating Exchange Instance
```go
import (
"os"
ccxt "github.com/ccxt/ccxt/go/v4"
ccxtpro "github.com/ccxt/ccxt/go/v4/pro"
)
// Public API (no authentication)
public := ccxt.NewBinance(nil)
// Private API — pass credentials in the config map
exchange := ccxt.NewBinance(map[string]any{
"apiKey": os.Getenv("BINANCE_APIKEY"),
"secret": os.Getenv("BINANCE_SECRET"),
"enableRateLimit": true, // default: true
"options": map[string]any{"defaultType": "swap"}, // optional
})
// Testnet / sandbox — call right after construction
exchange.SetSandboxMode(true)
// WebSocket (same config shape)
ws := ccxtpro.NewBinance(map[string]any{"apiKey": "...", "secret": "..."})
defer ws.Close()
```
## Common REST Operations
### Loading Markets
```go
if _, err := exchange.LoadMarkets(); err != nil {
panic(err)
}
market := exchange.GetMarket("BTC/USDT") // typed ccxt.MarketInterface
if market.Limits.Amount.Min != nil {
fmt.Println("min amount:", *market.Limits.Amount.Min)
}
fmt.Println(exchange.AmountToPrecision("BTC/USDT", 0.0012345)) // round to the market's step
```
### Fetching Ticker
```go
ticker, err := exchange.FetchTicker("BTC/USDT")
if err != nil {
panic(err)
}
fmt.Println(*ticker.Last, *ticker.Bid, *ticker.Ask)
tickers, err := exchange.FetchTickers(ccxt.WithFetchTickersSymbols([]string{"BTC/USDT", "ETH/USDT"}))
fmt.Println(tickers.Tickers["ETH/USDT"])
```
### Fetching Order Book
```go
orderbook, err := exchange.FetchOrderBook("BTC/USDT", ccxt.WithFetchOrderBookLimit(5))
if err != nil {
panic(err)
}
fmt.Println(orderbook.Bids[0]) // [price, amount]
fmt.Println(orderbook.Asks[0])
```
### Fetching OHLCV
```go
candles, err := exchange.FetchOHLCV("BTC/USDT",
ccxt.WithFetchOHLCVTimeframe("1h"),
ccxt.WithFetchOHLCVLimit(100),
)
fmt.Println(candles[0].Timestamp, candles[0].Close)
```
### Creating Orders
```go
// Limit
order, err := exchange.CreateLimitBuyOrder("BTC/USDT", 0.001, 50000)
order, err = exchange.CreateLimitSellOrder("BTC/USDT", 0.001, 70000)
order, err = exchange.CreateOrder("BTC/USDT", "limit", "buy", 0.001, ccxt.WithCreateOrderPrice(50000))
// Market
order, err = exchange.CreateMarketBuyOrder("BTC/USDT", 0.001)
order, err = exchange.CreateOrder("BTC/USDT", "market", "sell", 0.001)
// Extra unified/exchange params (stop loss, post-only, client id, ...)
order, err = exchange.CreateOrder("BTC/USDT", "limit", "buy", 0.001,
ccxt.WithCreateOrderPrice(50000),
ccxt.WithCreateOrderParams(map[string]any{"postOnly": true, "clientOrderId": "my-id-1"}),
)
if err != nil {
panic(err)
}
fmt.Println(*order.Id)
```
### Fetching Balance
```go
balance, err := exchange.FetchBalance()
if err != nil {
panic(err)
}
fmt.Println(*balance.Free["USDT"]) // available
fmt.Println(*balance.Balances["BTC"].Total) // per-currency struct: Free / Used / Total
```
### Fetching Orders
```go
openOrders, err := exchange.FetchOpenOrders(ccxt.WithFetchOpenOrdersSymbol("BTC/USDT"))
closedOrders, err := exchange.FetchClosedOrders(ccxt.WithFetchClosedOrdersSymbol("BTC/USDT"))
order, err := exchange.FetchOrder(orderId, ccxt.WithFetchOrderSymbol("BTC/USDT"))
```
### Fetching Trades
```go
trades, err := exchange.FetchTrades("BTC/USDT", ccxt.WithFetchTradesLimit(10))
myTrades, err := exchange.FetchMyTrades(ccxt.WithFetchMyTradesSymbol("BTC/USDT")) // auth required
```
### Canceling Orders
```go
canceled, err := exchange.CancelOrder(orderId, ccxt.WithCancelOrderSymbol("BTC/USDT"))
all, err := exchange.CancelAllOrders(ccxt.WithCancelAllOrdersSymbol("BTC/USDT"))
```
### Capabilities, Pagination and Testnet
```go
if exchange.GetHas()["fetchOHLCV"] == true {
// supported
}
features := exchange.GetFeatures() // per market type: which createOrder params, fetch limits, daysBack, ...
fmt.Println(features["spot"])
// Let ccxt page through history for you (respects rate limits)
history, err := exchange.FetchOHLCV("BTC/USDT",
ccxt.WithFetchOHLCVTimeframe("1d"),
ccxt.WithFetchOHLCVSince(1704067200000),
ccxt.WithFetchOHLCVParams(map[string]any{"paginate": true}),
)
```
## WebSocket Operations (Real-time)
`Watch*` calls block until the next update; call them in a loop. Construct with `ccxtpro.New<Exchange>` and always `defer exchange.Close()`.
### Watching Ticker
```go
exchange := ccxtpro.NewBinance(nil)
defer exchange.Close()
for {
ticker, err := exchange.WatchTicker("BTC/USDT")
if err != nil {
panic(err)
}
fmt.Println(*ticker.Last, *ticker.Timestamp)
}
```
### Watching Order Book
```go
for {
orderbook, err := exchange.WatchOrderBook("BTC/USDT", ccxt.WithWatchOrderBookLimit(10))
if err != nil {
panic(err)
}
fmt.Println("best bid:", orderbook.Bids[0], "best ask:", orderbook.Asks[0])
}
```
### Watching Trades
```go
for {
trades, err := exchange.WatchTrades("BTC/USDT")
if err != nil {
panic(err)
}
for _, t := range trades {
fmt.Println(*t.Price, *t.Amount, *t.Side)
}
}
```
### Watching Your Orders and Balance (auth required)
```go
exchange := ccxtpro.NewBinance(map[string]any{"apiKey": "...", "secret": "..."})
defer exchange.Close()
orders, err := exchange.WatchOrders(ccxt.WithWatchOrdersSymbol("BTC/USDT"))
balance, err := exchange.WatchBalance()
```
### Unsubscribing
```go
if exchange.GetHas()["unWatchTicker"] == true {
_, err := exchange.UnWatchTicker("BTC/USDT") // stop one stream, keep the connection
}
```
## 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:
```go
// Check if method is supported
if exchange.GetHas()["fetchOHLCV"] == true {
candles, err := exchange.FetchOHLCV("BTC/USDT", ccxt.WithFetchOHLCVTimeframe("1h"))
fmt.Println(len(candles), err)
}
// All capabilities: map[string]any{"fetchTicker": true, "fetchPositions": false, ...}
fmt.Println(exchange.GetHas())
```
### 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)
## 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):**
```go
order, err := exchange.CreateOrder("BTC/USDT", "limit", "buy", 0.01, ccxt.WithCreateOrderPrice(50000))
```
**WebSocket API (faster, lower latency) — on a `ccxtpro` instance:**
```go
order, err := ws.CreateOrderWs("BTC/USDT", "limit", "buy", 0.01, ccxt.WithCreateOrderWsPrice(50000))
```
### Checking WebSocket Method Availability
Not all exchanges support WebSocket trading methods:
```go
ws := ccxtpro.NewBinance(map[string]any{"apiKey": "...", "secret": "..."})
defer ws.Close()
var order ccxt.Order
var err error
if ws.GetHas()["createOrderWs"] == true {
order, err = ws.CreateOrderWs("BTC/USDT", "limit", "buy", 0.01, ccxt.WithCreateOrderWsPrice(50000))
} else {
order, err = ws.CreateOrder("BTC/USDT", "limit", "buy", 0.01, ccxt.WithCreateOrderPrice(50000)) // REST fallback
}
fmt.Println(order, err)
```
## Authentication
### Setting API Keys
```go
exchange := ccxt.NewBinance(map[string]any{
"apiKey": os.Getenv("BINANCE_APIKEY"),
"secret": os.Getenv("BINANCE_SECRET"),
// "password": os.Getenv("OKX_PASSWORD"), // exchanges that need a passphrase (okx, kucoin, ...)
})
// or after construction:
exchange.ApiKey = os.Getenv("BINANCE_APIKEY")
exchange.Secret = os.Getenv("BINANCE_SECRET")
```
### Testing Authentication
```go
_, err := exchange.FetchBalance()
if ccxt.IsInstance(err, ccxt.AuthenticationError) {
fmt.Println("Invalid API credentials")
} else if err != nil {
panic(err)
} else {
fmt.Println("Authentication successful!")
}
```
## Error Handling
### Error Types
```
BaseError
├─ NetworkError (recoverable - retry)
│ ├─ RequestTimeout
│ ├─ ExchangeNotAvailable
│ ├─ RateLimitExceeded
│ └─ DDoSProtection
└─ ExchangeError (non-recoverable - don't retry)
├─ AuthenticationError
├─ InsufficientFunds
├─ InvalidOrder
└─ NotSupported
```
Every failure is returned as a `*ccxt.Error` with a `Type` (e.g. `"InsufficientFunds"`) and a `Message`. There are **no per-error Go types**, so `err.(*ccxt.InsufficientFunds)` never matches. Use `ccxt.IsInstance(err, ccxt.<ErrorName>)`, which also matches subclasses (a `RateLimitExceeded` is a `NetworkError`):
```go
_, err := exchange.CreateOrder("BTC/USDT", "limit", "buy", 0.001, ccxt.WithCreateOrderPrice(50000))
if err != nil {
switch {
case ccxt.IsInstance(err, ccxt.InsufficientFunds):
fmt.Println("Not enough balance")
case ccxt.IsInstance(err, ccxt.InvalidOrder):
fmt.Println("Invalid order parameters (check precision / min amount)")
case ccxt.IsInstance(err, ccxt.AuthenticationError):
fmt.Println("Check your API credentials")
case ccxt.IsInstance(err, ccxt.NetworkError):
fmt.Println("Network problem - safe to retry")
default:
if e, ok := err.(*ccxt.Error); ok {
fmt.Println(e.Type, e.Message)
}
}
}
```
### Retry Logic for Network Errors
```go
func fetchWithRetry(exchange *ccxt.Binance, symbol string, maxRetries int) (ccxt.Ticker, error) {
var lastErr error
for i := 0; i < maxRetries; i++ {
ticker, err := exchange.FetchTicker(symbol)
if err == nil {
return ticker, nil
}
lastErr = err
if !ccxt.IsInstance(err, ccxt.NetworkError) {
return ticker, err // exchange errors are not retryable
}
time.Sleep(time.Duration(i+1) * time.Second)
}
return ccxt.Ticker{}, lastErr
}
```
## Rate Limiting
The built-in rate limiter is **on by default** (`enableRateLimit: true`) and throttles requests per instance, so share one instance per exchange/account instead of creating many.
```go
fmt.Println(exchange.RateLimit) // milliseconds between requests
exchange.EnableRateLimit = true // leave this on
```
## Proxy Configuration...
© ccxt · MIT · ccxt/ccxt