Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @app.route("/buy", methods=["GET", "POST"])
- @login_required
- def buy():
- """Buy shares of stock."""
- if request.method == "POST":
- # ensure a symbol was submitted
- if not request.form.get("symbol"):
- return apology("symbol required")
- # check if symbol is valid
- stock = lookup(request.form.get("symbol"))
- if not stock:
- return apology("symbol does not exist")
- # ensure that number of shares entered is not negative
- user_input_shares = int(request.form.get("shares"))
- if user_input_shares < 0:
- return apology("number of shares cannot be negative!")
- # check how much cash user has
- cash = db.execute("SELECT cash FROM users WHERE id=:uid", uid=session["user_id"])
- if not cash:
- return apology("something went wrong when looking up cash amount")
- # calculate total price of stock
- total = stock["price"] * user_input_shares
- if total > cash[0]["cash"]:
- return apology("You don't have enough money!")
- # update user's information and total amount of cash in database and send user to Portfolio
- total_cash = cash[0]["cash"] - total
- db.execute("UPDATE users SET cash=:cash WHERE id=:uid", cash=total_cash, uid=session["user_id"])
- transactions_info = db.execute("SELECT * FROM transactions WHERE user_id=:uid", uid=session["user_id"])
- total_shares = 0
- if len(transactions_info) != 0:
- for i in range(len(transactions_info)):
- if transactions_info[i]["stock_symbol"] == request.form.get("symbol") and transactions_info[i]["no_of_shares"] > 0:
- total_shares = db.execute("UPDATE transactions SET no_of_shares=:shares WHERE user_id=:uid AND stock_symbol=:ssymbol AND time=:t",
- shares=transactions_info["no_of_shares"] + user_input_shares, uid=session["user_id"], stock_symbol=request.form.get("symbol"),
- t=time.time())
- elif transactions_info[i]["stock_symbol"] != request.form.get("symbol"):
- db.execute("INSERT INTO transactions (stock_name, stock_price, stock_symbol, time, no_of_shares, user_id) VALUES(:sname, :sprice, :ssymbol, :t, :shares, :uid)",
- sname=stock["name"], sprice=stock["price"], ssymbol=stock["symbol"], t=time.time(), shares=user_input_shares, uid=session["user_id"])
- cash = db.execute("SELECT cash FROM users WHERE id=:uid", uid=session["user_id"])
- grand_total = 0
- total = 0
- for i in range(len(transactions_info)):
- grand_total = (transactions_info[i]["no_of_shares"] * transactions_info[i]["stock_price"]) + cash
- if transactions_info[i]["stock_symbol"] == stock["symbol"]:
- total = transactions_info["stock_price"] * transactions_info[i]["no_of_shares"]
- return render_template("index.html", transactions_info=transactions_info, total_shares=total_shares,
- grand_total=grand_total, cash=cash, total=total)
- elif request.method == "GET":
- return render_template("buy.html")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement