How to continue code while websocket is open?

Python noob here.

I'm using this script (SEE BELOW) from Part Time Larry to connect to the Alpaca API, but I noticed that if I add any code after ws.run_forever(), it doesn't execute, and I think it's because it's essentially an infinite loop that's just constantly listening for messages over the websocket. So the code is just stuck on that last line.

So my question is how do I get the websocket connection to do its thing while also being able to continue executing additional code in the script that I want to add below. Like I want to be able to listen or unlisten additional streams, and I want to call ws.close() when I'm all done.

My research is pointing me towards asyncIO, threading, asyncronous execution, and other things I don't understand. Any help is appreciated.

import config import websocket, json import time def on_open(ws): print("opened") auth_data = { "action": "authenticate", "data": {"key_id": config.API_KEY, "secret_key": config.SECRET_KEY} } ws.send(json.dumps(auth_data)) listen_message = {"action": "listen", "data": {"streams": ["AM.TSLA"]}} ws.send(json.dumps(listen_message)) def on_message(ws, message): print("received a message") print(message) def on_close(ws): print("closed connection") socket = "wss://data.alpaca.markets/stream" ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message, on_close=on_close) ws.run_forever() #All code down here does not execute print("This string is never printed") time.sleep(10) ws.close() 

For example, let's say I want to wait 10 seconds, then close the connection, how would I do it?

Submitted October 08, 2020 at 06:21PM by joeyisnotmyname
via https://ift.tt/2GOtW18

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s