Skip to content
All library documents

Why an IBPy Connection Closes When the Python Script Ends

Article Quant Q&A · Author: user19883

Summary

The document explains a basic cause of an Interactive Brokers TWS connection closing immediately in a short IBPy script: the Python process exits after creating the connection, which closes its socket. The log excerpt shows a client connecting and then the socket resetting moments later. The reply attributes that sequence to the script ending, rather than identifying a TWS-side timeout or a market-data error.

As a simple diagnostic, it refers to IBPy sample scripts that pause with a sleep long enough for responses to arrive, and suggests examining other ways to keep a connection active, such as running it in a separate thread and controlling that thread through a queue. The post does not provide a complete implementation or discuss reconnect handling, current library support, or production-grade lifecycle management. Its useful lesson is that an open connection does not keep a process alive; a script needs an explicit way to remain running while it handles messages.

Key ideas

  • A Python process ending also closes the socket it opened to TWS.
  • A brief pause in sample scripts can keep the process alive long enough to receive responses.
  • A separate thread and queue are suggested as ways to manage a long-running connection.
  • The log’s rapid socket closure is consistent with the client script terminating.
  • The discussion does not provide a complete connection-management implementation.

Tags

Full text
# Why does my ibpy connection always close automatically


# Why does my ibpy connection always close automatically












my code:

```
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message

def error_handler(msg):

   print "Server Error: %s" % msg

def reply_handler(msg):

   print "Server Response: %s, %s" % (msg.typeName, msg)

if __name__ == "__main__":
 tws_conn = Connection.create(port=7496, clientId=100)
 tws_conn.connect()
 tws_conn.register(error_handler, 'Error')
 tws_conn.registerAll(reply_handler)
```

and the TWS log file:

```
GO 00:27:20:952 JTS-EServerSocket-231: [0:62:76:1:0:0:0:SYS] Starting new conversation with client on /127.0.0.1
GO 00:27:20:952 JTS-EServerSocketNotifier-232: Starting async queue thread
GO 00:27:20:952 JTS-EServerSocket-231: [0:62:76:1:0:0:0:SYS] Server version is 76
GO 00:27:20:953 JTS-EServerSocket-231: [0:62:76:1:0:0:0:SYS] Client version is 62
GO 00:27:20:953 JTS-EServerSocket-231: [0:62:76:1:0:0:0:SYS] is 3rdParty false
GO 00:27:20:954 JTS-EServerSocket-231: [100:62:76:1:0:0:0:SYS] Client ID is 100
GO 00:27:20:958 JTS-EServerSocket-231: [100:62:76:1:0:0:0:ERR] Socket connection for client{100} has closed. 
GO 00:27:20:958 JTS-EServerSocket-231: Connection reset
GO 00:27:20:959 JTS-EServerSocket-231: ArEServer: Removing 174597970 with id 100
GO 00:27:20:959 JTS-EServerSocket-231: [100:62:76:1:0:0:0:SYS] Ending conversation with client{100} at /127.0.0.1
GO 00:27:20:959 JTS-EServerSocketNotifier-232: Terminating async queue thread
GO 00:27:20:959 JTS-EWriter2-233: [100:62:76:1:0:0:0:SYS] Writer thread terminated for socket client{100}.
GO 00:27:21:952 JTS-DeadlockMonitor-26: CPU:cur=0.00% avg=0.67% 30 min avg=0.67% 5 min avg=0.22% 1 min avg=1.02%
GC:called=20 times CPU used=0.09%
Finalizer:cur=0.00% avg=0.01% 30 min avg=0.01% 5 min avg=0.00% 1 min avg=0.00%
Threads Count:curr live=88 curr daemon=52
GO 00:27:47:000 JTS-CCPDispatcherS2-40: Setting time offset to -1282 diff 5579
GO 00:27:47:000 JTS-CCPDispatcherS2-40: Setting time offset to -1282 diff 0
```

## Answer by mementum (score 1)

https://quant.stackexchange.com/a/25509

Because your python script ends and with it the socket that `ibpy` has opened to connect to TWS.

The demo samples in the sources of `ibpy` use simple `time.sleep(x)` to make sure some information has been delivered (for example `fancy_marketdata.py`) before the script ends.

Try to remove the `time.sleep(x)` lines and see how the script also ends instantly.

Have a look at other ways to do it like here for example:

- https://stackoverflow.com/questions/34561626/ibpy-getting-portfolio-information-interactive-broker-python

You may consider running the `ibpy` connection in another thread and control the thread over a `Queue`.

Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.