Python获取并比较价格

2024-04-25 20:00:49 发布

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

我试图获取比特币的最新价格,将上一次的价格与最近的价格进行比较,然后写出价格是上涨了还是下跌了

我正在使用WebSockets实时流化这些值,以便获得每秒的最新价格,然后尝试获取最后一个流的值,并尝试将其与当前值进行比较

WebSocket返回以下内容:

2021-04-10T14:53:57.297218Z                    60300.010                 BTC-USD    channel type:ticker

然后我将值60300.010传递到一个名为price_val的变量中,然后我想与下一行进行比较? 当我尝试这样做时:

latest_val = price_val
   if latest_val < price_val
   print("down")   

但是我得到了local variable 'price_val' referenced before assignment

这可能是一个更好的方法,但不确定如何实现

这是我用来获取实时价格的代码

class TextWebsocketClient(cbpro.WebsocketClient):
    def on_open(self):
        self.url           = 'wss://ws-feed-public.sandbox.pro.coinbase.com'
        self.message_count = 0
    
    def on_message(self,msg):
        self.message_count += 1
        msg_type = msg.get('type',None)
        if msg_type == 'ticker':
            time_val   = msg.get('time',('-'*27))
            price_val  = msg.get('price',None)
            if price_val is not None:
                price_val = float(price_val)
            product_id = msg.get('product_id',None)
            outFile = open('sample.txt', 'a')
            outFile.write(f"{time_val:30} \
                {price_val:.3f} \
                {product_id}\tchannel type:{msg_type}\n")
            outFile.close()
            #print(f"{time_val:30} \
            #    {price_val:.3f} \
            #    {product_id}\tchannel type:{msg_type}")

    
    def on_close(self):
        print(f"<---Websocket connection closed--->\n\tTotal messages: {self.message_count}")

def on_message中,我添加了

latest_val = price_val
   if latest_val < price_val
   print("down") 

但这似乎不起作用,因为latest_valprice_val现在是相同的值


Tags: selfnonemessagegetiftimeondef
1条回答
网友
1楼 · 发布于 2024-04-25 20:00:49

让我解释一下到底发生了什么

  1. 您声明了一个名为price_val的局部变量

  2. 您将price_val.val(...)类似的内容分配给price_val(因为您没有给出所有代码,所以我只是猜测而已)

  3. 但是price_val是一个局部变量,它还没有值(unbound local)

这就是你的程序崩溃的原因

要解决这些问题:

您可以通过传递参数而不是依赖全局参数来解决此问题

例如,您的代码是:

Var1 = 1
Var2 = 0

def function(): 
    pass

您必须按如下方式进行更改:

def function(Var1, Var2):
    pass

相关问题 更多 >