@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
user_id = session["user_id"]
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
rows = db.execute("SELECT stock, SUM(shares) FROM history WHERE id = :id GROUP BY stock", id=user_id)
selected_sym = request.form.get("symbol")
try:
shares = int(request.form.get("shares"))
if shares <= 0:
return apology("Please enter valid shares", 400)
for i in range(len(rows)):
for j in range(len(rows[i])):
if rows[i]["stock"] == selected_sym:
if shares > rows[i]["SUM(shares)"]:
return apology("Please enter valid shares", 400)
except ValueError:
return apology("Please enter valid shares", 400)
quote = lookup(selected_sym)
if quote != None:
time = datetime.now()
current_time = time.strftime('%Y-%m-%d %H:%M:%S')
rows = db.execute("SELECT cash FROM users WHERE id = :id", id=user_id)
updated_cash = round(rows[0]["cash"] + (shares * quote["price"]), 2)
shares = -shares
update_users = db.execute("UPDATE users SET cash = :cash WHERE id = :id", id=user_id, cash=updated_cash)
insert_history = db.execute("INSERT INTO history (id, method, stock, price, shares, time) VALUES(:id, :method, :stock, :price, :shares, :time)",
id=user_id, method="SOLD", stock=quote["symbol"], price=quote["price"], shares=shares, time=current_time)
if not update_users:
return apology("Sorry, stock could not be bought")
if not insert_history:
return apology("Sorry, stock bought could not be saved")
return redirect(url_for("index"))
return apology("Sorry, this stock is not valid!")
# User reached route via GET (as by clicking a link or via redirect)
else:
rows = db.execute("SELECT DISTINCT stock FROM history WHERE id = :id", id=user_id)
return render_template("sell.html", stocks=rows)
return apology("Something went wrong")