That is_port_open check will cause what you experience.
TWS/IBGW are allergic to socket connections that do not actually start the? TWS API protocol (e.g. disconnect the socket without having sent any data). Not sure whether that is by design or whether those connections leak some resource.
I have attached the TWS API message flow again. You need to experiment with how much of the TWS API protocol startup handshake you have to do to avoid the port lockups. Maybe it is sufficient to send the FIRST_CLIENT_MESSAGE with such a low API version, that TWS/IBGW reject your connection request (say you claim the connecting client only speaks version 100).
But maybe you need more.
Hope that helps,
闯ü谤驳别苍
?
?
?
?
On Wed, Aug 14, 2024 at 11:52 AM, <mubbashirali35@...> wrote:
toggle quoted message
Show quoted text
Hey, guys. I hope everyone is doing great.
I have a sporadic problem occurring when I cannot connect with TWS, it gives a timeout error, and on checking the port it's usually stuck in the CLOSE_WAIT status and only way I can clear that is by restarting TWS.
Can someone please explain why the port goes stuck into CLOSE_WAIT state, what are the ways to avoid that? My personal understanding is it happens when the client doesn't disconnect properly, but in my strategy I have handled exceptions etc and have made sure to call disconnect() at the end.
This only time I connect is at the opening bell to trade i.e. 9.30 Eastern Time, most of the times it works like a charm, but sometimes it doesn't.
One important thing to mention, we have a basic flask backend to respond on HTTP requests to track TWS status & which account is logged into through this code:
def is_port_open(port):
? ? sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
? ? sock.settimeout(1) ?# 1 second timeout
? ? result = sock.connect_ex(('127.0.0.1', port))
? ? sock.close()
? ? return result == 0
def check_tws_account_status():
? ? paper_port = 7497
? ? dollar_port = 7496
? ? if is_port_open(paper_port):
? ? ? ? return 'paper'
? ? elif is_port_open(dollar_port):
? ? ? ? return 'dollar'
? ? else:
? ? ? ? return 'none'
Do you think this may have been causing the issue?
I would really appreciate any resources to understand this CLOSE_WAIT status situation.
Thanks!