Reputation:
I'm trying to get the latest bitcoin prices and compare the last price with the most recent and write out if the price has gone up or down.
I'm using WebSockets to stream the values in real time so I can get the latest price per second, and then I'm trying to take the value of the last stream and trying to compare it with the current.
The WebSocket returns this:
2021-04-10T14:53:57.297218Z 60300.010 BTC-USD channel type:ticker
I've then passed the value 60300.010
into a var called price_val
which I'd then like to compare with the next line?
When I try to do:
latest_val = price_val
if latest_val < price_val
print("down")
But I get local variable 'price_val' referenced before assignment
.
Probably a much better way to do this, but not sure how?
Here is the code I'm using to get the live prices
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}")
Within the def on_message
I added the
latest_val = price_val
if latest_val < price_val
print("down")
but this doesn't seem to work as latest_val
and price_val
are now the same value.
Upvotes: 0
Views: 445
Reputation: 51
Let me explain what actually happening.
You declare a local variable named price_val
You assign price_val.val(...)
something like that to price_val
(Since you didn't give all of your code so I just guess it.)
But price_val is a local variable which doesn't have a value yet (unbound local)
That's why Your program crashs.
To fix these issue :
You can fix this by passing parameters rather than relying on Globals
For example , your code is :
Var1 = 1
Var2 = 0
def function():
pass
You have to change it as like as below :
def function(Var1, Var2):
pass
Upvotes: 1