Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.38 KB | None | 0 0
  1.  
  2. #!/usr/bin/python
  3. from __future__ import print_function
  4.  
  5. import sys
  6. import socket
  7. import json
  8.  
  9. TEAMNAME = "TOMANDJERRYPLUSRAHUL"
  10. order_id = 0
  11. marketSellPrices={}
  12. marketBuyPrices={}
  13. currentBuyOrders={}
  14. currentSellOrders={}
  15. currentBuyOrdersConsolidated={'BOND':{},'VALBZ':{},'VALE':{}, 'GS':{},'MS':{},'WFC':{},'XLF':{}}
  16. currentSellOrdersConsolidated={'BOND':{},'VALBZ':{},'VALE':{}, 'GS':{},'MS':{},'WFC':{},'XLF':{}}
  17. pendingOrders={}
  18. currentStocksInPortfolio={}
  19. currentStocksInPortfolio['BOND']=0
  20. currentStocksInPortfolio['VALBZ']=0
  21. currentStocksInPortfolio['VALE']=0
  22. currentStocksInPortfolio['GS']=0
  23. currentStocksInPortfolio['MS']=0
  24. currentStocksInPortfolio['WFC']=0
  25. currentStocksInPortfolio['XLF']=0
  26.  
  27.  
  28.  
  29.  
  30. tradingIsOpen=True
  31.  
  32. exchange=0
  33.  
  34. def connect(mode):
  35. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  36. if mode == 'test':
  37. s.connect(("test-exch-TOMANDJERRYPLUSRAHUL", 25000))
  38. elif mode == 'production':
  39. s.connect(("production", 25000))
  40. return s.makefile('rw', 1)
  41.  
  42. # def connect(mode):
  43. # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  44. # s.connect(("test-exch-TOMANDJERRYPLUSRAHUL", 25000))
  45. # return s.makefile('rw', 1)
  46.  
  47.  
  48. def write(exchange, obj):
  49. json.dump(obj, exchange)
  50. exchange.write("\n")
  51.  
  52. def read(exchange):
  53. msg = exchange.readline()
  54. try:
  55. return json.loads(msg)
  56. except:
  57. return None
  58.  
  59. def fairvalue(symbol,mode='wtavg1'):
  60. if mode == 'buy':
  61. if symbol in marketBuyPrices:
  62. return marketBuyPrices[symbol][0]
  63. else:
  64. return None
  65. if mode == 'sell':
  66. if symbol in marketSellPrices:
  67. return marketSellPrices[symbol][0]
  68. else:
  69. return None
  70. if mode == 'wtavg1':
  71. if symbol not in marketBuyPrices or symbol not in marketSellPrices:
  72. return marketBuyPrices[symbol][0]
  73. else:
  74. return (marketBuyPrices[symbol][0]*marketSellPrices[symbol][1]
  75. +marketBuyPrices[symbol][1]*marketSellPrices[symbol][0])/(
  76. marketBuyPrices[symbol][1]+marketSellPrices[symbol][1])
  77.  
  78.  
  79. def ValArb01():
  80. # if fairvalue(VALBZ) + tolerance < fairvalue(VALE), penny the bid of VALBZ
  81. pass
  82. # try:
  83. # tolerance = 2
  84. # if fairvalue('VALBZ') + tolerance < fairvalue('VALE'):
  85. # # highest bid of VALBZ
  86. # marketBuyPrices[]
  87. # except:
  88. # pass
  89.  
  90.  
  91. def add_currentBuyOrdersConsolidated(stockName, price, quantity):
  92. global currentBuyOrdersConsolidated
  93. if price in currentBuyOrdersConsolidated[stockName]:
  94. currentBuyOrdersConsolidated[stockName][price] += quantity
  95. # quantity is negative when the order is filled (taken off the "current (unfilled)" buy order)
  96. else:
  97. currentBuyOrdersConsolidated[stockName][price] = quantity
  98.  
  99. def add_currentSellOrdersConsolidated(stockName, price, quantity):
  100. global currentSellOrdersConsolidated
  101. if price in currentSellOrdersConsolidated[stockName]:
  102. currentSellOrdersConsolidated[stockName][price] += quantity
  103. else:
  104. currentSellOrdersConsolidated[stockName][price] = quantity
  105.  
  106.  
  107. def buyOrder(stockName, price, quantity):
  108. global order_id
  109. write(exchange, {"type": "add", "team": TEAMNAME, "order_id": order_id,
  110. "symbol": stockName, "dir": "BUY", "price": price, "size": quantity})
  111. pendingOrders[order_id]=["BUY",order_id,stockName,price,quantity]
  112. add_currentBuyOrdersConsolidated(stockName, price, quantity)
  113. order_id+=1
  114.  
  115. def sellOrder(stockName, price, quantity):
  116. global order_id
  117. write(exchange, {"type": "add", "team": TEAMNAME, "order_id": order_id,
  118. "symbol": stockName, "dir": "SELL", "price": price, "size": quantity})
  119. pendingOrders[order_id]=["SELL",order_id,stockName,price,quantity]
  120. add_currentSellOrdersConsolidated(stockName, price, quantity)
  121. order_id+=1
  122.  
  123. def processAckOrder(orderNum):
  124. data=pendingOrders[orderNum]
  125. #print("processing order",orderNum)
  126. #print("data ", data)
  127. # data 1-4 are order_id,stockName,price,quantity
  128. [order_id,stockName,price,quantity]=[data[1],data[2],data[3],data[4]]
  129. if data[0]=='BUY':
  130. currentBuyOrders[orderNum]=[data[1],data[2],data[3],data[4]]
  131.  
  132. if data[0]=='SELL':
  133. currentSellOrders[orderNum]=[data[1],data[2],data[3],data[4]]
  134.  
  135.  
  136.  
  137. def bondArb():
  138. if tradingIsOpen:
  139. if 'BOND' in marketBuyPrices:
  140. bondPrices = marketBuyPrices['BOND']
  141. if len(bondPrices) >= 1 and bondPrices[0][0] > 1000:
  142. sellOrder('BOND', bondPrices[0][0], bondPrices[0][1])
  143. print("currentStocksInPortfolio", currentStocksInPortfolio)
  144. if 'BOND' in marketSellPrices:
  145. bondPrices = marketSellPrices['BOND']
  146. if len(bondPrices) >= 1 and bondPrices[0][0] < 1000:
  147. buyOrder('BOND', bondPrices[0][0], bondPrices[0][1])
  148. print("currentStocksInPortfolio", currentStocksInPortfolio)
  149. #New function
  150.  
  151. pastLength=20
  152. threshForAverage=5
  153. bondHistory={} #maintains averages of price for each stock
  154. liquidityMax=50
  155. def average(arr):
  156. total=0.0
  157. for i in range(len(arr)):
  158. total+=arr[i]
  159. return total/len(arr)
  160.  
  161.  
  162. def updatePriceHistory(symbol, newPrice):
  163. if symbol in bondHistory:
  164. if len(bondHistory[symbol])<pastLength:
  165. bondHistory[symbol].append(newPrice)
  166. else:
  167. bondHistory[symbol]=bondHistory[symbol][1:pastLength]
  168. bondHistory[symbol].append(newPrice)
  169. else:
  170. bondHistory[symbol]=[newPrice]
  171.  
  172.  
  173. def getOutstandingBuySize():
  174. tally=0
  175. for key in currentBuyOrders:
  176. tally+=currentBuyOrders[key][3]
  177. return tally
  178. def getOutstandingSellSize():
  179. tally=0
  180. for key in currentSellOrders:
  181. tally+=currentSellOrders[key][3]
  182. return tally
  183.  
  184. def funAverages():
  185. #if net change is +ve, we should buy
  186. for key in bondHistory:
  187. currentArr=bondHistory[key]
  188. if len(currentArr)==pastLength:
  189. prevAvg=currentArr[0:pastLength/2]
  190. prevAvg=average(prevAvg)
  191. futureAvg=currentArr[pastLength/2+1:pastLength]
  192. futureAvg=average(futureAvg)
  193. if futureAvg>prevAvg+threshForAverage:
  194. if getOutstandingBuySize()<liquidityMax:
  195. buyOrder(key,currentArr[len(currentArr)-1],20)
  196. #print("buying")
  197. if prevAvg+threshForAverage<futureAvg:
  198. if getOutstandingSellSize()<liquidityMax:
  199. sellOrder(key,currentArr[len(currentArr)-1],20)
  200. #print("selling")
  201. #if net change is -ve, we should sell
  202.  
  203.  
  204. #####
  205.  
  206. def bondLiquidity():
  207. # see how much bond we are providing limit order
  208.  
  209. # limit orders at 999, 998, ... price x we want (1000-x)^2+3
  210. for buyPrice in [999, 998, 997, 996]:
  211. pending_quantity = 0
  212. if 'BOND' in currentBuyOrders:
  213. for [price, quantity] in currentBuyOrders['BOND']:
  214. if price == buyPrice:
  215. pending_quantity += quantity
  216. if pending_quantity < (1000-buyPrice)^2+3:
  217. # print("pending_quantity", pending_quantity, "target", (1000-buyPrice)^2+3)
  218. buyOrder('BOND', buyPrice, (1000-buyPrice)^2+3-pending_quantity)
  219. for sellPrice in [1001, 1002, 1003, 1004]:
  220. pending_quantity = 0
  221. if 'BOND' in currentSellOrders:
  222. for [price, quantity] in currentSellOrders['BOND']:
  223. if price == sellPrice:
  224. pending_quantity += quantity
  225. if pending_quantity < (sellPrice-1000)^2+3:
  226. # print("pending_quantity", pending_quantity, "target", (sellPrice-1000)^2+3)
  227. sellOrder('BOND', sellPrice, (sellPrice-1000)^2+3-pending_quantity)
  228.  
  229.  
  230.  
  231.  
  232.  
  233. callCounter=0
  234. operationMod=50
  235.  
  236. def main(mode):
  237. global exchange
  238. global tradingIsOpen
  239. global callCounter
  240. exchange = connect(mode)
  241. write(exchange, {"type": "hello", "team": TEAMNAME})
  242. hello_from_exchange = read(exchange)
  243. print("The exchange replied:", hello_from_exchange, file=sys.stderr)
  244. print("starting trading")
  245. while tradingIsOpen:
  246. msg = read(exchange)
  247. if msg is None:
  248. continue
  249. if msg['type']=='book':#update book
  250. # print("updating book")
  251. currentStock=msg['symbol']
  252. buyPrices=msg['buy']
  253. sellPrices=msg['sell']
  254. marketBuyPrices[currentStock]=buyPrices
  255. marketSellPrices[currentStock]=sellPrices
  256. if len(buyPrices)>1:
  257. updatePriceHistory(currentStock,buyPrices[0][0])
  258. #print("book updated")
  259. #print("market Buy Positions")
  260. #print(marketBuyPrices)
  261. #print(marketSellPrices)
  262. if msg['type']=='ack':
  263. ackOrder=msg['order_id']
  264. processAckOrder(ackOrder)
  265. #print("order ack: ", ackOrder)
  266. if msg['type']=='fill':
  267. orderNum=msg['order_id']
  268. numFilled=msg['size']
  269. direction=msg['dir']
  270. stockNameFilled=msg['symbol']
  271.  
  272. if orderNum in pendingOrders:# if we never received ack
  273. processAckOrder(orderNum)
  274. # fill message doesn't give us price, so we find it in our records
  275. if direction == 'BUY':
  276. price = currentBuyOrders[orderNum][2]
  277. if direction == 'SELL':
  278. price = currentSellOrders[orderNum][2]
  279. # print("order filled: ", stockNameFilled, " ", direction, " ", price, " ", numFilled)
  280.  
  281. if direction=='BUY':
  282. currentBuyOrders[orderNum][3]-=numFilled
  283. currentStocksInPortfolio[stockNameFilled]+=numFilled
  284. # stockName, price, quantity
  285. add_currentBuyOrdersConsolidated(stockNameFilled, price, -numFilled)
  286. if direction=='SELL':
  287. currentSellOrders[orderNum][3]-=numFilled
  288. currentStocksInPortfolio[stockNameFilled]-=numFilled
  289. add_currentSellOrdersConsolidated(stockNameFilled, price, -numFilled)
  290.  
  291.  
  292. if msg['type']=="out":
  293. orderNum=msg['order_id']
  294. #print("order out ", orderNum)
  295. if orderNum in currentBuyOrders:
  296. del currentBuyOrders[orderNum]
  297. if orderNum in currentSellOrders:
  298. del currentSellOrders[orderNum]
  299. if msg['type']=='close':
  300. tradingIsOpen=False
  301.  
  302. # call your strategies here
  303.  
  304. funAverages()
  305. callCounter+=1
  306. #if (callCounter%operationMod)==0:
  307. #bondArb()
  308. #bondLiquidity()
  309.  
  310. if (callCounter%1000) ==0:
  311. print("currentBuyOrdersConsolidated", currentBuyOrdersConsolidated)
  312. print("currentSellOrdersConsolidated", currentSellOrdersConsolidated)
  313.  
  314.  
  315. if (callCounter%50000)==0:
  316. print("currentStocksInPortfolio", currentStocksInPortfolio)
  317.  
  318.  
  319.  
  320.  
  321.  
  322.  
  323. if __name__ == "__main__":
  324. if len(sys.argv) != 2:
  325. print("Use case: python [filename.py] [test/production]")
  326. else:
  327. main(sys.argv[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement