예제 #1
0
def getTrades(filepath):
    header = True
    file = open(filepath, 'rb')
    
    for row in csv.reader(file.read().splitlines(), delimiter=','):
        if not header:
            try:
                date_str = row[10].split("/")
                today = date(int(date_str[2]), int(date_str[0]), int(date_str[1]))
                
                trade = Trade()
                trade.account = row[0]
                trade.symbol = row[1]
                trade.securityType = row[2]
                trade.side = row[3]
                trade.quantity = row[4]
                trade.price = row[5]
                trade.route = row[6]
                trade.destination = row[7]
                trade.liqFlag = row[9]
                trade.tradeDate = today
                trade.executionId = row[11]
                trade.save() # save into database
            except Exception, e:
                print str(e.message)
                continue
        else:
            header = False
예제 #2
0
def upload(request):
    if request.POST:
        try:
            file = request.FILES['content']
            count = 1
            for row in csv.reader(file.read().splitlines(), delimiter=','):
                if count != 1: # Ignore the header row
                    try:
                        Trade.objects.get( executionId = row[8] ) # ignore existed trade, identify by execution id
                    except Trade.DoesNotExist:
                        trade = Trade()
                        trade.account = row[0]
                        trade.symbol = row[1]
                        trade.side= row[2]
                        trade.quantity = row[3]
                        trade.price = row[4]
                        trade.broker = row[5]
                        trade.tradeDate = row[6]
                        trade.exchange = row[7]
                        trade.executionId = row[8]
                        trade.save()
                else:
                    count += 1
                
        except Exception, e:
            print e.message
            return HttpResponseRedirect("/trade/")
예제 #3
0
파일: views.py 프로젝트: brianjob/offseason
def propose_trade(request, team_id):
    players = []
    picks = []

    for key in request.POST:
        if 'player' in key:
            players.append(key.split('_')[1])
        elif 'pick' in key:
            picks.append(key.split('_')[1])

    t2 = Team.objects.get(pk=team_id)

    if len(players) == 0 and len(picks) == 0:
        msg = Message.objects.get(text=Message.EMPTY_TRADE)
        return HttpResponseRedirect(
            reverse('trades:league', args=(t2.league.id, )) + '?msg=' +
            str(msg.id))

    t1 = request.user.manager.team_set.get(league=t2.league)

    trade = Trade(team1=t1, team2=t2)

    trade.save()

    t1_picks = t2_picks = 0
    for pick_id in picks:
        pick = Pick.objects.get(pk=pick_id)
        if pick.team == t1:
            t1_picks += 1
        else:
            t2_picks += 1
        pp = PickPiece(trade=trade, pick=pick)
        pp.save()

    if t1_picks != t2_picks:
        trade.delete()
        msg = Message.objects.get(text=Message.UNEQUAL_PICKS)
        return HttpResponseRedirect(
            reverse('trades:league', args=(t1.league.id, )) + '?msg=' +
            str(msg.id))

    for player_id in players:
        player = Player.objects.get(pk=player_id)
        pp = PlayerPiece(trade=trade, player=player)
        pp.save()

    return HttpResponseRedirect(reverse('trades:trade', args=(trade.pk, )))
예제 #4
0
파일: views.py 프로젝트: brianjob/offseason
def propose_trade(request, team_id):
	players = []
	picks = []

	for key in request.POST:
		if 'player' in key:
			players.append(key.split('_')[1])
		elif 'pick' in key:
			picks.append(key.split('_')[1])

	t2 = Team.objects.get(pk=team_id)

	if len(players) == 0 and len(picks) == 0:
		msg = Message.objects.get(text=Message.EMPTY_TRADE)
		return HttpResponseRedirect(reverse('trades:league',
			args=(t2.league.id, )) + '?msg=' + str(msg.id))

	t1 = request.user.manager.team_set.get(league=t2.league)

	trade = Trade(team1=t1, team2=t2)

	trade.save()

	t1_picks = t2_picks = 0
	for pick_id in picks:
		pick = Pick.objects.get(pk=pick_id)
		if pick.team == t1:
			t1_picks += 1
		else:
			t2_picks += 1
		pp = PickPiece(trade=trade, pick=pick)
		pp.save()

	if t1_picks != t2_picks:
		trade.delete()
		msg = Message.objects.get(text=Message.UNEQUAL_PICKS)
		return HttpResponseRedirect(reverse('trades:league',
			args=(t1.league.id, )) + '?msg=' + str(msg.id))

	for player_id in players:
		player = Player.objects.get(pk=player_id)
		pp = PlayerPiece(trade=trade, player=player)
		pp.save()

	return HttpResponseRedirect(reverse('trades:trade', args=(trade.pk,)))
