tws_gateway.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import copy
  5. from time import sleep, strftime
  6. import ConfigParser
  7. import logging
  8. import json
  9. from ib.ext.Contract import Contract
  10. from ib.ext.EClientSocket import EClientSocket
  11. from misc2.helpers import ContractHelper, ConfigMap
  12. from comms.ibgw.base_messaging import Prosumer
  13. from comms.ibgw.tws_event_handler import TWS_event_handler
  14. from comms.ibgw.client_request_handler import ClientRequestHandler
  15. from comms.ibgw.subscription_manager import SubscriptionManager
  16. from comms.tws_protocol_helper import TWS_Protocol
  17. import redis
  18. class TWS_gateway():
  19. # monitor IB connection / heart beat
  20. # ibh = None
  21. # tlock = None
  22. # ib_conn_status = None
  23. TWS_GW_DEFAULT_CONFIG = {
  24. 'name': 'tws_gateway_server',
  25. 'bootstrap_host': 'localhost',
  26. 'bootstrap_port': 9092,
  27. 'redis_host': 'localhost',
  28. 'redis_port': 6379,
  29. 'redis_db': 0,
  30. 'tws_host': 'localhost',
  31. 'tws_api_port': 8496,
  32. 'tws_app_id': 38888,
  33. 'group_id': 'TWS_GW',
  34. 'session_timeout_ms': 10000,
  35. 'clear_offsets': False,
  36. 'order_transmit': False,
  37. 'topics': list(TWS_Protocol.topicMethods) + list(TWS_Protocol.gatewayMethods)
  38. }
  39. def __init__(self, kwargs):
  40. temp_kwargs = copy.copy(kwargs)
  41. self.kwargs = copy.copy(TWS_gateway.TWS_GW_DEFAULT_CONFIG)
  42. for key in self.kwargs:
  43. if key in temp_kwargs:
  44. self.kwargs[key] = temp_kwargs.pop(key)
  45. self.kwargs.update(temp_kwargs)
  46. '''
  47. TWS_gateway start up sequence
  48. 1. establish redis connection
  49. 2. initialize prosumer instance - gateway message handler
  50. 3. establish TWS gateway connectivity
  51. 4. initialize listeners: ClientRequestHandler and SubscriptionManager
  52. 5. start the prosumer
  53. '''
  54. logging.info('starting up TWS_gateway...')
  55. self.ib_order_transmit = self.kwargs['order_transmit']
  56. logging.info('Order straight through (no-touch) flag = %s' % ('True' if self.ib_order_transmit == True else 'False'))
  57. logging.info('establishing redis connection...')
  58. self.initialize_redis()
  59. logging.info('starting up gateway message handler - kafka Prosumer...')
  60. self.gw_message_handler = Prosumer(name='tws_gw_prosumer', kwargs=self.kwargs)
  61. logging.info('initializing TWS_event_handler...')
  62. self.tws_event_handler = TWS_event_handler(self.gw_message_handler)
  63. logging.info('starting up IB EClientSocket...')
  64. self.tws_connection = EClientSocket(self.tws_event_handler)
  65. logging.info('establishing TWS gateway connectivity...')
  66. if not self.connect_tws():
  67. logging.error('TWS_gateway: unable to establish connection to IB %s:%d' %
  68. (self.kwargs['tws_host'], self.kwargs['tws_api_port']))
  69. self.disconnect_tws()
  70. sys.exit(-1)
  71. else:
  72. # start heart beat monitor
  73. pass
  74. # logging.info('starting up IB heart beat monitor...')
  75. # self.tlock = Lock()
  76. # self.ibh = IbHeartBeat(config)
  77. # self.ibh.register_listener([self.on_ib_conn_broken])
  78. # self.ibh.run()
  79. logging.info('instantiating listeners...cli_req_handler')
  80. self.cli_req_handler = ClientRequestHandler('client_request_handler', self)
  81. logging.info('instantiating listeners subscription manager...')
  82. self.initialize_subscription_mgr()
  83. logging.info('registering messages to listen...')
  84. self.gw_message_handler.add_listeners([self.cli_req_handler])
  85. self.gw_message_handler.add_listener_topics(self.contract_subscription_mgr, self.kwargs['subscription_manager.topics'])
  86. logging.info('start TWS_event_handler. Start prosumer processing loop...')
  87. self.gw_message_handler.start_prosumer()
  88. logging.info('**** Completed initialization sequence. ****')
  89. self.main_loop()
  90. def initialize_subscription_mgr(self):
  91. self.contract_subscription_mgr = SubscriptionManager(self.kwargs['name'], self.tws_connection,
  92. self.gw_message_handler,
  93. self.get_redis_conn(), self.kwargs['subscription_manager.subscriptions.redis_key'])
  94. def initialize_redis(self):
  95. self.rs = redis.Redis(self.kwargs['redis_host'], self.kwargs['redis_port'], self.kwargs['redis_db'])
  96. try:
  97. self.rs.client_list()
  98. except redis.ConnectionError:
  99. logging.error('TWS_gateway: unable to connect to redis server using these settings: %s port:%d db:%d' %
  100. (self.kwargs['redis_host'], self.kwargs['redis_port'], self.kwargs['redis_db']))
  101. logging.error('aborting...')
  102. sys.exit(-1)
  103. def get_redis_conn(self):
  104. return self.rs
  105. def connect_tws(self):
  106. if type(self.kwargs['tws_app_id']) <> int:
  107. logging.error('TWS_gateway:connect_tws. tws_app_id must be of int type but detected %s!' % str(type(kwargs['tws_app_id'])))
  108. sys.exit(-1)
  109. logging.info('TWS_gateway - eConnect. Connecting to %s:%d App Id: %d...' %
  110. (self.kwargs['tws_host'], self.kwargs['tws_api_port'], self.kwargs['tws_app_id']))
  111. self.tws_connection.eConnect(self.kwargs['tws_host'], self.kwargs['tws_api_port'], self.kwargs['tws_app_id'])
  112. return self.tws_connection.isConnected()
  113. def disconnect_tws(self, value=None):
  114. sleep(2)
  115. self.tws_connection.eDisconnect()
  116. def on_ib_conn_broken(self, msg):
  117. logging.error('TWS_gateway: detected broken IB connection!')
  118. self.ib_conn_status = 'ERROR'
  119. self.tlock.acquire() # this function may get called multiple times
  120. try: # block until another party finishes executing
  121. if self.ib_conn_status == 'OK': # check status
  122. return # if already fixed up while waiting, return
  123. self.eDisconnect()
  124. self.eConnect()
  125. while not self.tws_connection.isConnected():
  126. logging.error('TWS_gateway: attempt to reconnect...')
  127. self.eConnect()
  128. sleep(2)
  129. # we arrived here because the connection has been restored
  130. # resubscribe tickers again!
  131. logging.info('TWS_gateway: IB connection restored...resubscribe contracts')
  132. self.contract_subscription_mgr.force_resubscription()
  133. finally:
  134. self.tlock.release()
  135. def persist_subscription_table(self):
  136. self.pcounter = (self.pcounter + 1) % 10
  137. if (self.pcounter >= 8):
  138. self.contract_subscription_mgr.persist_subscriptions()
  139. def main_loop(self):
  140. try:
  141. logging.info('TWS_gateway:main_loop ***** accepting console input...')
  142. self.pcounter = 0
  143. while True:
  144. sleep(.5)
  145. self.persist_subscription_table()
  146. except (KeyboardInterrupt, SystemExit):
  147. logging.error('TWS_gateway: caught user interrupt. Shutting down...')
  148. self.gw_message_handler.set_stop()
  149. self.gw_message_handler.join()
  150. logging.info('TWS_gateway: Service shut down complete...')
  151. sys.exit(0)
  152. if __name__ == '__main__':
  153. if len(sys.argv) != 2:
  154. print("Usage: %s <config file>" % sys.argv[0])
  155. exit(-1)
  156. cfg_path= sys.argv[1:]
  157. kwargs = ConfigMap().kwargs_from_file(cfg_path)
  158. logconfig = kwargs['logconfig']
  159. logconfig['format'] = '%(asctime)s %(levelname)-8s %(message)s'
  160. logging.basicConfig(**logconfig)
  161. app = TWS_gateway(kwargs)