Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.01 KB | None | 0 0
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3.  
  4. import sys
  5. import socket
  6. import json
  7.  
  8. TEAMNAME = "TOMANDJERRYPLUSRAHUL"
  9. order_id = 0
  10. marketSellPrices={}
  11. marketBuyPrices={}
  12. currentBuyOrders={}
  13. currentSellOrders={}
  14. pendingOrders={}
  15. currentStocksInPortfolio={}
  16. currentStocksInPortfolio['BOND']=0
  17. currentStocksInPortfolio['VALBZ']=0
  18. currentStocksInPortfolio['VALE']=0
  19. currentStocksInPortfolio['GS']=0
  20. currentStocksInPortfolio['MS']=0
  21. currentStocksInPortfolio['WFC']=0
  22. currentStocksInPortfolio['XLF']=0
  23.  
  24.  
  25. tradingIsOpen=True
  26.  
  27. exchange=0
  28.  
  29. def connect(mode):
  30. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  31. if mode == 'test':
  32. s.connect(("test-exch-TOMANDJERRYPLUSRAHUL", 25000))
  33. elif mode == 'production':
  34. s.connect(("production", 25000))
  35. return s.makefile('rw', 1)
  36.  
  37. # def connect(mode):
  38. # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  39. # s.connect(("test-exch-TOMANDJERRYPLUSRAHUL", 25000))
  40. # return s.makefile('rw', 1)
  41.  
  42.  
  43. def write(exchange, obj):
  44. json.dump(obj, exchange)
  45. exchange.write("\n")
  46.  
  47. def read(exchange):
  48. msg = exchange.readline()
  49. try:
  50. return json.loads(msg)
  51. except:
  52. return None
  53.  
  54.  
  55. def buyOrder(stockName, price, quantity):
  56. global order_id
  57. write(exchange, {"type": "add", "team": TEAMNAME, "order_id": order_id,
  58. "symbol": stockName, "dir": "BUY", "price": price, "size": quantity})
  59. pendingOrders[order_id]=["BUY",order_id,stockName,price,quantity]
  60. order_id+=1
  61.  
  62. def sellOrder(stockName, price, quantity):
  63. global order_id
  64. write(exchange, {"type": "add", "team": TEAMNAME, "order_id": order_id,
  65. "symbol": stockName, "dir": "SELL", "price": price, "size": quantity})
  66. pendingOrders[order_id]=["SELL",order_id,stockName,price,quantity]
  67. order_id+=1
  68.  
  69. def processAckOrder(orderNum):
  70. data=pendingOrders[orderNum]
  71. #print("processing order",orderNum)
  72. #print("data ", data)
  73. if data[0]=='BUY':
  74. currentBuyOrders[orderNum]=[data[1],data[2],data[3],data[4]]
  75. if data[0]=='SELL':
  76. currentSellOrders[orderNum]=[data[1],data[2],data[3],data[4]]
  77.  
  78.  
  79. def bondArb():
  80. if tradingIsOpen:
  81. if 'BOND' in marketBuyPrices:
  82. bondPrices = marketBuyPrices['BOND']
  83. if len(bondPrices) >= 1 and bondPrices[0][0] > 1000:
  84. sellOrder('BOND', bondPrices[0][0], bondPrices[0][1])
  85. print("currentStocksInPortfolio", currentStocksInPortfolio)
  86. if 'BOND' in marketSellPrices:
  87. bondPrices = marketSellPrices['BOND']
  88. if len(bondPrices) >= 1 and bondPrices[0][0] < 1000:
  89. buyOrder('BOND', bondPrices[0][0], bondPrices[0][1])
  90. print("currentStocksInPortfolio", currentStocksInPortfolio)
  91. #New function
  92.  
  93. pastLength=20
  94. threshForAverage=5
  95. bondHistory={} #maintains averages of price for each stock
  96.  
  97. def average(arr):
  98. total=0.0
  99. for i in range(len(arr)):
  100. total+=arr[i]
  101. return total/len(arr)
  102.  
  103.  
  104. def updatePriceHistory(symbol, newPrice):
  105. if symbol in bondHistory:
  106. if len(bondHistory[symbol])<pastLength:
  107. bondHistory[symbol].append(newPrice)
  108. else:
  109. bondHistory[symbol]=bondHistory[symbol][1:pastLength]
  110. bondHistory[symbol].append(newPrice)
  111. else:
  112. bondHistory[symbol]=[newPrice]
  113.  
  114.  
  115. def funAverages():
  116. #if net change is +ve, we should buy
  117. for key in bondHistory:
  118. currentArr=bondHistory[key]
  119. if len(currentArr)==pastLength:
  120. prevAvg=currentArr[0:pastLength/2]
  121. prevAvg=average(prevAvg)
  122. futureAvg=currentArr[pastLength/2+1:pastLength]
  123. futureAvg=average(futureAvg)
  124. if futureAvg>prevAvg+threshForAverage:
  125. buyOrder(key,currentArr[len(currentArr)-1],20)
  126. #print("buying")
  127. if prevAvg+threshForAverage<futureAvg:
  128. sellOrder(key,currentArr[len(currentArr)-1],20)
  129. #print("selling")
  130. #if net change is -ve, we should sell
  131.  
  132.  
  133. #####
  134.  
  135. def bondLiquidity():
  136. # see how much bond we are providing limit order
  137.  
  138. # limit orders at 999, 998, ... price x we want (1000-x)^2+3
  139. for buyPrice in [999, 998, 997, 996]:
  140. pending_quantity = 0
  141. if 'BOND' in currentBuyOrders:
  142. for [price, quantity] in currentBuyOrders['BOND']:
  143. if price == buyPrice:
  144. pending_quantity += quantity
  145. if pending_quantity < (1000-buyPrice)^2+3:
  146. # print("pending_quantity", pending_quantity, "target", (1000-buyPrice)^2+3)
  147. buyOrder('BOND', buyPrice, (1000-buyPrice)^2+3-pending_quantity)
  148. for sellPrice in [1001, 1002, 1003, 1004]:
  149. pending_quantity = 0
  150. if 'BOND' in currentSellOrders:
  151. for [price, quantity] in currentSellOrders['BOND']:
  152. if price == sellPrice:
  153. pending_quantity += quantity
  154. if pending_quantity < (sellPrice-1000)^2+3:
  155. # print("pending_quantity", pending_quantity, "target", (sellPrice-1000)^2+3)
  156. sellOrder('BOND', sellPrice, (sellPrice-1000)^2+3-pending_quantity)
  157.  
  158.  
  159.  
  160.  
  161.  
  162. callCounter=0
  163. operationMod=50
  164.  
  165. def main(mode):
  166. global exchange
  167. global tradingIsOpen
  168. global callCounter
  169. exchange = connect(mode)
  170. write(exchange, {"type": "hello", "team": TEAMNAME})
  171. hello_from_exchange = read(exchange)
  172. print("The exchange replied:", hello_from_exchange, file=sys.stderr)
  173. print("starting trading")
  174. while tradingIsOpen:
  175. msg = read(exchange)
  176. if msg is None:
  177. continue
  178. if msg['type']=='book':#update book
  179. # print("updating book")
  180. currentStock=msg['symbol']
  181. buyPrices=msg['buy']
  182. sellPrices=msg['sell']
  183. marketBuyPrices[currentStock]=buyPrices
  184. marketSellPrices[currentStock]=sellPrices
  185. if len(buyPrices)>1:
  186. updatePriceHistory(currentStock,buyPrices[0][0])
  187. #print("book updated")
  188. #print("market Buy Positions")
  189. #print(marketBuyPrices)
  190. #print(marketSellPrices)
  191. if msg['type']=='ack':
  192. ackOrder=msg['order_id']
  193. processAckOrder(ackOrder)
  194. #print("order ack: ", ackOrder)
  195. if msg['type']=='fill':
  196. orderNum=msg['order_id']
  197. numFilled=msg['size']
  198. direction=msg['dir']
  199. stockNameFilled=msg['symbol']
  200. #print("order filled: ", stockNameFilled, " ", direction, " ", numFilled)
  201. if orderNum in pendingOrders:# if we never received ack
  202. processAckOrder(orderNum)
  203. if direction=='BUY':
  204. currentBuyOrders[orderNum][3]-=numFilled
  205. currentStocksInPortfolio[stockNameFilled]+=numFilled
  206. if direction=='SELL':
  207. currentSellOrders[orderNum][3]-=numFilled
  208. currentStocksInPortfolio[stockNameFilled]-=numFilled
  209. if msg['type']=="out":
  210. orderNum=msg['order_id']
  211. #print("order out ", orderNum)
  212. if orderNum in currentBuyOrders:
  213. del currentBuyOrders[orderNum]
  214. if orderNum in currentSellOrders:
  215. del currentSellOrders[orderNum]
  216. if msg['type']=='close':
  217. tradingIsOpen=False
  218.  
  219. # call your strategies here
  220.  
  221. funAverages()
  222.  
  223. callCounter+=1
  224. if (callCounter%operationMod)==0:
  225. bondArb()
  226. #bondLiquidity()
  227.  
  228. if (callCounter%50000)==0:
  229. print(currentStocksInPortfolio)
  230.  
  231.  
  232.  
  233.  
  234.  
  235.  
  236. if __name__ == "__main__":
  237. if len(sys.argv) != 2:
  238. print("Use case: python [filename.py] [test/production]")
  239. else:
  240. main(sys.argv[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement