问题描述
我的问题是一般如何使用 WebSocket 数据。我正在使用这个包 https://www.npmjs.com/package/binance 来获取币安实时行情。我想要做的是获取实时数据并将其与我使用 axios 调用的其他一些交换数据进行比较。但我得到的是连续的币安数据流,不知道如何使用它,我试图在 stream
中运行函数,但这似乎没有帮助,因为数据流是连续的,而且 axios 请求需要时间返回。如果我的问题不完整,我可以添加更多。
解决方法
binance 包仅支持 websocket 流,但 REST API(directly 或使用 different 包)将帮助您更轻松地实现目标。
您可以拥有两个功能 - 每个功能都用于从交易所检索价格,然后比较不同来源的价格。
const axios = require('axios');
const getBinanceBtcPrice = async () => {
// binance allows retrieving a single symbol
// if you omit the param,it would return prices of all symbols
// and you'd have to loop through them like in the WazirX example
const response = await axios.get('https://api.binance.com/api/v3/avgPrice?symbol=BTCUSDT');
return response.data.price;
}
const getWazirxBtcPrice = async () => {
// WazirX only returns all symbol data
const response = await axios.get('https://api.wazirx.com/api/v2/market-status');
// you need to loop through all of them,until you find the desired pair
for (let market of response.data.markets) {
// in your case `btc` and `usdt` (mind the lowecase letters)
if (market.baseMarket === 'btc' && market.quoteMarket === 'usdt') {
// mind that WazirX only returns price in full integer,// it does not return floating numbers
return market.last;
}
}
// did not find the combination
return null;
}
const run = async () => {
const binancePrice = await getBinanceBtcPrice();
const wazirxPrice = await getWazirxBtcPrice();
console.log(binancePrice);
console.log(wazirxPrice);
}
run();