Websocket send after initial connection?

I’ve been using the code from: https://github.com/hackingthemarkets/alpaca-websockets/blob/master/stream.py

I can successfully authorize the connection and send an initial message to listen for some data:

ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message, on_close=on_close)
ws.run_forever()

However, the thing that has me stumped is how do I send additional messages once the initial connection is made? The initial message is bundled inside the on_open function, so I don’t really understand how to send additional message after that first on_open message is sent. For example, if I try to do this:

message = {"action": "listen", "data": {"streams": ["AM.TSLA", "T.TSLA"]}}
ws.send(json.dumps(message))

it doesn’t work. Nothing seems to happen and I don’t get any response. The only solution I have right now is to close the original connection, and create a new one with a different message, but that just seems dumb.

Why not use the stream API in the official SDK?
It’d let you listen to those endpoints using a decorator.

1 Like

thanks for the reply. I guess it’s because I don’t really understand how it works. But I guess that’s not saying much considering I don’t know how the web socket works either, lol.

But i think you’re right, maybe I should try that out

1 Like

The official API is definitely an easier way to go, hope you get everything working!

1 Like