Пример #1
0
    def sell(self, ticker, quantity):
        """
            SELL stock. checks if a stock exists in the user's positions and
            has sufficient shares. creates a new Trade and modifies the Position
            as well as adding to the user's balance. returns nothing
        """
        trade = Trade()
        current_price = get_price(ticker)
        mv = current_price * int(quantity)

        trade.account_id = self.account_id
        trade.volume = quantity
        trade.ticker = ticker
        trade.price = current_price
        trade.market_value = mv * -1

        self.balance += mv
        self.update_balance()

        position = Position()
        position.account_id = self.account_id
        position.ticker = trade.ticker
        stored_position = Position.select_one_where(
            'WHERE account_id=? and ticker=?',
            (position.account_id, position.ticker))
        if stored_position:
            position.num_shares = stored_position.num_shares
            position.position_id = stored_position.position_id
            if stored_position.num_shares < trade.volume or stored_position.num_shares == 0:
                transaction_error('Not enough shares')
            else:
                trade.save()
                if stored_position:
                    position.num_shares = trade.volume
                else:
                    position.num_shares -= trade.volume
                position.save()
        else:
            transaction_error('Ticker {} is invalid'.format(trade.ticker))
Пример #2
0
    def buy(self, ticker, quantity):
        """
            BUY stock. checks if a stock exists in the user's positions and
            has sufficient shares. creates a new Trade and modifies the Position
            as well as adding to the user's balance. returns nothing
        """
        trade = Trade()
        current_price = get_price(ticker)
        mv = current_price * int(quantity)

        if self.balance < mv:
            transaction_error('Insufficient funds')
        else:
            trade.account_id = self.account_id
            trade.volume = quantity
            trade.ticker = ticker
            trade.price = current_price
            trade.market_value = mv

            self.balance -= mv
            self.update_balance()

            position = Position()
            position.account_id = self.account_id
            position.ticker = trade.ticker
            stored_position = Position.select_one_where(
                'WHERE account_id=? and ticker=?',
                (position.account_id, position.ticker))

            if stored_position:
                position.position_id = stored_position.position_id
                position.num_shares = stored_position.num_shares
                position.num_shares += trade.volume
            else:
                position.num_shares = trade.volume
            trade.save()
            position.save()