Ejemplo n.º 1
0
    def process_transaction(self, session, quote, trigger):
        # Calculate real price of stock purchase based on current quote
        user = trigger.user
        quantity = amount_to_quantity(quote, trigger.amount)
        real_amount = quote * quantity

        log.debug('Trigger %d: Buying %d units of %s (%s total) for %s', 
                trigger.id, quantity, trigger.stock_symbol, real_amount, user.username)

        # Use reserve balance to buy stock
        user.reserve_balance -= trigger.amount

        # Put extra money back in users account
        extra = trigger.amount - real_amount
        log.debug('Trigger %d: Extra money left over after purchase: %s', trigger.id, extra)
        user.account_balance += extra

        # create or update the StockPurchase for this stock symbol
        stock = session.query(StockPurchase).filter_by(
            user=user, stock_symbol=trigger.stock_symbol
        ).first()
        if not stock:
            stock = StockPurchase(user=user,
                    stock_symbol=trigger.stock_symbol,
                    quantity=quantity)
        else:
            stock.quantity = stock.quantity + quantity

        session.delete(trigger)

        session.commit()

        xml.log_trigger('SET_BUY_TRIGGER', trigger, status_message='Trigger item bought')
Ejemplo n.º 2
0
    def run(self, username):
        self.session = get_session()
        user = self.session.query(User).filter_by(username=username).first()
        if not user:
            xml.log_error('COMMIT_BUY', 'username not found')
            raise UserNotFoundError(username)
        transaction = self.session.query(Transaction).filter_by(
            username=user.username, operation='BUY', committed=False
        ).first()
        if not transaction:
            xml.log_error('COMMIT_BUY', 'no buy tranaction found')
            raise NoBuyTransactionError(username)

        if (datetime.now() - transaction.creation_time) > config.TRANSACTION_TIMEOUT:
            self.session.delete(transaction)
            self.session.commit()
            raise ExpiredBuyTransactionError(username)

        price = transaction.stock_value * transaction.quantity

        user.account_balance -= price
        transaction.committed = True

        # create or update the StockPurchase for this stock symbol
        stock = self.session.query(StockPurchase).filter_by(
            user=user, stock_symbol=transaction.stock_symbol
        ).first()
        if not stock:
            stock = StockPurchase(user=user,
                    stock_symbol=transaction.stock_symbol,
                    quantity=transaction.quantity)
        else:
            stock.quantity = stock.quantity + transaction.quantity

        self.session.commit()
        xml.log_transaction('COMMIT_BUY', transaction, status_message='success')

        return xml.ResultResponse('success')