helpers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import logging
  4. import threading
  5. import ConfigParser
  6. from ib.ext.Contract import Contract
  7. from ib.ext.Order import Order
  8. from ib.ext.ExecutionFilter import ExecutionFilter
  9. class BaseHelper():
  10. @staticmethod
  11. def object2kvstring(o):
  12. return json.dumps(o.__dict__)
  13. @staticmethod
  14. def kvstring2object(kvstring, object):
  15. return BaseHelper.kv2object(json.loads(kvstring), object)
  16. @staticmethod
  17. def kv2object(kv, Object):
  18. o = Object()
  19. map(lambda x: o.__setattr__(x, kv[x].encode('ascii') if type(kv[x]) == unicode else kv[x]), kv.keys())
  20. return o
  21. class OrderHelper(BaseHelper):
  22. pass
  23. # @staticmethod
  24. # def object2kvstring(contract):
  25. # return json.dumps(contract.__dict__)
  26. #
  27. # @staticmethod
  28. # def kvstring2object(sm_order):
  29. # return OrderHelper.kv2object(json.loads(sm_order))
  30. #
  31. #
  32. # @staticmethod
  33. # def kv2object(m_order):
  34. # newOrder = Order()
  35. # map(lambda x: newOrder.__setattr__(x, m_order[x].encode('ascii') if type(m_order[x]) == unicode else m_order[x]), m_order.keys())
  36. # return newOrder
  37. class ExecutionFilterHelper(BaseHelper):
  38. @staticmethod
  39. def makeExeuction(executionTuple):
  40. '''
  41. String m_acctNumber The customer account number.
  42. double m_avgPrice Average price. Used in regular trades, combo trades and legs of the combo. Does not include commissions.
  43. int m_clientId "The id of the client that placed the order.
  44. Note: TWS orders have a fixed client id of ""0."""
  45. int m_cumQty Cumulative quantity. Used in regular trades, combo trades and legs of the combo.
  46. String m_exchange Exchange that executed the order.
  47. String m_execId Unique order execution id.
  48. int m_liquidation Identifies the position as one to be liquidated last should the need arise.
  49. int m_orderId "The order id.
  50. Note:  TWS orders have a fixed order id of ""0."""
  51. int m_permId The TWS id used to identify orders, remains the same over TWS sessions.
  52. double m_price The order execution price, not including commissions.
  53. int m_shares The number of shares filled.
  54. String m_side "Specifies if the transaction was a sale or a purchase. Valid values are:
  55. BOT
  56. SLD"
  57. String m_time The order execution time.
  58. '''
  59. pass
  60. @staticmethod
  61. def makeExeuctionFilter(executionFilterTuple):
  62. '''
  63. String m_acctCode Filter the results of the reqExecutions() method based on an account code. Note: this is only relevant for Financial Advisor (FA) accounts.
  64. int m_clientId Filter the results of the reqExecutions() method based on the clientId.
  65. String m_exchange Filter the results of the reqExecutions() method based on theorder exchange.
  66. String m_secType "Filter the results of the reqExecutions() method based on the order security type.
  67. Note: Refer to the Contract struct for the list of valid security types."
  68. String m_side "Filter the results of the reqExecutions() method based on the order action.
  69. Note: Refer to the Order class for the list of valid order actions."
  70. String m_symbol Filter the results of the reqExecutions() method based on the order symbol.
  71. String m_time "Filter the results of the reqExecutions() method based on execution reports received after the specified time.
  72. The format for timeFilter is ""yyyymmdd-hh:mm:ss"""
  73. '''
  74. new_filter = ExecutionFilter()
  75. new_filter.m_acctCode = executionFilterTuple[0]
  76. new_filter.m_clientId = executionFilterTuple[1]
  77. new_filter.m_exchange = executionFilterTuple[2]
  78. new_filter.m_secType = executionFilterTuple[3]
  79. new_filter.m_side = executionFilterTuple[4]
  80. new_filter.m_symbol = executionFilterTuple[5]
  81. new_filter.m_time = executionFilterTuple[6]
  82. return new_filter
  83. class ContractHelper(BaseHelper):
  84. def __init__(self, contractTuple):
  85. self.makeContract(contractTuple)
  86. @staticmethod
  87. def makeContract(contractTuple):
  88. newContract = Contract()
  89. newContract.m_symbol = contractTuple[0]
  90. newContract.m_secType = contractTuple[1]
  91. newContract.m_exchange = contractTuple[2]
  92. newContract.m_currency = contractTuple[3]
  93. newContract.m_expiry = contractTuple[4]
  94. newContract.m_strike = contractTuple[5]
  95. newContract.m_right = contractTuple[6]
  96. logging.debug( 'Contract Values:%s,%s,%s,%s,%s,%s,%s:' % contractTuple)
  97. return newContract
  98. @staticmethod
  99. def convert2Tuple(newContract):
  100. newContractTuple = (newContract.m_symbol,\
  101. newContract.m_secType,\
  102. newContract.m_exchange,\
  103. newContract.m_currency,\
  104. newContract.m_expiry,\
  105. newContract.m_strike,\
  106. newContract.m_right, newContract.m_conId)
  107. logging.debug( 'Contract Values:%s,%s,%s,%s,%s,%s,%s %s:' % newContractTuple)
  108. return newContractTuple
  109. @staticmethod
  110. def contract2kvstring(contract):
  111. return json.dumps(contract.__dict__)
  112. @staticmethod
  113. def kvstring2contract(sm_contract):
  114. return ContractHelper.kv2contract(json.loads(sm_contract))
  115. @staticmethod
  116. def kv2contract(m_contract):
  117. newContract = Contract()
  118. map(lambda x: newContract.__setattr__(x, m_contract[x].encode('ascii') if type(m_contract[x]) == unicode else m_contract[x]), m_contract.keys())
  119. return newContract
  120. @staticmethod
  121. def printContract(contract):
  122. s = '[%s-%s-%s-%s-%s-%s-%s-%s]' % (contract.m_symbol,
  123. contract.m_secType,
  124. contract.m_exchange,
  125. contract.m_currency,
  126. contract.m_expiry,
  127. contract.m_strike,
  128. contract.m_right,
  129. contract.m_conId)
  130. #logging.info(s)
  131. return s
  132. @staticmethod
  133. def makeRedisKey(contract):
  134. #print "makerediskey %s" % ContractHelper.printContract(contract)
  135. #20150904
  136. contract.m_strike = int(contract.m_strike)
  137. #contract.m_strike = contract.m_strike
  138. if contract.m_secType == 'OPT':
  139. s = '%s-%s-%s-%s' % (contract.m_symbol,
  140. contract.m_expiry,
  141. contract.m_strike,
  142. contract.m_right)
  143. else:
  144. s = '%s-%s-%s-%s' % (contract.m_symbol,
  145. contract.m_expiry,
  146. contract.m_secType, '')
  147. return s
  148. @staticmethod
  149. def makeRedisKeyEx(contract, old=False):
  150. # this routine is to circumvent a problem in makeRedisKey with
  151. # the key in position 3 having different meanings under different conditions.
  152. #
  153. #
  154. # to differentiate the keys generated by the old and new functions,
  155. # contract keys created using this routine have their last slot
  156. # hard coded a magic number 102
  157. if (old):
  158. return ContractHelper.makeRedisKey(contract)
  159. #contract.m_strike = int(contract.m_strike)
  160. #contract.m_strike = contract.m_strike
  161. # amend 10/22
  162. # add exchange to the key
  163. # s = '%s-%s-%s-%s-%s-%s-%s-%d' % (contract.m_symbol,
  164. # contract.m_expiry,
  165. # contract.m_strike,
  166. # contract.m_right,
  167. # contract.m_secType,
  168. # contract.m_currency,
  169. #
  170. # contract.m_exchange,
  171. #
  172. # 102)
  173. # amend 12/1
  174. #change strike format to 2 dp
  175. s = '%s-%s-%.2f-%s-%s-%s-%s-%d' % (contract.m_symbol,
  176. contract.m_expiry,
  177. float(contract.m_strike),
  178. contract.m_right,
  179. contract.m_secType,
  180. contract.m_currency,
  181. contract.m_exchange,
  182. 102)
  183. return s
  184. @staticmethod
  185. def is_equal(c1, c2):
  186. return ContractHelper.makeRedisKeyEx(c1) == ContractHelper.makeRedisKeyEx(c2)
  187. @staticmethod
  188. def makeContractfromRedisKeyEx(key):
  189. def utf2asc(x):
  190. return x.encode('ascii') if isinstance(x, unicode) else x
  191. #return map(lambda x: (x[0], ContractHelper.kvstring2contract(utf2asc(x[1]))), id_contracts)
  192. toks = utf2asc(key).split('-')
  193. c = Contract()
  194. c.m_symbol = toks[0]
  195. c.m_expiry = toks[1]
  196. c.m_strike = float(toks[2])
  197. c.m_right = toks[3]
  198. c.m_secType = toks[4]
  199. c.m_currency = toks[5]
  200. c.m_exchange = toks[6]
  201. return c
  202. # def str2dict(s):
  203. # return ast.literal_eval(s)
  204. def dict2str(dict):
  205. # enclose strings in double quotes
  206. return '{' + ', '.join('"%s" : %s' % (k, '"%s"' % v if type(v) == str else v) for k, v in dict.iteritems()) + '}'
  207. class HelperFunctions():
  208. @staticmethod
  209. def utf2asc(x):
  210. return x.encode('ascii') if isinstance(x, unicode) else x
  211. class ConfigMap():
  212. def kwargs_from_file(self, path):
  213. cfg = ConfigParser.ConfigParser()
  214. if len(cfg.read(path)) == 0:
  215. raise ValueError, "Failed to open config file [%s]" % path
  216. kwargs = {}
  217. for section in cfg.sections():
  218. optval_list = map(lambda o: (o, cfg.get(section, o)), cfg.options(section))
  219. for ov in optval_list:
  220. try:
  221. kwargs[ov[0]] = eval(ov[1])
  222. except:
  223. continue
  224. #logging.debug('ConfigMap: %s' % kwargs)
  225. return kwargs