Issue
I am trying to receive messages via websocket-client module and be able to use received messages for other purposes (e.g. execute buy/sell orders based on incoming messages).
Here is what I have so far:
import websocket
import time
import json
def on_message(ws, message):
try:
current_price = json.loads(message)
print(current_price["price"]) # data type is dict.. only showing values for the key 'price'
except:
print("Please wait..")
time.sleep(1)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
sub_params = {'type': 'subscribe', 'product_ids': ['BTC-USD'], 'channels': ['ticker']}
ws.send(json.dumps(sub_params))
if __name__ == "__main__":
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://ws-feed.pro.coinbase.com/",
on_open = on_open,
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.run_forever()
Running this code will print the current Bitcoin price (current_price
) as they come in through its websocket feed.
What I want to do next is to be able to access that variable current_price
outside of the websocket function, and I am having a difficulty here. Writing anything beyond ws.run_forever()
will be ignored because the websocket event loop will never end.
So I tried running the websocket on a separate thread with 'threading' mordule:
import websocket
import json
import threading
current_price = 0
def on_message(ws, message):
global current_price
current_price = message
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
sub_params = {'type': 'subscribe', 'product_ids': ['BTC-USD'], 'channels': ['ticker']}
ws.send(json.dumps(sub_params))
if __name__ == "__main__":
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://ws-feed.pro.coinbase.com/",
on_open = on_open,
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws_thread = threading.Thread(target = ws.run_forever)
ws_thread.start()
print(current_price)
and this returns 0
. What can I do to make this work?
Solution
Not sure if this is the most appropriate answer, but found a way to make this work.
import queue
.
.
.
.
def on_message(ws, message):
current_price = message
q.put(current_price)
.
.
.
ws_thread.start()
while True:
print(q.get())
Answered By - Chobani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.