查询交易 - fetchTrade
你可以调用ccxt的统一API方法fetchTrades
/ fetch_trades
来获取指定交易对的最近交易记录。
fetchTrade
方法声明如下:
async fetchTrades (symbol, since = undefined, limit = undefined, params = {})
例如,如果你希望逐个打印所有交易对的近期交易(别忘了交易所的限流!), 可以使用以下代码。
JavaScript示例代码:
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))
PHP示例代码:
if ($exchange->has['fetchTrades']) {
foreach ($exchange->markets as $symbol => $market) {
usleep ($exchange->rateLimit * 1000); // usleep wants microseconds
var_dump ($exchange->fetch_trades ($symbol));
}
}
上面展示的fetchTrades
方法返回一个按时间戳升序排列的交易数组,最早的交易在
第一个,最新的交易在最后一个。交易数组结构如下:
[
{
'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
},
...
]
大多数交易所返回上述交易对象中的大部分字段,虽然也有些交易所不会返回type, side, 交易id或委托单id这些字段 。 大多数时候可以保证你能拿到一个交易的以下字段:timestamp, datetime,symbol, price 和amount 。
第二个可选参数since
可以按时间戳削减结果数组,第三个参数limit
可以削减返回的交易数量。
如果用户不指定since
,那么fetchTrade
方法将返回交易所默认的公开交易时间范围,这是交易所特定的,
有些交易所会返回自交易对上市开始的所有交易,另一些交易所则会返回缩减集合,例如
最近24小时、或者最近100个交易等等。如果用户希望更精确地控制时间窗口,那么应当指定
since
参数。
ccxt的统一API中的大多数方法都会返回一个对象或对象数组。然而,也有极少数交易所会一次 返回所有的交易。通常来说交易所的API会限制仅返回最近的一定数量的交易。你不能只用 一个调用就返回自交易对上市依赖的所有交易对象,实际上,很少有交易所会容忍或允许 这种调用行为。
要查询历史交易,开发者需要按页遍历数据。分页通常暗示着使用循环分块提取数据。
大多数情况下,开发者需要使用至少某种类型的分页来获得一致的结果。
另一方面,有些交易所不支持公开交易的分页查询。总体来说交易所会提供最近的交易。
fetchTrades ()
/ fetch_trades()
方法也可以接收一个额外的关联数组作为其第四个参数。
你可以用这个关联数组传入特定交易所支持的额外的参数。请查询交易所的API文档获取详细信息。