def offers_handler(): items = Item.objects.all() offers = Offer.objects.filter(is_active=True) for item in items: for buy_offer in offers.filter(item=item, order_type=OrderType.BUY.value): buy_offer_unit_price = ItemTransfer.get_unit_price(buy_offer) sale_offers = offers.filter(item=item, order_type=OrderType.SALE.value, price__lte=buy_offer.price) valid_sale_offers = filter( lambda offer: buy_offer_unit_price >= ItemTransfer. get_unit_price(offer), sale_offers) for sale_offer in sorted( valid_sale_offers, key=lambda offer: ItemTransfer.get_unit_price(offer)): diff = min(buy_offer.quantity, sale_offer.quantity) Trade(item=item, seller=sale_offer.user, buyer=buy_offer.user, quantity=diff, unit_price=sale_offer.price / sale_offer.quantity, buyer_offer=buy_offer, seller_offer=sale_offer).save() [ ItemTransfer.handling_offer(offer, diff) for offer in [buy_offer, sale_offer] ] ItemTransfer.items_transfer(sale_offer, diff) ItemTransfer.items_transfer(buy_offer, diff, True) if not buy_offer.quantity: break
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,)))
def test_list_all_queryset(self): """Retrieve all trades ordered by date booked""" queryset = Trade.list_all(return_queryset=True) self.assertEqual(len(queryset), 3) last_timestamp = 0 for item in queryset: self.assertGreater(item.date_booked.timestamp(), last_timestamp) last_timestamp = item.date_booked.timestamp()
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'] + "\"}")
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, )))
def buy_offer(request, pk): sale_offer = get_object_or_404(Offer, id=pk) buy_offer = Offer(user=request.user, quantity=sale_offer.quantity, entry_quantity=sale_offer.quantity, price=sale_offer.price, order_type=OrderType.BUY.value, item=sale_offer.item) buy_offer.save() diff = min(buy_offer.quantity, sale_offer.quantity) Trade(item=sale_offer.item, seller=sale_offer.user, buyer=buy_offer.user, quantity=diff, unit_price=sale_offer.price / sale_offer.quantity, buyer_offer=buy_offer, seller_offer=sale_offer).save() [ ItemTransfer.handling_offer(offer, diff) for offer in [buy_offer, sale_offer] ] ItemTransfer.items_transfer(sale_offer, diff) ItemTransfer.items_transfer(buy_offer, diff, True)
def get_trade(): return trade or Trade()
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
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()
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
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/")