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.register(error_handler, 'Error')

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 /
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 /
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

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:

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.