tws_gateway.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import copy
  5. from time import sleep, strftime
  6. import logging
  7. import json
  8. from ib.ext.Contract import Contract
  9. from ib.ext.EClientSocket import EClientSocket
  10. from misc2.helpers import ContractHelper, ConfigMap
  11. from optparse import OptionParser
  12. from comms.ibgw.base_messaging import Prosumer
  13. from comms.ibgw.tws_event_handler import TWS_event_handler
  14. from comms.ibgw.ib_heartbeat import IbHeartBeat
  15. from comms.ibgw.client_request_handler import ClientRequestHandler
  16. from comms.ibgw.subscription_manager import SubscriptionManager
  17. from comms.tws_protocol_helper import TWS_Protocol
  18. from comms.ibgw.tws_gateway_restapi import WebConsole
  19. from comms.ibgw.order_manager import OrderManager
  20. from ormdapi.v2.quote_handler import QuoteRESTHandler
  21. import redis
  22. import threading
  23. from threading import Lock
  24. class TWS_gateway():
  25. # monitor IB connection / heart beat
  26. # ibh = None
  27. # tlock = None
  28. # ib_conn_status = None
  29. TWS_GW_DEFAULT_CONFIG = {
  30. 'name': 'tws_gateway_server',
  31. 'bootstrap_host': 'localhost',
  32. 'bootstrap_port': 9092,
  33. 'redis_host': 'localhost',
  34. 'redis_port': 6379,
  35. 'redis_db': 0,
  36. 'tws_host': 'localhost',
  37. 'tws_api_port': 8496,
  38. 'tws_app_id': 38888,
  39. 'group_id': 'TWS_GW',
  40. 'session_timeout_ms': 10000,
  41. 'clear_offsets': False,
  42. 'order_transmit': False,
  43. 'topics': list(TWS_Protocol.topicMethods),
  44. 'reset_db_subscriptions': False
  45. }
  46. def __init__(self, kwargs):
  47. temp_kwargs = copy.copy(kwargs)
  48. self.kwargs = copy.copy(TWS_gateway.TWS_GW_DEFAULT_CONFIG)
  49. for key in self.kwargs:
  50. if key in temp_kwargs:
  51. self.kwargs[key] = temp_kwargs.pop(key)
  52. self.kwargs.update(temp_kwargs)
  53. '''
  54. TWS_gateway start up sequence
  55. 1. establish redis connection
  56. 2. initialize prosumer instance - gateway message handler
  57. 3. establish TWS gateway connectivity
  58. 4. initialize listeners: ClientRequestHandler and SubscriptionManager
  59. 4a. start order_id_manager
  60. 5. start the prosumer
  61. 6. run web console
  62. '''
  63. logging.info('starting up TWS_gateway...')
  64. self.ib_order_transmit = self.kwargs['order_transmit']
  65. logging.info('Order straight through (no-touch) flag = %s' % ('True' if self.ib_order_transmit == True else 'False'))
  66. logging.info('establishing redis connection...')
  67. self.initialize_redis()
  68. logging.info('starting up gateway message handler - kafka Prosumer...')
  69. self.gw_message_handler = Prosumer(name='tws_gw_prosumer', kwargs=self.kwargs)
  70. logging.info('initializing TWS_event_handler...')
  71. self.tws_event_handler = TWS_event_handler(self.gw_message_handler)
  72. logging.info('starting up IB EClientSocket...')
  73. self.tws_connection = EClientSocket(self.tws_event_handler)
  74. logging.info('establishing TWS gateway connectivity...')
  75. if self.connect_tws() == False:
  76. logging.error('TWS_gateway: unable to establish connection to IB %s:%d' %
  77. (self.kwargs['tws_host'], self.kwargs['tws_api_port']))
  78. self.disconnect_tws()
  79. sys.exit(-1)
  80. else:
  81. # start heart beat monitor
  82. logging.info('starting up IB heart beat monitor...')
  83. self.tlock = Lock()
  84. self.ibh = IbHeartBeat(self.kwargs)
  85. self.ibh.register_listener([self.on_ib_conn_broken])
  86. self.ibh.run()
  87. logging.info('instantiating listeners...cli_req_handler')
  88. self.cli_req_handler = ClientRequestHandler('client_request_handler', self)
  89. logging.info('instantiating listeners subscription manager...')
  90. self.initialize_subscription_mgr()
  91. logging.info('registering messages to listen...')
  92. self.gw_message_handler.add_listeners([self.cli_req_handler])
  93. self.gw_message_handler.add_listener_topics(self.contract_subscription_mgr, self.kwargs['subscription_manager.topics'])
  94. logging.info('initialize order_id_manager and quote_handler for REST API...')
  95. self.initialize_order_quote_manager()
  96. logging.info('start TWS_event_handler. Start prosumer processing loop...')
  97. self.gw_message_handler.start_prosumer()
  98. logging.info('start web console...')
  99. self.start_web_console()
  100. logging.info('**** Completed initialization sequence. ****')
  101. self.main_loop()
  102. def initialize_subscription_mgr(self):
  103. self.contract_subscription_mgr = SubscriptionManager(self.kwargs['name'], self.tws_connection,
  104. self.gw_message_handler,
  105. self.get_redis_conn(), self.kwargs)
  106. self.tws_event_handler.set_subscription_manager(self.contract_subscription_mgr)
  107. def initialize_order_quote_manager(self):
  108. # self.order_id_mgr = OrderIdManager(self.tws_connection)
  109. # self.tws_event_handler.set_order_id_manager(self.order_id_mgr)
  110. # self.order_id_mgr.start()
  111. self.order_manager = OrderManager('order_manager', self, self.kwargs)
  112. self.order_manager.start_order_manager()
  113. self.quote_manager = QuoteRESTHandler('quote_manager', self)
  114. def initialize_redis(self):
  115. self.rs = redis.Redis(self.kwargs['redis_host'], self.kwargs['redis_port'], self.kwargs['redis_db'])
  116. try:
  117. self.rs.client_list()
  118. except redis.ConnectionError:
  119. logging.error('TWS_gateway: unable to connect to redis server using these settings: %s port:%d db:%d' %
  120. (self.kwargs['redis_host'], self.kwargs['redis_port'], self.kwargs['redis_db']))
  121. logging.error('aborting...')
  122. sys.exit(-1)
  123. def start_web_console(self):
  124. def start_flask():
  125. w = WebConsole(self)
  126. # tell tws_event_handler that WebConsole
  127. # is interested to receive all messages
  128. for e in TWS_event_handler.PUBLISH_TWS_EVENTS:
  129. self.tws_event_handler.register(e, w)
  130. w.add_resource()
  131. w.app.run(host=self.kwargs['webconsole.host'], port=self.kwargs['webconsole.port'],
  132. debug=self.kwargs['webconsole.debug'], use_reloader=self.kwargs['webconsole.auto_reload'])
  133. t_webApp = threading.Thread(name='Web App', target=start_flask)
  134. t_webApp.setDaemon(True)
  135. t_webApp.start()
  136. def get_order_id_manager(self):
  137. return self.order_manager.get_order_id_mgr()
  138. def get_order_manager(self):
  139. return self.order_manager
  140. def get_tws_connection(self):
  141. return self.tws_connection
  142. def get_tws_event_handler(self):
  143. return self.tws_event_handler
  144. def get_subscription_manager(self):
  145. return self.contract_subscription_mgr
  146. def get_quote_manager(self):
  147. return self.quote_manager
  148. def get_redis_conn(self):
  149. return self.rs
  150. def connect_tws(self):
  151. if type(self.kwargs['tws_app_id']) <> int:
  152. logging.error('TWS_gateway:connect_tws. tws_app_id must be of int type but detected %s!' % str(type(kwargs['tws_app_id'])))
  153. sys.exit(-1)
  154. logging.info('TWS_gateway - eConnect. Connecting to %s:%d App Id: %d...' %
  155. (self.kwargs['tws_host'], self.kwargs['tws_api_port'], self.kwargs['tws_app_id']))
  156. self.tws_connection.eConnect(self.kwargs['tws_host'], self.kwargs['tws_api_port'], self.kwargs['tws_app_id'])
  157. return self.tws_connection.isConnected()
  158. def disconnect_tws(self, value=None):
  159. sleep(2)
  160. self.tws_connection.eDisconnect()
  161. def on_ib_conn_broken(self, msg):
  162. logging.error('TWS_gateway: detected broken IB connection!')
  163. self.ib_conn_status = 'ERROR'
  164. self.tlock.acquire() # this function may get called multiple times
  165. try: # block until another party finishes executing
  166. if self.ib_conn_status == 'OK': # check status
  167. return # if already fixed up while waiting, return
  168. #self.disconnect_tws()
  169. self.connect_tws()
  170. while not self.tws_connection.isConnected():
  171. logging.error('TWS_gateway: attempt to reconnect...')
  172. self.connect_tws()
  173. sleep(2)
  174. # we arrived here because the connection has been restored
  175. # resubscribe tickers again!
  176. self.ib_conn_status = 'OK'
  177. logging.info('TWS_gateway: IB connection restored...resubscribe contracts')
  178. self.contract_subscription_mgr.force_resubscription()
  179. finally:
  180. self.tlock.release()
  181. def persist_subscription_table(self):
  182. self.pcounter = (self.pcounter + 1) % 10
  183. if (self.pcounter >= 8):
  184. self.contract_subscription_mgr.persist_subscriptions()
  185. def shutdown_all(self):
  186. sleep(1)
  187. logging.info('shutdown_all sequence started....')
  188. self.gw_message_handler.set_stop()
  189. self.gw_message_handler.join()
  190. self.ibh.shutdown()
  191. self.menu_loop_done = True
  192. self.get_order_id_manager().set_stop()
  193. sys.exit(0)
  194. def post_shutdown(self):
  195. th = threading.Thread(target=self.shutdown_all)
  196. th.daemon = True
  197. th.start()
  198. def main_loop(self):
  199. def print_menu():
  200. menu = {}
  201. menu['1']="Dump subscription manager content to log"
  202. menu['2']=""
  203. menu['3']="Start up configuration"
  204. menu['4']=""
  205. menu['9']="Exit"
  206. choices=menu.keys()
  207. choices.sort()
  208. for entry in choices:
  209. print entry, menu[entry]
  210. def get_user_input(selection):
  211. logging.info('TWS_gateway:main_loop ***** accepting console input...')
  212. print_menu()
  213. while 1:
  214. resp = sys.stdin.readline()
  215. response[0] = resp.strip('\n')
  216. try:
  217. response = [None]
  218. user_input_th = threading.Thread(target=get_user_input, args=(response,))
  219. user_input_th.daemon = True
  220. user_input_th.start()
  221. self.pcounter = 0
  222. self.menu_loop_done = False
  223. while not self.menu_loop_done:
  224. sleep(.5)
  225. self.persist_subscription_table()
  226. if response[0] is not None:
  227. selection = response[0]
  228. if selection =='1':
  229. self.contract_subscription_mgr.dump()
  230. elif selection == '3':
  231. print '\n'.join('[%s]:%s' % (k,v) for k,v in self.kwargs.iteritems())
  232. elif selection == '9':
  233. self.shutdown_all()
  234. sys.exit(0)
  235. break
  236. else:
  237. pass
  238. response[0] = None
  239. print_menu()
  240. except (KeyboardInterrupt, SystemExit):
  241. logging.error('TWS_gateway: caught user interrupt. Shutting down...')
  242. self.shutdown_all()
  243. logging.info('TWS_gateway: Service shut down complete...')
  244. sys.exit(0)
  245. if __name__ == '__main__':
  246. usage = "usage: %prog [options]"
  247. parser = OptionParser(usage=usage)
  248. parser.add_option("-c", "--clear_offsets", action="store_true", dest="clear_offsets",
  249. help="delete all redis offsets used by this program")
  250. parser.add_option("-r", "--reset_db_subscriptions", action="store_true", dest="reset_db_subscriptions",
  251. help="delete subscriptions entries in redis used by this program")
  252. parser.add_option("-f", "--config_file",
  253. action="store", dest="config_file",
  254. help="path to the config file")
  255. (options, args) = parser.parse_args()
  256. kwargs = ConfigMap().kwargs_from_file(options.config_file)
  257. for option, value in options.__dict__.iteritems():
  258. if value <> None:
  259. kwargs[option] = value
  260. logconfig = kwargs['logconfig']
  261. logconfig['format'] = '%(asctime)s %(levelname)-8s %(message)s'
  262. logging.basicConfig(**logconfig)
  263. logging.info('config settings: %s' % kwargs)
  264. app = TWS_gateway(kwargs)