Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- from __future__ import print_function
- import sys
- import socket
- import json
- TEAMNAME = "TOMANDJERRYPLUSRAHUL"
- order_id = 0
- marketSellPrices={}
- marketBuyPrices={}
- currentBuyOrders={}
- currentSellOrders={}
- pendingOrders={}
- currentStocksInPortfolio={}
- currentStocksInPortfolio['BOND']=0
- currentStocksInPortfolio['VALBZ']=0
- currentStocksInPortfolio['VALE']=0
- currentStocksInPortfolio['GS']=0
- currentStocksInPortfolio['MS']=0
- currentStocksInPortfolio['WFC']=0
- currentStocksInPortfolio['XLF']=0
- tradingIsOpen=True
- exchange=0
- def connect(mode):
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- if mode == 'test':
- s.connect(("test-exch-TOMANDJERRYPLUSRAHUL", 25000))
- elif mode == 'production':
- s.connect(("production", 25000))
- return s.makefile('rw', 1)
- # def connect(mode):
- # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- # s.connect(("test-exch-TOMANDJERRYPLUSRAHUL", 25000))
- # return s.makefile('rw', 1)
- def write(exchange, obj):
- json.dump(obj, exchange)
- exchange.write("\n")
- def read(exchange):
- msg = exchange.readline()
- try:
- return json.loads(msg)
- except:
- return None
- def buyOrder(stockName, price, quantity):
- global order_id
- write(exchange, {"type": "add", "team": TEAMNAME, "order_id": order_id,
- "symbol": stockName, "dir": "BUY", "price": price, "size": quantity})
- pendingOrders[order_id]=["BUY",order_id,stockName,price,quantity]
- order_id+=1
- def sellOrder(stockName, price, quantity):
- global order_id
- write(exchange, {"type": "add", "team": TEAMNAME, "order_id": order_id,
- "symbol": stockName, "dir": "SELL", "price": price, "size": quantity})
- pendingOrders[order_id]=["SELL",order_id,stockName,price,quantity]
- order_id+=1
- def processAckOrder(orderNum):
- data=pendingOrders[orderNum]
- #print("processing order",orderNum)
- #print("data ", data)
- if data[0]=='BUY':
- currentBuyOrders[orderNum]=[data[1],data[2],data[3],data[4]]
- if data[0]=='SELL':
- currentSellOrders[orderNum]=[data[1],data[2],data[3],data[4]]
- def bondArb():
- if tradingIsOpen:
- if 'BOND' in marketBuyPrices:
- bondPrices = marketBuyPrices['BOND']
- if len(bondPrices) >= 1 and bondPrices[0][0] > 1000:
- sellOrder('BOND', bondPrices[0][0], bondPrices[0][1])
- print("currentStocksInPortfolio", currentStocksInPortfolio)
- if 'BOND' in marketSellPrices:
- bondPrices = marketSellPrices['BOND']
- if len(bondPrices) >= 1 and bondPrices[0][0] < 1000:
- buyOrder('BOND', bondPrices[0][0], bondPrices[0][1])
- print("currentStocksInPortfolio", currentStocksInPortfolio)
- #New function
- pastLength=20
- threshForAverage=5
- bondHistory={} #maintains averages of price for each stock
- def average(arr):
- total=0.0
- for i in range(len(arr)):
- total+=arr[i]
- return total/len(arr)
- def updatePriceHistory(symbol, newPrice):
- if symbol in bondHistory:
- if len(bondHistory[symbol])<pastLength:
- bondHistory[symbol].append(newPrice)
- else:
- bondHistory[symbol]=bondHistory[symbol][1:pastLength]
- bondHistory[symbol].append(newPrice)
- else:
- bondHistory[symbol]=[newPrice]
- def funAverages():
- #if net change is +ve, we should buy
- for key in bondHistory:
- currentArr=bondHistory[key]
- if len(currentArr)==pastLength:
- prevAvg=currentArr[0:pastLength/2]
- prevAvg=average(prevAvg)
- futureAvg=currentArr[pastLength/2+1:pastLength]
- futureAvg=average(futureAvg)
- if futureAvg>prevAvg+threshForAverage:
- buyOrder(key,currentArr[len(currentArr)-1],20)
- #print("buying")
- if prevAvg+threshForAverage<futureAvg:
- sellOrder(key,currentArr[len(currentArr)-1],20)
- #print("selling")
- #if net change is -ve, we should sell
- #####
- def bondLiquidity():
- # see how much bond we are providing limit order
- # limit orders at 999, 998, ... price x we want (1000-x)^2+3
- for buyPrice in [999, 998, 997, 996]:
- pending_quantity = 0
- if 'BOND' in currentBuyOrders:
- for [price, quantity] in currentBuyOrders['BOND']:
- if price == buyPrice:
- pending_quantity += quantity
- if pending_quantity < (1000-buyPrice)^2+3:
- # print("pending_quantity", pending_quantity, "target", (1000-buyPrice)^2+3)
- buyOrder('BOND', buyPrice, (1000-buyPrice)^2+3-pending_quantity)
- for sellPrice in [1001, 1002, 1003, 1004]:
- pending_quantity = 0
- if 'BOND' in currentSellOrders:
- for [price, quantity] in currentSellOrders['BOND']:
- if price == sellPrice:
- pending_quantity += quantity
- if pending_quantity < (sellPrice-1000)^2+3:
- # print("pending_quantity", pending_quantity, "target", (sellPrice-1000)^2+3)
- sellOrder('BOND', sellPrice, (sellPrice-1000)^2+3-pending_quantity)
- callCounter=0
- operationMod=50
- def main(mode):
- global exchange
- global tradingIsOpen
- global callCounter
- exchange = connect(mode)
- write(exchange, {"type": "hello", "team": TEAMNAME})
- hello_from_exchange = read(exchange)
- print("The exchange replied:", hello_from_exchange, file=sys.stderr)
- print("starting trading")
- while tradingIsOpen:
- msg = read(exchange)
- if msg is None:
- continue
- if msg['type']=='book':#update book
- # print("updating book")
- currentStock=msg['symbol']
- buyPrices=msg['buy']
- sellPrices=msg['sell']
- marketBuyPrices[currentStock]=buyPrices
- marketSellPrices[currentStock]=sellPrices
- if len(buyPrices)>1:
- updatePriceHistory(currentStock,buyPrices[0][0])
- #print("book updated")
- #print("market Buy Positions")
- #print(marketBuyPrices)
- #print(marketSellPrices)
- if msg['type']=='ack':
- ackOrder=msg['order_id']
- processAckOrder(ackOrder)
- #print("order ack: ", ackOrder)
- if msg['type']=='fill':
- orderNum=msg['order_id']
- numFilled=msg['size']
- direction=msg['dir']
- stockNameFilled=msg['symbol']
- #print("order filled: ", stockNameFilled, " ", direction, " ", numFilled)
- if orderNum in pendingOrders:# if we never received ack
- processAckOrder(orderNum)
- if direction=='BUY':
- currentBuyOrders[orderNum][3]-=numFilled
- currentStocksInPortfolio[stockNameFilled]+=numFilled
- if direction=='SELL':
- currentSellOrders[orderNum][3]-=numFilled
- currentStocksInPortfolio[stockNameFilled]-=numFilled
- if msg['type']=="out":
- orderNum=msg['order_id']
- #print("order out ", orderNum)
- if orderNum in currentBuyOrders:
- del currentBuyOrders[orderNum]
- if orderNum in currentSellOrders:
- del currentSellOrders[orderNum]
- if msg['type']=='close':
- tradingIsOpen=False
- # call your strategies here
- funAverages()
- callCounter+=1
- if (callCounter%operationMod)==0:
- bondArb()
- #bondLiquidity()
- if (callCounter%50000)==0:
- print(currentStocksInPortfolio)
- if __name__ == "__main__":
- if len(sys.argv) != 2:
- print("Use case: python [filename.py] [test/production]")
- else:
- main(sys.argv[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement