Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @login_required
- def sell():
- """Sell shares of stock."""
- if request.method == "POST":
- # ensure that entered stock symbol is valid
- stock = lookup(request.form.get("symbol"))
- if not stock:
- return apology("invalid symbol!")
- # check if user has shares of that stock
- stock_query = db.execute("SELECT * FROM user_stocks WHERE user_id=:uid AND stock_symbol=:ssymbol", uid=session["user_id"], ssymbol=stock["symbol"])
- for i in range(len(stock_query)):
- if stock_query[i]["stock_symbol"] != request.form.get("symbol"):
- return apology("You don't have any shares of that stock!")
- # ensure that user has enough shares of the stock
- total_shares = 0;
- for i in range(len(stock_query)):
- total_shares += stock_query[i]["no_of_shares"]
- # check if subtracting that number of shares will leave the user with no shares of that stock left
- # or if it leaves him/her with the amount he/she wants
- shares_to_sell = int(request.form.get("shares"))
- for i in range(len(stock_query)):
- if shares_to_sell > 0:
- if total_shares < shares_to_sell:
- return apology("You don't have enough shares of that stock for this!")
- elif total_shares >= shares_to_sell or stock_query[i]["no_of_shares"] >= shares_to_sell:
- db.execute("INSERT INTO user_stocks (stock_name, stock_price, stock_symbol, no_of_shares, user_id) VALUES(:sname, :sprice, :ssymbol, :shares, :uid)",
- sname=stock_query[i]["stock_name"], sprice=stock_query[i]["stock_price"], ssymbol=request.form.get("symbol"), shares=(-1 * shares_to_sell), uid=session["user_id"])
- else:
- return apology("The shares you have to sell has to be a positive number greater than 0!")
- user_cash = db.execute("SELECT cash FROM users WHERE id=:uid", uid=session["user_id"])
- db.execute("UPDATE users SET cash=:cash WHERE id=:uid", cash=user_cash[0]["cash"] + (stock["price"] * int(request.form.get("shares"))), uid=session["user_id"])
- return redirect(url_for("index"))
- elif request.method == "GET":
- return render_template("sell.html")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement