include 'ccxt.php';
var_dump (\ccxt\Exchange::$exchanges);
交易所类的实例化
可以使用JavaScript、Python、PHP实例化指定的交易所类:
JavaScript:
const ccxt = require ('ccxt')
let exchange = new ccxt.kraken () // default id
let kraken1 = new ccxt.kraken ({ id: 'kraken1' })
let kraken2 = new ccxt.kraken ({ id: 'kraken2' })
let id = 'gdax'
let gdax = new ccxt[id] ();
// from variable id
const exchangeId = 'binance'
, exchangeClass = ccxt[exchangeId]
, exchange = new exchangeClass ({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'timeout': 30000,
'enableRateLimit': true,
})
# enable built-in rate limiting upon instantiation of the exchange
exchange = ccxt.bitfinex({
'enableRateLimit': True,
})
# or switch the built-in rate-limiter on or off later after instantiation
exchange.enableRateLimit = True # enable
exchange.enableRateLimit = False # disable
下面是使用PHP实现同样功能的代码:
// enable built-in rate limiting upon instantiation of the exchange
$exchange = new \ccxt\bitfinex (array (
'enableRateLimit' => true,
));
// or switch the built-in rate-limiter on or off later after instantiation
$exchange->enableRateLimit = true; // enable
$exchange->enableRateLimit = false; // disable
{
'id': ' btcusd', // string literal for referencing within an exchange
'symbol': 'BTC/USD', // uppercase string literal of a pair of currencies
'base': 'BTC', // uppercase string, unified base currency code, 3 or more letters
'quote': 'USD', // uppercase string, unified quote currency code, 3 or more letters
'baseId': 'btc', // any string, exchange-specific base currency id
'quoteId': 'usd', // any string, exchange-specific quote currency id
'active': true, // boolean, market status
'precision': { // number of decimal digits "after the dot"
'price': 8, // integer or float for TICK_SIZE roundingMode, might be missing if not supplied by the exchange
'amount': 8, // integer, might be missing if not supplied by the exchange
'cost': 8, // integer, very few exchanges actually have it
},
'limits': { // value limits when placing orders on this market
'amount': {
'min': 0.01, // order amount should be > min
'max': 1000, // order amount should be < max
},
'price': { ... }, // same min/max limits for the price of the order
'cost': { ... }, // same limits for order cost = price * amount
},
'info': { ... }, // the original unparsed market info from the exchange
}
(async () => {
console.log (await exchange.loadMarkets ())
let btcusd1 = exchange.markets['BTC/USD'] // get market structure by symbol
let btcusd2 = exchange.market ('BTC/USD') // same result in a slightly different way
let btcusdId = exchange.marketId ('BTC/USD') // get market id by symbol
let symbols = exchange.symbols // get an array of symbols
let symbols2 = Object.keys (exchange.markets) // same as previous line
console.log (exchange.id, symbols) // print all symbols
let currencies = exchange.currencies // a list of currencies
let bitfinex = new ccxt.bitfinex ()
await bitfinex.loadMarkets ()
bitfinex.markets['BTC/USD'] // symbol → market (get market by symbol)
bitfinex.markets_by_id['XRPBTC'] // id → market (get market by id)
bitfinex.markets['BTC/USD']['id'] // symbol → id (get id by symbol)
bitfinex.markets_by_id['XRPBTC']['symbol'] // id → symbol (get symbol by id)
})
Python示例代码:
print (exchange.load_markets ())
etheur1 = exchange.markets['ETH/EUR'] # get market structure by symbol
etheur2 = exchange.market ('ETH/EUR') # same result in a slightly different way
etheurId = exchange.market_id ('BTC/USD') # get market id by symbol
symbols = exchange.symbols # get a list of symbols
symbols2 = list (exchange.markets.keys ()) # same as previous line
print (exchange.id, symbols) # print all symbols
currencies = exchange.currencies # a list of currencies
kraken = ccxt.kraken ()
kraken.load_markets ()
kraken.markets['BTC/USD'] # symbol → market (get market by symbol)
kraken.markets_by_id['XXRPZUSD'] # id → market (get market by id)
kraken.markets['BTC/USD']['id'] # symbol → id (get id by symbol)
kraken.markets_by_id['XXRPZUSD']['symbol'] # id → symbol (get symbol by id)
PHP示例代码:
$var_dump ($exchange->load_markets ());
$dashcny1 = $exchange->markets['DASH/CNY']; // get market structure by symbol
$dashcny2 = $exchange->market ('DASH/CNY'); // same result in a slightly different way
$dashcnyId = $exchange->market_id ('DASH/CNY'); // get market id by symbol
$symbols = $exchange->symbols; // get an array of symbols
$symbols2 = array_keys ($exchange->markets); // same as previous line
var_dump ($exchange->id, $symbols); // print all symbols
$currencies = $exchange->currencies; // a list of currencies
$okcoinusd = '\\ccxt\\okcoinusd';
$okcoinusd = new $okcoinusd ();
$okcoinusd->load_markets ();
$okcoinusd->markets['BTC/USD']; // symbol → market (get market by symbol)
$okcoinusd->markets_by_id['btc_usd']; // id → market (get market by id)
$okcoinusd->markets['BTC/USD']['id']; // symbol → id (get id by symbol)
$okcoinusd->markets_by_id['btc_usd']['symbol']; // id → symbol (get symbol by id)
(async () => {
let kraken = new ccxt.kraken ({ verbose: true }) // log HTTP requests
await kraken.load_markets () // request markets
console.log (kraken.id, kraken.markets) // output a full list of all loaded markets
console.log (Object.keys (kraken.markets)) // output a short list of market symbols
console.log (kraken.markets['BTC/USD']) // output single market details
await kraken.load_markets () // return a locally cached version, no reload
let reloadedMarkets = await kraken.load_markets (true) // force HTTP reload = true
console.log (reloadedMarkets['ETH/BTC'])
}) ()
Python示例代码:
poloniex = ccxt.poloniex({'verbose': True}) # log HTTP requests
poloniex.load_markets() # request markets
print(poloniex.id, poloniex.markets) # output a full list of all loaded markets
print(list(poloniex.markets.keys())) # output a short list of market symbols
print(poloniex.markets['BTC/ETH']) # output single market details
poloniex.load_markets() # return a locally cached version, no reload
reloadedMarkets = poloniex.load_markets(True) # force HTTP reload = True
print(reloadedMarkets['ETH/ZEC'])
PHP示例代码:
$bitfinex = new \ccxt\bitfinex (array ('verbose' => true)); // log HTTP requests
$bitfinex.load_markets (); // request markets
var_dump ($bitfinex->id, $bitfinex->markets); // output a full list of all loaded markets
var_dump (array_keys ($bitfinex->markets)); // output a short list of market symbols
var_dump ($bitfinex->markets['XRP/USD']); // output single market details
$bitfinex->load_markets (); // return a locally cached version, no reload
$reloadedMarkets = $bitfinex->load_markets (true); // force HTTP reload = true
var_dump ($bitfinex->markets['XRP/BTC']);
(async () => {
const params = {
'foo': 'bar', // exchange-specific overrides in unified queries
'Hello': 'World!', // see their docs for more details on parameter names
}
// the overrides go into the last argument to the unified call ↓ HERE
const result = await exchange.fetchOrderBook (symbol, length, params)
}) ()
Python示例代码:
params = {
'foo': 'bar', # exchange-specific overrides in unified queries
'Hello': 'World!', # see their docs for more details on parameter names
}
# overrides go in the last argument to the unified call ↓ HERE
result = exchange.fetch_order_book(symbol, length, params)
PHP示例代码:
$params = array (
'foo' => 'bar', // exchange-specific overrides in unified queries
'Hello' => 'World!', // see their docs for more details on parameter names
}
// overrides go into the last argument to the unified call ↓ HERE
$result = $exchange->fetch_order_book ($symbol, $length, $params);
if (exchange.has['fetchTrades']) {
let since = exchange.milliseconds () - 86400000 // -1 day from now
// alternatively, fetch from a certain starting datetime
// let since = exchange.parse8601 ('2018-01-01T00:00:00Z')
let allTrades = []
while (since < exchange.milliseconds ()) {
const symbol = undefined // change for your symbol
const limit = 20 // change for your limit
const trades = await exchange.fetchTrades (symbol, since, limit)
if (trades.length) {
since = trades[trades.length - 1]['timestamp']
allTrades = allTrades.concat (trades)
} else {
break
}
}
}
Python:
if exchange.has['fetchOrders']:
since = exchange.milliseconds () - 86400000 # -1 day from now
# alternatively, fetch from a certain starting datetime
# since = exchange.parse8601('2018-01-01T00:00:00Z')
all_orders = []
while since < exchange.milliseconds ():
symbol = None # change for your symbol
limit = 20 # change for your limit
orders = await exchange.fetch_orders(symbol, since, limit)
if len(orders):
since = orders[len(orders) - 1]['timestamp']
all_orders += orders
else:
break
PHP:
if ($exchange->has['fetchMyTrades']) {
$since = exchange->milliseconds () - 86400000; // -1 day from now
// alternatively, fetch from a certain starting datetime
// $since = $exchange->parse8601 ('2018-01-01T00:00:00Z');
$all_trades = array ();
while (since < exchange->milliseconds ()) {
$symbol = null; // change for your symbol
$limit = 20; // change for your limit
$trades = $exchange->fetchMyTrades ($symbol, $since, $limit);
if (count($trades)) {
$since = $trades[count($trades) - 1]['timestamp'];
$all_trades = array_merge ($all_trades, $trades);
} else {
break;
}
}
}
if (exchange.has['fetchTrades']) {
let from_id = 'abc123' // all ids are strings
let allTrades = []
while (true) {
const symbol = undefined // change for your symbol
const since = undefined
const limit = 20 // change for your limit
const params = {
'from_id': from_id, // exchange-specific non-unified parameter name
}
const trades = await exchange.fetchTrades (symbol, since, limit, params)
if (trades.length) {
from_id = trades[trades.length - 1]['id']
allTrades.push (trades)
} else {
break
}
}
}
Python:
if exchange.has['fetchOrders']:
from_id = 'abc123' # all ids are strings
all_orders = []
while True:
symbol = None # change for your symbol
since = None
limit = 20 # change for your limit
params = {
'from_id': from_id, # exchange-specific non-unified parameter name
}
orders = await exchange.fetch_orders(symbol, since, limit, params)
if len(orders):
from_id = orders[len(orders) - 1]['id']
all_orders += orders
else:
break
PHP:
if ($exchange->has['fetchMyTrades']) {
$from_id = 'abc123' // all ids are strings
$all_trades = array ();
while (true) {
$symbol = null; // change for your symbol
$since = null;
$limit = 20; // change for your limit
$params = array (
'from_id' => $from_id, // exchange-specific non-unified parameter name
);
$trades = $exchange->fetchMyTrades ($symbol, $since, $limit, $params);
if (count($trades)) {
$from_id = $trades[count($trades) - 1]['id'];
$all_trades = array_merge ($all_trades, $trades);
} else {
break;
}
}
}
if (exchange.has['fetchTrades']) {
let page = 0 // exchange-specific type and value
let allTrades = []
while (true) {
const symbol = undefined // change for your symbol
const since = undefined
const limit = 20 // change for your limit
const params = {
'page': page, // exchange-specific non-unified parameter name
}
const trades = await exchange.fetchTrades (symbol, since, limit, params)
if (trades.length) {
// not thread-safu and exchange-specific !
page = exchange.last_json_response['cursor']
allTrades.push (trades)
} else {
break
}
}
}
Python:
if exchange.has['fetchOrders']:
cursor = 0 # exchange-specific type and value
all_orders = []
while True:
symbol = None # change for your symbol
since = None
limit = 20 # change for your limit
params = {
'cursor': cursor, # exchange-specific non-unified parameter name
}
orders = await exchange.fetch_orders(symbol, since, limit, params)
if len(orders):
# not thread-safu and exchange-specific !
cursor = exchange.last_http_headers['CB-AFTER']
all_orders += orders
else:
break
PHP:
if ($exchange->has['fetchMyTrades']) {
$start = '0' // exchange-specific type and value
$all_trades = array ();
while (true) {
$symbol = null; // change for your symbol
$since = null;
$limit = 20; // change for your limit
$params = array (
'start' => $start, // exchange-specific non-unified parameter name
);
$trades = $exchange->fetchMyTrades ($symbol, $since, $limit, $params);
if (count($trades)) {
// not thread-safu and exchange-specific !
$start = $exchange->last_json_response['next'];
$all_trades = array_merge ($all_trades, $trades);
} else {
break;
}
}
}
(async function test () {
const ccxt = require ('ccxt')
const exchange = new ccxt.bitfinex ()
const limit = 5
const orders = await exchange.fetchOrderBook ('BTC/USD', limit, {
// this parameter is exchange-specific, all extra params have unique names per exchange
'group': 1, // 1 = orders are grouped by price, 0 = orders are separate
})
}) ()
Python示例代码:
import ccxt
# return up to ten bidasks on each side of the order book stack
limit = 10
ccxt.cex().fetch_order_book('BTC/USD', limit)
PHP示例代码:
// instantiate the exchange by id
$exchange = '\\ccxt\\kraken';
$exchange = new $exchange ();
// up to ten orders on each side, for example
$limit = 20;
var_dump ($exchange->fetch_order_book ('BTC/USD', $limit));
{
'symbol': string symbol of the market ('BTC/USD', 'ETH/BTC', ...)
'info': { the original non-modified unparsed reply from exchange API },
'timestamp': int (64-bit Unix Timestamp in milliseconds since Epoch 1 Jan 1970)
'datetime': ISO8601 datetime string with milliseconds
'high': float, // highest price
'low': float, // lowest price
'bid': float, // current best bid (buy) price
'bidVolume': float, // current best bid (buy) amount (may be missing or undefined)
'ask': float, // current best ask (sell) price
'askVolume': float, // current best ask (sell) amount (may be missing or undefined)
'vwap': float, // volume weighed average price
'open': float, // opening price
'close': float, // price of last trade (closing price for current period)
'last': float, // same as `close`, duplicated for convenience
'previousClose': float, // closing price for the previous period
'change': float, // absolute change, `last - open`
'percentage': float, // relative change, `(change/open) * 100`
'average': float, // average price, `(last + open) / 2`
'baseVolume': float, // volume of base currency traded for last 24 hours
'quoteVolume': float, // volume of quote currency traded for last 24 hours
}
``
注意:
- bidVolume指的是委托账本中当前的最优买入价委托单的总量
- askVolume指的是委托账本中当前的最优卖出价委托单的总量
- baseVolume指的是过去24小时内基准货币的交易量(买入或卖出)
- quoteVolume指的是过去24小时内报价货币的交易量(买入或卖出)
行情结构中的所有价格都是以报价货币计量,其中某些字段可能是undefined / None / null。
base currency ↓ BTC / USDT ETH / BTC DASH / ETH ↑ quote currency ```
if (exchange.has['fetchTicker']) {
console.log (await (exchange.fetchTicker ('BTC/USD'))) // ticker for BTC/USD
let symbols = Object.keys (exchange.markets)
let random = Math.floor (Math.random () * (symbols.length - 1))
console.log (exchange.fetchTicker (symbols[random])) // ticker for a random symbol
}
Python示例代码:
import random
if (exchange.has['fetchTicker']):
print(exchange.fetch_ticker('LTC/ZEC')) # ticker for LTC/ZEC
symbols = list(exchange.markets.keys())
print(exchange.fetch_ticker(random.choice(symbols))) # ticker for a random symbol
PHP别忘了正确设置时区:
if ($exchange->has['fetchTicker']) {
var_dump ($exchange->fetch_ticker ('ETH/CNY')); // ticker for ETH/CNY
$symbols = array_keys ($exchange->markets);
$random = rand () % count ($symbols);
var_dump ($exchange->fetch_ticker ($symbols[$random])); // ticker for a random symbol
}
{
'info': { ... }, // the original JSON response from the exchange as is
'BTC/USD': { ... }, // a single ticker for BTC/USD
'ETH/BTC': { ... }, // a ticker for ETH/BTC
...
}
let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));
if (exchange.has.fetchOHLCV) {
for (symbol in exchange.markets) {
await sleep (exchange.rateLimit) // milliseconds
console.log (await exchange.fetchOHLCV (symbol, '1m')) // one minute
}
}
Python示例代码:
import time
if exchange.has['fetchOHLCV']:
for symbol in exchange.markets:
time.sleep (exchange.rateLimit / 1000) # time.sleep wants seconds
print (symbol, exchange.fetch_ohlcv (symbol, '1d')) # one day
PHP示例代码:
if ($exchange->has['fetchOHLCV']) {
foreach ($exchange->markets as $symbol => $market) {
usleep ($exchange->rateLimit * 1000); // usleep wants microseconds
var_dump ($exchange->fetch_ohlcv ($symbol, '1M')); // one month
}
}
if (exchange.has['fetchTrades']) {
let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));
for (symbol in exchange.markets) {
await sleep (exchange.rateLimit) // milliseconds
console.log (await exchange.fetchTrades (symbol))
}
}
Python示例代码:
import time
if exchange.has['fetchTrades']:
for symbol in exchange.markets: # ensure you have called loadMarkets() or load_markets() method.
time.sleep (exchange.rateLimit / 1000) # time.sleep wants seconds
print (symbol, exchange.fetch_trades (symbol))
[
{
'info': { ... }, // the original decoded JSON as is
'id': '12345-67890:09876/54321', // string trade id
'timestamp': 1502962946216, // Unix timestamp in milliseconds
'datetime': '2017-08-17 12:42:48.000', // ISO8601 datetime with milliseconds
'symbol': 'ETH/BTC', // symbol
'order': '12345-67890:09876/54321', // string order id or undefined/None/null
'type': 'limit', // order type, 'market', 'limit' or undefined/None/null
'side': 'buy', // direction of the trade, 'buy' or 'sell'
'price': 0.06917684, // float price in quote currency
'amount': 1.5, // amount of base currency
},
...
]
$exchange = new \ccxt\liqui ();
print_r ($exchange->has); // or var_dump
一个典型的.hash属性通常包含如下对应上述用于查询委托单的API方法的标志:
exchange.has = {
// ... other flags ...
'fetchOrder': true, // available from the exchange directly and implemented in ccxt
'fetchOrders': false, // not available from the exchange or not implemented in ccxt
'fetchOpenOrders': true,
'fetchClosedOrders': 'emulated', // not available from the exchange, but emulated in ccxt
// ... other flags ...
}
ture和false的含义很明确。emulated表示这个方法是ccxt模拟出来的,不是交易所原生API提供的。 The meanings of boolean true and false are obvious.
where (order['timestamp'] < before) && (order['status'] != 'open')
清理命令接受一个参数来声明具体的清理条件。示例代码如下:
JavaScript:
// keep last 24 hours of history in cache
before = exchange.milliseconds () - 24 * 60 * 60 * 1000
// purge all closed and canceled orders "older" or issued "before" that time
exchange.purgeCachedOrders (before)
Python:
# keep last hour of history in cache
before = exchange.milliseconds () - 1 * 60 * 60 * 1000
# purge all closed and canceled orders "older" or issued "before" that time
exchange.purge_cached_orders (before)
PHP:
// keep last 24 hours of history in cache
$before = $exchange->milliseconds () - 24 * 60 * 60 * 1000;
// purge all closed and canceled orders "older" or issued "before" that time
$exchange->purge_cached_orders ($before);
if (exchange.has['fetchOrder']) {
// you can use the params argument for custom overrides
let order = await exchange.fetchOrder (id, symbol = undefined, params = {})
}
(async function () {
const order = await exchange.fetchOrder (id)
console.log (order)
}) ()
Python 2/3 同步方式的示例代码:
if exchange.has['fetchOrder']:
order = exchange.fetch_order(id)
print(order)
# Python 3.5+ asyncio (asynchronous)
import asyncio
import ccxt.async_support as ccxt
if exchange.has['fetchOrder']:
order = asyncio.get_event_loop().run_until_complete(exchange.fetch_order(id))
print(order)
PHP:
if ($exchange->has['fetchOrder']) {
$order = $exchange->fetch_order ($id);
var_dump ($order);
}
查询全部委托单 - fetchOrders
使用fetchOrders方法查询交易所的全部委托单,方法原型如下;
if (exchange.has['fetchOrders'])
exchange.fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {})
{
'id': '12345-67890:09876/54321', // string
'datetime': '2017-08-17 12:42:48.000', // ISO8601 datetime of 'timestamp' with milliseconds
'timestamp': 1502962946216, // order placing/opening Unix timestamp in milliseconds
'lastTradeTimestamp': 1502962956216, // Unix timestamp of the most recent trade on this order
'status': 'open', // 'open', 'closed', 'canceled'
'symbol': 'ETH/BTC', // symbol
'type': 'limit', // 'market', 'limit'
'side': 'buy', // 'buy', 'sell'
'price': 0.06917684, // float price in quote currency
'amount': 1.5, // ordered amount of base currency
'filled': 1.1, // filled amount of base currency
'remaining': 0.4, // remaining amount to fill
'cost': 0.076094524, // 'filled' * 'price' (filling price used where available)
'trades': [ ... ], // a list of order trades/executions
'fee': { // fee info, if available
'currency': 'BTC', // which currency the fee is (usually quote)
'cost': 0.0009, // the fee amount in that currency
'rate': 0.002, // the fee rate (if available)
},
'info': { ... }, // the original unparsed order structure as is
}
// using general createOrder, type = 'market' and side = 'buy' or 'sell'
exchange.createOrder (symbol, 'market', 'sell', amount, ...)
exchange.create_order (symbol, 'market', 'buy', amount, ...)
// this example is oversimplified and doesn't show all the code that is
// required to handle the errors and exchange metadata properly
// it shows just the concept of placing a market buy order
const exchange = new ccxt.cex ({
'apiKey': YOUR_API_KEY,
'secret': 'YOUR_SECRET',
'enableRateLimit': true,
// 'options': {
// 'createMarketBuyOrderRequiresPrice': true, // default
// },
})
;(async () => {
// when `createMarketBuyOrderRequiresPrice` is true, we can pass the price
// so that the total cost of the order would be calculated inside the library
// by multiplying the amount over price (amount * price)
const symbol = 'BTC/USD'
const amount = 2 // BTC
const price = 9000 // USD
// cost = amount * price = 2 * 9000 = 18000 (USD)
// note that we don't use createMarketBuyOrder here, instead we use createOrder
// createMarketBuyOrder will omit the price and will not work when
// exchange.options['createMarketBuyOrderRequiresPrice'] = true
const order = await exchange.createOrder (symbol, 'market', 'buy', amount, price)
console.log (order)
})
const exchange = new ccxt.cex ({
'apiKey': YOUR_API_KEY,
'secret': 'YOUR_SECRET',
'enableRateLimit': true,
'options': {
'createMarketBuyOrderRequiresPrice': false, // switch off
},
})
// or, to switch it off later, after the exchange instantiation, you can do
exchange.options['createMarketBuyOrderRequiresPrice'] = false
;(async () => {
// when `createMarketBuyOrderRequiresPrice` is true, we can pass the price
// so that the total cost of the order would be calculated inside the library
// by multiplying the amount over price (amount * price)
const symbol = 'BTC/USD'
const amount = 2 // BTC
const price = 9000 // USD
cost = amount * price // ← instead of the amount cost goes ↓ here
const order = await exchange.createMarketBuyOrder (symbol, cost)
console.log (order)
})
{
'info': { ... }, // the original decoded JSON as is
'id': '12345-67890:09876/54321', // string trade id
'timestamp': 1502962946216, // Unix timestamp in milliseconds
'datetime': '2017-08-17 12:42:48.000', // ISO8601 datetime with milliseconds
'symbol': 'ETH/BTC', // symbol
'order': '12345-67890:09876/54321', // string order id or undefined/None/null
'type': 'limit', // order type, 'market', 'limit' or undefined/None/null
'side': 'buy', // direction of the trade, 'buy' or 'sell'
'takerOrMaker': 'taker', // string, 'taker' or 'maker'
'price': 0.06917684, // float price in quote currency
'amount': 1.5, // amount of base currency
'cost': 0.10376526, // total cost (including fees), `price * amount`
'fee': { // provided by exchange or calculated by ccxt
'cost': 0.0015, // float
'currency': 'ETH', // usually base currency for buys, quote currency for sells
'rate': 0.002, // the fee rate (if available)
},
}
取决于交易所的要求,上述调用可能需要传入货币代码数组作为第一个参数。 Depending on the exchange it may or may not require a list of unified currency codes in the first argument. fetchDepositAddresses方法返回一个地址对象数组。
{
'currency': currency, // currency code
'address': address, // address in terms of requested currency
'tag': tag, // tag / memo / paymentId for particular currencies (XRP, XMR, ...)
'info': response, // raw unparsed data as returned from the exchange
}
{
'info': { ... }, // the JSON response from the exchange as is
'id': '123456', // exchange-specific transaction id, string
'txid': '0x68bfb29821c50ca35ef3762f887fd3211e4405aba1a94e448a4f218b850358f0',
'timestamp': 1534081184515, // timestamp in milliseconds
'datetime': '2018-08-12T13:39:44.515Z', // ISO8601 string of the timestamp
'addressFrom': '0x38b1F8644ED1Dbd5DcAedb3610301Bf5fa640D6f', // sender
'address': '0x02b0a9b7b4cDe774af0f8e47cb4f1c2ccdEa0806', // "from" or "to"
'addressTo': '0x304C68D441EF7EB0E2c056E836E8293BD28F8129', // receiver
'tagFrom', '0xabcdef', // "tag" or "memo" or "payment_id" associated with the sender
'tag': '0xabcdef' // "tag" or "memo" or "payment_id" associated with the address
'tagTo': '0xhijgklmn', // "tag" or "memo" or "payment_id" associated with the receiver
'type': 'deposit', // or 'withdrawal', string
'amount': 1.2345, // float (does not include the fee)
'currency': 'ETH', // a common unified currency code, string
'status': 'pending', // 'ok', 'failed', 'canceled', string
'updated': undefined, // UTC timestamp of most recent status change in ms
'comment': 'a comment or message defined by the user if any',
'fee': { // the entire fee structure may be undefined
'currency': 'ETH', // a unified fee currency code
'cost': 0.1234, // float
'rate': undefined, // approximately, fee['cost'] / amount, float
},
}
{
'status': 'ok', // 'ok', 'shutdown', 'error', 'maintenance'
'updated': undefined, // integer, last updated timestamp in milliseconds if updated via the API
'eta': undefined, // when the maintenance or outage is expected to end
'url': undefined, // a link to a GitHub issue or to an exchange post on the subject
}
{
'id': 'hqfl-f125f9l2c9', // string id of the ledger entry, e.g. an order id
'direction': 'out', // or 'in'
'account': '06d4ab58-dfcd-468a', // string id of the account if any
'referenceId': 'bf7a-d4441fb3fd31', // string id of the trade, transaction, etc...
'referenceAccount': '3146-4286-bb71', // string id of the opposite account (if any)
'type': 'trade', // string, reference type, see below
'currency': 'BTC', // string, unified currency code, 'ETH', 'USDT'...
'amount': 123.45, // absolute number, float (does not include the fee)
'timestamp': 1544582941735, // milliseconds since epoch time in UTC
'datetime': "2018-12-12T02:49:01.735Z", // string of timestamp, ISO8601
'before': 0, // amount of currency on balance before
'after': 0, // amount of currency on balance after
'status': 'ok', // 'ok, 'pending', 'canceled'
'fee': { // object or or undefined
'cost': 54.321, // absolute number on top of the amount
'currency': 'ETH', // string, unified currency code, 'ETH', 'USDT'...
},
'info': { ... }, // raw ledger entry as is from the exchange
}
// try to call a unified method
try {
const response = await exchange.fetchTicker ('ETH/BTC')
console.log (response)
} catch (e) {
// if the exception is thrown, it is "caught" and can be handled here
// the handling reaction depends on the type of the exception
// and on the purpose or business logic of your application
if (e instanceof ccxt.NetworkError) {
console.log (exchange.id, 'fetchTicker failed due to a network error:', e.message)
// retry or whatever
// ...
} else if (e instanceof ccxt.ExchangeError) {
console.log (exchange.id, 'fetchTicker failed due to exchange error:', e.message)
// retry or whatever
// ...
} else {
console.log (exchange.id, 'fetchTicker failed with:', e.message)
// retry or whatever
// ...
}
}
Python:
try:
response = await exchange.fetch_order_book('ETH/BTC')
print(response)
except ccxt.NetworkError as e:
print(exchange.id, 'fetch_order_book failed due to a network error:', str(e))
# retry or whatever
# ...
except ccxt.ExchangeError as e:
print(exchange.id, 'fetch_order_book failed due to exchange error:', str(e))
# retry or whatever
# ...
except Exception as e:
print(exchange.id, 'fetch_order_book failed with:', str(e))
# retry or whatever
# ...
PHP:
// try to call a unified method
try {
$response = $exchange->fetch_trades('ETH/BTC');
print_r($response);
} catch (\ccxt\NetworkError $e) {
echo $exchange->id . ' fetch_trades failed due to a network error: ' . $e->getMessage () . "\n";
// retry or whatever
// ...
} catch (\ccxt\ExchangeError $e) {
echo $exchange->id . ' fetch_trades failed due to exchange error: ' . $e->getMessage () . "\n";
// retry or whatever
// ...
} catch (Exception $e) {
echo $exchange->id . ' fetch_trades failed with: ' . $e->getMessage () . "\n";
// retry or whatever
// ...
}
异常类的体系
ccxt中所有的机场都派生自BaseError基类,其定义如下:
JavaScript:
class BaseError extends Error {
constructor () {
super ()
// a workaround to make `instanceof BaseError` work in ES5
this.constructor = BaseError
this.__proto__ = BaseError.prototype
}
}