如何过滤从python中的websocketapi接收的特定消息,并将其写入CSV

2024-10-03 21:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编码和Python非常陌生,我正试图从bitfinexapi接收实时的交易数据,并过滤掉传入的特定消息,因为这会产生重复。我想把这些经过过滤的消息,然后连续输出到csv文件中。在

具体来说,我想保存名为“te”的消息(参见下面API的输出),因为这些是在执行时执行的交易。流也给出了“tu”,这是重复的。我只想把“te”下载到csv中进行其他处理和保存。在

下面是我的代码,它是我在网上找到的一个精简版本:

import websocket
import time
import sys
from datetime import datetime, timedelta, timezone

import sched, time
import json
import csv
import requests

class BitfinexWebSocketReader():
    endpoint = "wss://api.bitfinex.com/ws/2"
    def __init__(self):
        #websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp(
                BitfinexWebSocketReader.endpoint,
                on_message = self.on_message,                 
                on_error = self.on_error, 
                on_close = self.on_close
         )
        self.ws.on_open = self.on_open

        try:
            self.run()
        except KeyboardInterrupt:
            self.ws.close()

    def run(self):
        self.ws.run_forever()
        print("### run ###")
        pass

    def on_message(self, ws, message):
        print(message)

    def on_error(self, ws, error):
        print(error)
        sys.exit()

    def on_close(self, ws):
        print("### closed ###")

    def on_open(self, ws):
        #print("### open ###")
        ws.send(json.dumps({"event": "subscribe", "channel": "Trades", "symbol": "tBTCUSD"}))

if __name__=="__main__":
    BitfinexWebSocketReader()

下面是几秒钟的输出示例:

^{pr2}$

附加问题:为什么每次执行代码时都会弹出超长的第一个条目?在


Tags: csvrunimportself消息messageclosews
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:00

您可以在构造函数中初始化某种数据结构,如list()set()来存储所需的消息,然后在on_message方法中过滤它们。在

所以在你的构造器里

def __init__(self):
    #websocket.enableTrace(True)
    self.ws = websocket.WebSocketApp(
            BitfinexWebSocketReader.endpoint,
            on_message = self.on_message,                 
            on_error = self.on_error, 
            on_close = self.on_close
     )
    self.ws.on_open = self.on_open
    self.store = []

    try:
        self.run()
    except KeyboardInterrupt:
        self.ws.close()

在你的on_message方法中

^{pr2}$

相关问题 更多 >