gpt4 book ai didi

python - 如何从 websocket 保存数据?

转载 作者:行者123 更新时间:2023-12-01 01:56:53 25 4
gpt4 key购买 nike

我已成功订阅 websocket 并正在接收数据。我正在等待保存数据,以便可以在数据框中使用它进行进一步分析。

到目前为止,我的代码仅返回空列表和数据帧。

代码:返回空列表

wsClient = GDAX.WebsocketClient(url="wss://ws-feed.gdax.com", products="LTC-USD")

df1 = []

for i in wsClient.start():
df1 = df1.append(wsClient.start())

代码:返回空列表和数据框

wsClient = GDAX.WebsocketClient(url="wss://ws-feed.gdax.com", products="LTC-USD")


dfs = []
for i in wsClient.start():
dfs.append(wsClient.start())
df1 = pd.concat(dfs)

最佳答案

您需要实现自己的自定义 on_message 方法才能获取 websocket 信息:

import time
import gdax
import pandas as pd

results = []

class myWebsocketClient(gdax.WebsocketClient):
def on_open(self):
self.url = "wss://ws-feed.gdax.com/"
self.products = ["LTC-USD"]

def on_message(self, msg):
if 'price' in msg and 'type' in msg:
results.append(msg['price'])

wsClient = myWebsocketClient()
wsClient.start()

time.sleep(5)

df = pd.DataFrame(results, columns = ["Price"])
print(df.head())
wsClient.close()

这将运行 5 秒,并输出:

          Price
0 153.13000000
1 151.14000000
2 140.52000000
3 140.52000000
4 152.62000000

-- Socket Closed --

关于python - 如何从 websocket 保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com