如何从websocket保存数据?

时间:2018-04-27 16:12:01

标签: python pandas websocket

我已成功订阅了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)

1 个答案:

答案 0 :(得分:1)

您需要实施自己的自定义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 --