如何在一个请求中从 Binance API 获取所有(或多个)对的历史 klines?

Posted

技术标签:

【中文标题】如何在一个请求中从 Binance API 获取所有(或多个)对的历史 klines?【英文标题】:How to get ALL (or multiple) pair's historical klines from Binance API in ONE request? 【发布时间】:2020-12-10 09:24:30 【问题描述】:

我有一个交易多对 (30-40) 的交易机器人。它使用之前的 5m 蜡烛作为价格输入。因此,我一一获得所有对的 5m 历史记录。目前,整个周期大约需要 10 分钟,所以 5m 蜡烛每 10m 更新一次,这不好。

关于如何加快速度的任何想法?

【问题讨论】:

我现在用this.. 【参考方案1】:

我认为对你来说最好的选择是 websocket 连接。您不能每次接收 kline 数据。 5 分钟,但您可以收到蜡烛的每一次变化,就像您在图表中看到的那样。 Binance API 仅提供此功能,但结合 websocket 连接,它会非常快,而不是 10 分钟。

收到数据后,您只需指定蜡烛何时关闭,您可以通过 json 数据中的时间戳('t' 和 'T')来完成。 [documentation here]

您必须安装 websockets 库。

pip install websockets

这里有一些示例代码如何工作。

import asyncio
import websockets


async def candle_stick_data():
    url = "wss://stream.binance.com:9443/ws/" #steam address
    first_pair = 'bnbbtc@kline_1m' #first pair
    async with websockets.connect(url+first_pair) as sock:
        pairs = '"method": "SUBSCRIBE", "params": ["xrpbtc@kline_1m","ethbtc@kline_1m" ],  "id": 1' #other pairs

        await sock.send(pairs)
        print(f"> pairs")
        while True:
            resp = await sock.recv()
            print(f"< resp")

asyncio.get_event_loop().run_until_complete(candle_stick_data())

输出:

< "e":"kline","E":1599828802835,"s":"XRPBTC","k":"t":1599828780000,"T":1599828839999,"s":"XRPBTC","i":"1m","f":76140140,"L":76140145,"o":"0.00002346","c":"0.00002346","h":"0.00002346","l":"0.00002345","v":"700.00000000","n":6,"x":false,"q":"0.01641578","V":"78.00000000","Q":"0.00182988","B":"0"
< "e":"kline","E":1599828804297,"s":"BNBBTC","k":"t":1599828780000,"T":1599828839999,"s":"BNBBTC","i":"1m","f":87599856,"L":87599935,"o":"0.00229400","c":"0.00229610","h":"0.00229710","l":"0.00229400","v":"417.88000000","n":80,"x":false,"q":"0.95933156","V":"406.63000000","Q":"0.93351653","B":"0"
< "e":"kline","E":1599828804853,"s":"ETHBTC","k":"t":1599828780000,"T":1599828839999,"s":"ETHBTC","i":"1m","f":193235180,"L":193235214,"o":"0.03551300","c":"0.03551700","h":"0.03551800","l":"0.03551300","v":"21.52300000","n":35,"x":false,"q":"0.76437246","V":"11.53400000","Q":"0.40962829","B":"0"
< "e":"kline","E":1599828806303,"s":"BNBBTC","k":"t":1599828780000,"T":1599828839999,"s":"BNBBTC","i":"1m","f":87599856,"L":87599938,"o":"0.00229400","c":"0.00229620","h":"0.00229710","l":"0.00229400","v":"420.34000000","n":83,"x":false,"q":"0.96497998","V":"406.63000000","Q":"0.93351653","B":"0"

【讨论】:

【参考方案2】:

只是为了跟进那个答案。您可以看到蜡烛关闭,因为每个报价的 websocket 返回数据都有一个布尔属性,用于判断蜡烛是否关闭,即如果蜡烛在 5 分钟标记上关闭,则在 5 分钟时间范围内

【讨论】:

以上是关于如何在一个请求中从 Binance API 获取所有(或多个)对的历史 klines?的主要内容,如果未能解决你的问题,请参考以下文章

如何验证对 Binance API 的 cURL 请求?

使用 Python(最好是请求)从 Binance API 获取烛台/Kline 数据以获取 JSON 数据

Binance - 通过 WebSockets 获取所选硬币的当前价格

如何将美元平价的所有硬币获取到 Binance API?

邮递员 GET 请求 Binance API

如何使用 Dart 签署 Binance HTTP 请求