예제 #5
0
def index(request, address):
    if request.method == 'GET':
        trades = Trade.objects.filter(
            Q(first_party=address) | Q(second_party=address))
        trades = list(map(lambda trade: tradeToJson(trade), trades))
        trades = '[' + ','.join(trades) + ']'
        return HttpResponse("{\"trades\": " + str(trades) + "}")
    elif request.method == 'POST':
        body = json.loads(request.body.decode("utf-8"))
        trade = Trade(first_party=address,
                      second_party=body['secondParty'],
                      address=body['address'])
        trade.save()
        card = Card.objects.filter(id=body['card']).first()
        tradeItem = TradeItem(card=card, party=address, trade=trade)
        tradeItem.save()
        return HttpResponse(tradeToJson(trade))
    elif request.method == 'DELETE':
        body = json.loads(request.body.decode("utf-8"))
        Trade.objects.filter(address=body['address']).delete()
        return HttpResponse("{ \"address\": \"" + body['address'] + "\"}")
예제 #6
0
def getTradesByDir(path):
    print "Getting trades record from files..."    
    filelist = os.listdir(path)
    filelist.sort()
    log = open(ERROR_LOG, "a")
    
    for filename in filelist: # each file represent one day
        if string.find(filename, ".DS_Store"):
            continue
        filepath = os.path.join(path, filename)
        print filepath
        file = open(filepath, 'rb')
        header = True
        for row in csv.reader(file.read().splitlines(), delimiter=','): # all marks in this file
            if not header:
                try:
                    date_str = row[10].split("/")
                    today = date(int(date_str[2]), int(date_str[0]), int(date_str[1]))
                    
                    trade = Trade()
                    trade.account = row[0]
                    trade.symbol = row[1]
                    trade.securityType = row[2]
                    trade.side = row[3]
                    trade.quantity = row[4]
                    trade.price = row[5]
                    trade.route = row[6]
                    trade.destination = row[7]
                    trade.liqFlag = row[9]
                    trade.tradeDate = today
                    trade.executionId = row[11]
                    trade.save() # save into database
                except Exception, e:
                    print str(e.message)
                    log.write( strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
                    log.write( "\tGet trades file from %s failed: %s\n" % (filename, str(e.message)) )
                    continue
            else:
                header = False
        file.close()    
예제 #7
0
def getReport(today):
    
#    filepath = getTradeFile(today)
#    if filepath == None:
#        return False
    print "Getting reports..."
    filepath = './temp/WBPT_LiquidEOD_2013_01_07.csv'
    file = open(filepath, 'rb')
    log = open(ERROR_LOG, "a")
    
    refreshReports(today) # create 
    
    header = True
    for row in csv.reader(file.read().splitlines(), delimiter=','):
        if not header:
            try:
                date_str = row[10].split("/")
                today = date(int(date_str[2]), int(date_str[0]), int(date_str[1]))
                
                trade = Trade()
                trade.account = row[0]
                trade.symbol = row[1]
                trade.securityType = row[2]
                trade.side = row[3]
                trade.quantity = row[4]
                trade.price = row[5]
                trade.route = row[6]
                trade.destination = row[7]
                trade.liqFlag = row[9]
                trade.tradeDate = today
                trade.executionId = row[11]
                
                new_report = newReport(trade.account, trade.symbol, today) # get report
                
                # update report
                if trade.side == "BUY":
                    total = new_report.buys * new_report.buyAve
                    total += trade.quantity * trade.price # new total
                    new_report.buys += trade.quantity # new buys
                    new_report.buyAve = total / new_report.buys # new buy ave
            
                elif trade.side == "SEL" or trade.side == "SS":
                    total = new_report.sells * new_report.sellAve
                    total += trade.quantity * trade.price # new total
                    new_report.sells += trade.quantity # new sells
                    new_report.sellAve = total / new_report.sells # new sell ave
        
                else:
                    print "Error: Invalid Side."
                    continue
                
                trade.save() # save into database
                new_report.save() # save result
                
            except Exception, e:
                print str(e.message)
                log.write( strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
                log.write("\tGet report Failed: %s\n" % str(e.message))
                continue
        else:
            header = False