def buy(): form = BuyForm() if form.validate_on_submit(): query_symbol = form.symbol.data query_quantity = form.shares.data share = get_quote(query_symbol) buy_price = float(share['price']) transaction_value = buy_price * query_quantity if transaction_value > current_user.cash: flash('Not enough cash to proceed with the purchase') return redirect(url_for('main_bp.quote')) owned_stock = Stock.is_owned(query_symbol, current_user) if owned_stock: owned_stock.shares += query_quantity else: stock = Stock(symbol=query_symbol, shares=query_quantity, buy_price=buy_price, owner=current_user) db.session.add(stock) current_user.cash -= transaction_value db.session.commit() transaction = Transaction(user_id=current_user.id, stock_id=Stock.is_owned( query_symbol, current_user).id, buy_price=buy_price, shares=query_quantity) db.session.add(transaction) db.session.commit() flash( f"You bought {query_quantity} {query_symbol} shares at £ {buy_price:0.2f} each" ) return redirect(url_for('main_bp.index')) flash('Something went wrong, please try again') return redirect(url_for('main_bp.quote'))
def sell(): form = SellForm() choices = [(stock.symbol, stock.symbol) for stock in current_user.stocks] form.symbol.choices = choices if form.validate_on_submit(): query_symbol = form.symbol.data query_quantity = form.shares.data owned_stock = Stock.is_owned(query_symbol, current_user) if not owned_stock: flash('You do not own this stock') return redirect(url_for('main_bp.sell')) if query_quantity > owned_stock.shares: flash('You do not have enough shares to sell') return redirect(url_for('main_bp.sell')) share = get_quote(query_symbol) sell_price = float(share['price']) flash( f"You sold {query_quantity} {query_symbol} shares at {sell_price:0.2f} each" ) current_user.cash += query_quantity * sell_price owned_stock.shares -= query_quantity transaction = Transaction(user_id=current_user.id, stock_id=owned_stock.id, sell_price=sell_price, shares=query_quantity) db.session.add(transaction) db.session.commit() return redirect(url_for('main_bp.index')) return render_template('sell.html', form=form)