def get_position_for(self,symbol): where="WHERE account_pk=? and ticker=?" values=(self.pk,symbol) result=Position.select_one(where,values) if result: return result position=Position() position.account_pk=self.pk position.ticker=symbol position.shares=0 return position
def get_position_for(self, ticker): where = "WHERE account_pk = ? AND ticker = ?" values = (self.pk, ticker) result = Position.select_one(where, values) if result: return result position = Position() position.account_pk = self.pk position.ticker = ticker position.shares = 0 return position
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))
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()