How to reconnect to web sockets?

After some time connection to alpaca web socket drops.

How to reconnect or check if connection exists?

I used this:  
setInterval(async () => {
 updates_client.connect();
 }, 600000); 

But after some time it gives me an error.
throw new Error(‘WebSocket is not open: readyState 0 (CONNECTING)’);
^

Error: WebSocket is not open: readyState 0 (CONNECTING)

Can anybody give me an example of reconnection in Node please?

Hi,
try using this sample code: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/examples/websocket_listener.js

I wrote a reconnect block in Python — basically just re-initializes a connection if connection object is null (or if a basic socket operation fails) prior to any further requests.

Blockquote

        if RE_CONN:
            try:
                  portfolio = self.api.list_positions()
             except:
                  print('Reconnecting...')
                  self.api = tradeapi.REST(base_url = ep, key_id = api_key, secret_key=secret_key)
              
                  portfolio = self.api.list_positions()

         else:
              portfolio = self.api.list_positions()

Cannot get formatting to work from mobile — sorry.
It’s in my GitHub Trailstop code — this worked effectively for me on both live and paper environments.

Hi you are doing REST api calls. you don’t need to reconnect.
reconnection is for websockets

Regardless, it is still managed as a client basically, still loses connection to the REST, and still needs to be reconnected.

Typically this class instance maintains the connection, but sometimes throughout the day it’s lost and needs to re-init.

so I’m not sure I understand.
doing a REST call always disconnects once it’s completed. it doesn’t stay connected.
every time that you do something like self.api.list_positions() you connect and disconnect.
so what do you mean by staying connected?

Yes, the list_positions is a new call, however the connection to the API to GET the REST call is treated like a socket. The api class instance loses it’s connection, so the calls will start to fail, and need to be re-init.

Basically, self.api starts throwing errors, is no longer receiving anything from the REST. There’s alot of traffic to the API, so while the connection to the API should hold, and does many days, sometimes it loses connection like every hour or so — so the API connection needs to be re-initialized, as does the class/member variable used to reference it.

this is not a socket. the REST class is an instance. it is not connected to the server.
only when you do the rest call you connect to the server.

but you’re saying that the instance stops working? not receiving response from the server?
are you maybe exceeding the limitations of the api calls?
what error do you get?