def buy(self, word, quantity, tweeted=None): latest_batch = Batch.objects.latest() price = word.latest_price(force=True) buy_price = max(price, consts.MIN_BUY_PRICE) if buy_price == 0: raise OrderError("You can't buy a word with a price of $0.00.") buy_price_with_commission = buy_price slots_held = self.slots_held() slots_available = max(0, consts.MAX_SLOTS - slots_held) if quantity > slots_available: raise OrderError("You don't have enough slots available to buy %d of this word." % quantity) try: holding = self.holding_set.filter(word=word)[0] except IndexError: holding = None if self.cash < buy_price_with_commission * quantity: raise OrderError("You can't afford %s units" % priceformat.quantity(quantity)) if holding is not None: holding.record() else: holding = Holding(user_round=self, word=word) holding.quantity = 0 holding.slots = 0 holding.quantity += quantity holding.slots += quantity * word.slots holding.current_value = price * holding.quantity holding.value_at_purchase = buy_price_with_commission * holding.quantity holding.save() # this has to be after the holding because it relies on the # holding to be properly updated to calculate the new value self.cash -= buy_price_with_commission * quantity self.last_trade = datetime.datetime.now() self.save() self.update_current_value() new_order = Order(user_round=self, word=word, order_type='B', quantity=quantity, price=buy_price_with_commission, tweeted=tweeted) new_order.save() return new_order
def confirmation(self): return "%s units %s for $%s." % (priceformat.quantity(self.quantity), "bought" if self.order_type == 'B' else "sold", priceformat.currency(self.cash_exchanged))
def description(self): return "%s %s %s" % ( self.order_type_description, priceformat.quantity(self.quantity), self.word.content )