- updated the code to display history properly,ie when sold shows negative,and when bought shows positive
- updated index to remove entire row when stocks is 0
I cant figure out why check 50 is not checking my value.
Can someone help me with this issue, i been stuck for 2 days staring at it for 15 hours. I checked adding "AAAA" stock of value 28 and bought 4 and sold 2 and yielded $56.Please look into it.
Buy.html
{% extends "layout.html" %}
{% block title %}buy{% endblock %}
{% block main%}
<form action="/buy" method="POST">
<div class="form-group"><input type="text" name ="symbol" placeholder=" Symbol"autofocus="form-control"></div>
<div class="form-group"><input type="text" step="any" name ="shares" placeholder=" Shares" >
</div>
<button class="btn btn-primary" type=submit>Buy</button>
</form>
{% endblock %}
Sell.html
{% extends "layout.html" %}
{% block title %}sell{% endblock %}
{% block main %}
<form action="/sell" method="POST">
<SELECT class ="form-group" name="symbol">
<option class="form-group" disabled selected value="">Symbol</option>
{% for i in symbouls %}
<option value="{{i}}">{{i}}</option>
{% endfor %}
</SELECT>
<div class="form-group"><input type= number step="any" name="shares" placeholder=" Shares"></div>
<button class= "btn btn-primary" type="submit">Sell</button>
</form>
{% endblock %}
Index.html
{% extends "layout.html" %}
{% block title %}index{% endblock %}
{% block main %}
<style>
table,th{
border:2px white;
border-collapse:collapse;
margin:25px ;
min-width:170px;
font-size:1.1em;
background-color:#009879;
text-align:left;
color:#ffffff;
}
td{
border:1.5px white;
background-color:#ffffff;
color:#009879;
padding:10px 8px;
text-align:left;
}
</style>
<table class="form-group">
<tr>
<th>{{heading[0]}}</th>
<th>{{heading[1]}}</th>
<th>{{heading[2]}}</th>
<th>{{heading[3]}}</th>
<th>{{heading[4]}}</th>
</tr>
{% for i in row %}
<tr>
<td>{{i.symbol}} </td>
<td>{{i.name}} </td>
<td>{{i.shares}} </td>
<td> {{i.price | usd}}</td>
<td>{{i.total | usd}}</td>
</tr>
{% endfor %}
<tr>
<td>cash</td>
<td></td>
<td></td>
<td></td>
<td>{{maxi[0]["cash"] | usd}}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{{maxi[0]["crapola"] | usd}}</td>
</tr>
</table>
{% endblock %}
My code:
import os
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import apology, login_required, lookup, usd
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
SYMBOLS=set()
HEADING=[" Stock"," Name"," Shares"," Price"," Total"]
HEADING1=[" Symbol","Share","Price","Transacted"]
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Custom filter
app.jinja_env.filters["usd"] = usd
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")
# Make sure API key is set
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not set")
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
ids =session["user_id"]
db.execute("DELETE FROM current WHERE shares = ? AND id = ?",0,ids)
row=db.execute("SELECT * FROM current WHERE id=?",ids)
print(row)
if len(row)!=None:
for i in row:
value=lookup(i["symbol"])
price=value["price"]
shares=i["shares"]
print(shares)
totale= price * shares
i["total"]=totale
maxi=db.execute("SELECT * FROM users WHERE id=?",ids)
cash=maxi[0]["cash"]
print(maxi)
return render_template("index.html",heading=HEADING,row=row,maxi=maxi)
else:
maxi=db.execute("SELECT * FROM users WHERE id=?",ids)
cash=maxi[0]["cash"]
print(maxi)
return render_template("index.html",heading=HEADING,row=row,maxi=maxi)
# @app.route("/password")
# def password():
# if request.method="POST":
# else:
# return render_template("password.html")
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method=="POST":
if not request.form.get("symbol"):
return apology("missing symbol",400)
if not request.form.get("shares"):
return apology("missing shares",400)
try:
check=(request.form.get("shares"))
print(check)
if float(check).is_integer()== False or int(check) < 0 :
return apology("Enter proper values",400)
except ValueError:
return apology("Enter proper values")
value=lookup(request.form.get("symbol"))
if value==None:
return apology("Not found",400)
price=value["price"]
print(price)
name=value["name"]
symbol=value["symbol"]
print(symbol)
shares = int(request.form.get("shares"))
print(shares)
ids =session["user_id"]
print(ids)
val = db.execute("SELECT * FROM users WHERE id=?",ids)
print(val)
cash= int(val[0]["cash"])
user=val[0]["username"]
print(cash)
print(user)
if cash < price * shares:
return apology("INSUFFICIENT FUNDS",403)
else:
tutal= price * shares
cash = cash - (price * shares)
print(cash)
row=db.execute("SELECT * FROM history WHERE id=? AND symbol=? ORDER BY histid DESC",ids,symbol)
print(row)
if len(row)==0:
share=0
else:
share=int(row[0]["share"])
print(share)
share=share + shares
print(share)
db.execute("UPDATE users SET cash=? WHERE id=?",cash,ids)
db.execute("INSERT INTO history(symbol,share,price,id,calculations,time) VALUES(?,?,?,?,?,CURRENT_TIMESTAMP)",symbol,share,price,ids,shares)
current=db.execute("SELECT * FROM current WHERE id=? AND symbol=?",ids,symbol)
print(current)
if len(current)==0:
db.execute("INSERT INTO current(symbol,name,shares,price,id,total) VALUES(?,?,?,?,?,?)",symbol,name,share,price,ids,tutal)
else:
update=db.execute("SELECT total FROM current WHERE id=? AND symbol=?",ids,symbol)
update=update[0]["total"]
total= update + tutal
db.execute("UPDATE current SET shares=?, total=? WHERE id=? AND symbol=?",share,total,ids,symbol)
return redirect("/")
else:
return render_template("buy.html")
@app.route("/history")
@login_required
def history():
"""Show history of transactions"""
ids= session["user_id"]
row1=db.execute("SELECT * FROM history WHERE id=?",ids)
return render_template("history.html",row1=row1,heading1=HEADING1)
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 403)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 403)
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
return apology("invalid username and/or password", 403)
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
if request.method=="POST":
value=lookup(request.form.get("symbol"))
print(value)
if value==None:
return apology("not found",400)
print(value)
return render_template("quoted.html",name=value["name"],price=value["price"],symbol=value["symbol"])
else:
return render_template("quote.html")
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method=="POST":
if not request.form.get("username"):
return apology("MUST PROVIDE USERNAME", 400)
elif not request.form.get("password"):
return apology("MISSING PASSWORD", 400)
elif not request.form.get("confirmation"):
return apology("MISSING CONFIRM PASSWORD", 400)
elif request.form.get("password") != request.form.get("confirmation"):
return apology("PASSWORDS DON'T MATCH",400)
rows=db.execute("SELECT * FROM users WHERE username=?",request.form.get("username"))
if len(rows) == 1:
return apology("USERNAME ALREADY USED",400)
hashword = generate_password_hash(request.form.get("password"), method='pbkdf2:sha256', salt_length=8)
db.execute("INSERT INTO users (username,hash) VALUES(?,?)",request.form.get("username"),hashword)
return redirect("/login")
if request.method=="GET":
return render_template("register.html")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock"""
if request.method=="POST":
if not request.form.get("symbol") or request.form.get("symbol") not in SYMBOLS:
return apology("missing symbol",400)
if not request.form.get("shares"):
return apology("missing shares",400)
check=request.form.get("shares")
if int(check) < 0 :
return apology("Enter proper values",400)
value=lookup(request.form.get("symbol"))
if value==None:
return apology("Not found",400)
name=value["name"]
symbol=request.form.get("symbol")
price=value["price"]
ids=session["user_id"]
shares=int(request.form.get("shares"))
val=db.execute("SELECT * FROM users WHERE id=?",ids)
print(val)
cash=int(val[0]["cash"])
user=val[0]["username"]
print(cash)
val1=db.execute("SELECT * FROM history WHERE id=? AND symbol=? ORDER BY histid DESC",ids,symbol)
print(val1)
share=int(val1[0]["share"])
print(share)
print(shares)
if share < shares:
return apology("share limit",400)
else:
ji= db.execute("SELECT total FROM current WHERE id=? AND symbol=?",ids,symbol)
update=ji[0]["total"]
tetul=update - (shares * price)
share=share - shares
hi=db.execute("SELECT * FROM users WHERE id=?",ids)
cash=hi[0]["cash"]
cash= cash + (shares * price)
db.execute("UPDATE users SET cash=? WHERE id=?",cash,ids)
db.execute("INSERT INTO history(symbol,share,price,id,calculations,time) VALUES(?,?,?,?,?,CURRENT_TIMESTAMP)",symbol,share,price,ids,-shares)
db.execute("UPDATE current SET shares=?,total=? WHERE id=? AND symbol =?",share,tetul,ids,symbol)
return redirect("/")
else:
ids=session["user_id"]
symboul=db.execute("SELECT symbol FROM history WHERE id=?",ids)
for i in symboul:
for j in i:
SYMBOLS.add(i[j])
print(SYMBOLS)
return render_template("sell.html",symbouls=SYMBOLS)
def errorhandler(e):
"""Handle error"""
if not isinstance(e, HTTPException):
e = InternalServerError()
return apology(e.name, e.code)
# Listen for errors
for code in default_exceptions:
app.errorhandler(code)(errorhandler)