我正在尝试通过websocket-client模块接收消息,并能够将接收到的消息用于其他目的(例如,根据传入消息执行购买/出售订单)。
这是我到目前为止所拥有的:
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()
运行此代码将打印当前的比特币价格(current_price
,这些价格是通过Websocket Feed传入的。
我接下来要做的是能够在websocket函数之外访问变量current_price
,而我在这里遇到了困难。除ws.run_forever()
之外的任何内容都将被忽略,因为websocket事件循环永远不会结束。
因此,我尝试使用“线程”模型在单独的线程上运行websocket:
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)
,这将返回0
。我该怎么做才能使这项工作成功?
答案 0 :(得分:1)
不确定这是否是最合适的答案,但找到了使之有效的方法。
import queue
.
.
.
.
def on_message(ws, message):
current_price = message
q.put(current_price)
.
.
.
ws_thread.start()
while True:
print(q.get())