如何存储来自 Binance Websocket 的数据?

How can I store data coming from Binance Websocket?

我目前正在尝试存储一些来自 Binance Miniticker Websocket 的数据流,但我想不出这样做的方法。 我想将数据附加到现有字典中,以便我可以将其作为历史数据进行访问。

def miniticker_socket(msg):
    ''' define how to process incoming WebSocket messages '''
    if msg[0]['e'] != 'error':

        for item in msg:
            miniticker["{0}".format(item['s'])] = {'low': [],'high': [], 'open': [], 'close':[],'timestamp':[], 'symbol':[] }

            miniticker[item['s']]['close'].append(msg[msg.index(item)]['c'])

        print(miniticker[item['s']])
    else:
        print('there has been an issue')

bsm = BinanceSocketManager(client)
#ticker_key = bsm.start_symbol_ticker_socket(crypto, ticker_socket)
miniticker_key = bsm.start_miniticker_socket(miniticker_socket)
bsm.start()

我在上面的代码中遇到的问题是数据没有被追加,因为每次 Websocket 回调函数时,它也会将字典定义为空。我无法在 Websocket 外部定义字典,因为字典的名称由套接字内的 item['s'] 元素给出。

我还尝试返回整个数据并在另一个函数中调用回调函数,但这会产生另一个错误,提示“msg is not defined”。

非常感谢您对此的反馈! 谢谢

我认为您可能需要一个全局变量字典,其中包含来自自动收报机的字典值。您将需要一些独特的东西作为全局字典的键。

例如,您可以使用字符串日期时间:

timestamp_key = datetime.datetime.now().isoformat()

global_dict[timestamp_key] = miniticker["{0}".format(item['s'])] = {'low': [],'high': [], 'open': [], 'close':[],'timestamp':[], 'symbol':[] }
global_dict[timestamp_key][item['s']]['close'].append(msg[msg.index(item)]['c'])

全局字典最终会是这样的:

{
  "2020-03-25T17:14:19.382748": {
    "your_data_key1": { "more": "data" }
  },
  "2021-03-25T17:15:19.249148": {
    "your_data_key1": { "more": "data_from_another_update" }
  }
}

此外,您可以尝试检查字典中是否已经存在键miniticker:

key = "{0}".format(item['s'])
if key not in miniticker.keys():
    miniticker["{0}".format(item['s'])] = {...}


所以不会每次都重新定义为空字典