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={}
- currentBuyOrdersConsolidated={'BOND':{},'VALBZ':{},'VALE':{}, 'GS':{},'MS':{},'WFC':{},'XLF':{}}
- currentSellOrdersConsolidated={'BOND':{},'VALBZ':{},'VALE':{}, 'GS':{},'MS':{},'WFC':{},'XLF':{}}
- 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 fairvalue(symbol,mode='wtavg1'):
- if mode == 'buy':
- if symbol in marketBuyPrices:
- return marketBuyPrices[symbol][0]
- else:
- return None
- if mode == 'sell':
- if symbol in marketSellPrices:
- return marketSellPrices[symbol][0]
- else:
- return None
- if mode == 'wtavg1':
- if symbol not in marketBuyPrices or symbol not in marketSellPrices:
- return marketBuyPrices[symbol][0]
- else:
- return (marketBuyPrices[symbol][0]*marketSellPrices[symbol][1]
- +marketBuyPrices[symbol][1]*marketSellPrices[symbol][0])/(
- marketBuyPrices[symbol][1]+marketSellPrices[symbol][1])
- def ValArb01():
- # if fairvalue(VALBZ) + tolerance < fairvalue(VALE), penny the bid of VALBZ
- pass
- # try:
- # tolerance = 2
- # if fairvalue('VALBZ') + tolerance < fairvalue('VALE'):
- # # highest bid of VALBZ
- # marketBuyPrices[]
- # except:
- # pass
- def add_currentBuyOrdersConsolidated(stockName, price, quantity):
- global currentBuyOrdersConsolidated
- if price in currentBuyOrdersConsolidated[stockName]:
- currentBuyOrdersConsolidated[stockName][price] += quantity
- # quantity is negative when the order is filled (taken off the "current (unfilled)" buy order)
- else:
- currentBuyOrdersConsolidated[stockName][price] = quantity
- def add_currentSellOrdersConsolidated(stockName, price, quantity):
- global currentSellOrdersConsolidated
- if price in currentSellOrdersConsolidated[stockName]:
- currentSellOrdersConsolidated[stockName][price] += quantity
- else:
- currentSellOrdersConsolidated[stockName][price] = quantity
- 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]
- add_currentBuyOrdersConsolidated(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]
- add_currentSellOrdersConsolidated(stockName, price, quantity)
- order_id+=1
- def processAckOrder(orderNum):
- data=pendingOrders[orderNum]
- #print("processing order",orderNum)
- #print("data ", data)
- # data 1-4 are order_id,stockName,price,quantity
- [order_id,stockName,price,quantity]=[data[1],data[2],data[3],data[4]]
- 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
- liquidityMax=50
- 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 getOutstandingBuySize():
- tally=0
- for key in currentBuyOrders:
- tally+=currentBuyOrders[key][3]
- return tally
- def getOutstandingSellSize():
- tally=0
- for key in currentSellOrders:
- tally+=currentSellOrders[key][3]
- return tally
- 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:
- if getOutstandingBuySize()<liquidityMax:
- buyOrder(key,currentArr[len(currentArr)-1],20)
- #print("buying")
- if prevAvg+threshForAverage<futureAvg:
- if getOutstandingSellSize()<liquidityMax:
- 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']
- if orderNum in pendingOrders:# if we never received ack
- processAckOrder(orderNum)
- # fill message doesn't give us price, so we find it in our records
- if direction == 'BUY':
- price = currentBuyOrders[orderNum][2]
- if direction == 'SELL':
- price = currentSellOrders[orderNum][2]
- # print("order filled: ", stockNameFilled, " ", direction, " ", price, " ", numFilled)
- if direction=='BUY':
- currentBuyOrders[orderNum][3]-=numFilled
- currentStocksInPortfolio[stockNameFilled]+=numFilled
- # stockName, price, quantity
- add_currentBuyOrdersConsolidated(stockNameFilled, price, -numFilled)
- if direction=='SELL':
- currentSellOrders[orderNum][3]-=numFilled
- currentStocksInPortfolio[stockNameFilled]-=numFilled
- add_currentSellOrdersConsolidated(stockNameFilled, price, -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%1000) ==0:
- print("currentBuyOrdersConsolidated", currentBuyOrdersConsolidated)
- print("currentSellOrdersConsolidated", currentSellOrdersConsolidated)
- if (callCounter%50000)==0:
- print("currentStocksInPortfolio", 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