예제 #1
0
def buy_crypto(crypto_name):

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/login")

    user = User.query.get_or_404(g.user.id)

    users_usdt = UserCrypto.query.filter_by(name='USDCUSDT')

    usdts = [usdt for usdt in users_usdt]

    user_crypto = [crypto for crypto in user.crypto]

    crypto_names = [crypto.name for crypto in user_crypto]

    users_cryptos_names = [crypto.name for crypto in user_crypto]

    crypto = Crypto.query.filter_by(name=crypto_name).first()

    try:
        bought_coin = users_cryptos_names.index(crypto.name)
        crypto_amount = user.crypto[bought_coin].amount
    except ValueError:
        crypto_amount = 0

    for usdt in usdts:
        if user.id == usdt.user_crypto:
            user_money = usdt

    USDT = user_money.amount

    crypto = Crypto.query.filter_by(name=crypto_name).first()

    if crypto_name == 'USDCUSDT':
        flash("You can't trade that directly", "danger")
        return redirect('/cryptos/USDCUSDT')

    crypto = Crypto.query.filter_by(name=crypto_name).first()

    update_crypto_price(crypto_name)

    form_max = (USDT - 5) / crypto.price

    buyform = BuyForm()

    if buyform.validate_on_submit():

        if buy_crypto_func(crypto_name, buyform):

            return redirect(f'/user/{g.user.id}')
        else:
            return redirect(f'/cryptos/{crypto.name}/buy')

    return render_template('crypto_buy.html',
                           crypto=crypto,
                           buyform=buyform,
                           USDT=USDT,
                           crypto_amount=crypto_amount,
                           form_max=form_max)
예제 #2
0
def portfolio():
	"""
	View user stock portfolio and make buy orders
	"""
	if 'user' not in session:
		return redirect(url_for('login'))
	# Fetch user information from db
	user = User.query.filter_by(id=session['user']).first()
	balance = '%.2f'%(user.money)
	
	form = BuyForm()

	if request.method == 'POST':
		if form.validate_on_submit():
			symbol = form.ticker.data
			quantity = form.quantity.data
			symbol_price = iex.get_symbol_price(symbol)
			# Check if symbol exists
			if not symbol_price:
				flash('Symbol does not exist')
				return redirect(url_for('portfolio'))
			# Check if user has enough funds to purchase
			total_price = quantity * symbol_price
			if total_price <= decimal.Decimal(user.money):
				new_transaction = Transaction(user_id=session['user'], symbol=symbol.upper(), quantity=quantity, price=symbol_price, buy_transaction=True)
				user.money -= decimal.Decimal(total_price)
				db.session.add(new_transaction)
				db.session.commit()
				flash('Successfully bought {} shares of {} at {}'.format(quantity, symbol.upper(), symbol_price))
			else:
				flash('Not enough money')
			return redirect(url_for('portfolio'))

	# Gather portfolio information from transactions
	symbol_count = {}
	transactions = Transaction.query.filter_by(user_id=session['user']).all()
	for transaction in transactions:
		symbol_count[transaction.symbol.upper()] = symbol_count.get(transaction.symbol.upper(), 0) + transaction.quantity
	stocks = []
	for symbol in symbol_count:
		symbol_json = iex.get_symbol(symbol)
		open_price = symbol_json['open']
		cur_price = symbol_json['latestPrice']
		stocks.append({
			'change_sign': 1 if cur_price > open_price else -1 if cur_price < open_price else 0,
			'symbol': symbol,
		 	'count': symbol_count[symbol],
			'value': cur_price * symbol_count[symbol]
			})

	value = '%.2f'%(sum(stock['value'] for stock in stocks))
	return render_template('portfolio.html', balance=balance, value=value, stocks=stocks, form=form, title='Portfolio')
예제 #3
0
def viewbudget():
    form = BuyForm()
    #get budget data
    mybudget = Budget.query.filter_by(user_id=session["user_id"]).first()
    if mybudget:
        img_path = f"images/budget_charts/{mybudget.graph_link}"
    else:
        img_path = None
    if form.validate_on_submit():
        mybudget.spending_left -= form.money.data
        db.session.commit()
    return render_template("viewbudget.html",
                           form=form,
                           img_path=img_path,
                           data=mybudget)
예제 #4
0
def index():
    form = BuyForm(request.form)

    if 'user' in session:
        session_flag = True
    else:
        session_flag = False

    if request.method == 'POST':
        item = form.item.data
        precio = form.precio.data

        if request.form['submit_button'] == 'Salir':
            session.pop('user', None)
            return redirect('/')
        if request.form['submit_button'] == 'Borrar':
            if item != None and precio != None:
                coso = {'item': item, 'precio': precio}
                db_delete_one(inventario, coso)
        else:
            if item != None and precio != None:
                coso = {"item": item, "precio": precio}
                db_insert_user(inventario, coso)

    items = db_find_all(inventario)

    return render_template('admin.html',
                           items=items,
                           session_flag=session_flag)
예제 #5
0
파일: views.py 프로젝트: linxunke/linxunke
def transaction(id):
    user=g.user
    shop=Shop.query.filter_by(id=id).first()
    form= BuyForm()
    if form.validate_on_submit():
         if g.user.money>shop.price:
             g.user.money=g.user.money-shop.price
             db.session.add(g.user)
             db.session.commit()
             return redirect(url_for('Success'))
         else :
             return redirect(url_for('false'))
    return render_template('transaction.html',
                           user=user,
                           form=form,
                           shop=shop)
예제 #6
0
def buy():
    paymentOut = "Payment output"
    form = BuyForm()
    if form.is_submitted():
        result = request.form
        denom_1 = int(result['denom_1'])
        denom_2 = int(result['denom_2'])
        denom_3 = int(result['denom_3'])
        denom_4 = int(result['denom_4'])
        user_cash = denom_1 * 1 + denom_2 * 2 + denom_3 * 5 + denom_4 * 10
        item = result['item_name']
        print("user cash = \t", user_cash, "\titem = \t", item)
        paymentOut = m1.makePayment(user_cash, item, denom_1, denom_2, denom_3,
                                    denom_4)
    return render_template('buy.html',
                           form=form,
                           items=m1.items,
                           paymentOut=paymentOut,
                           wallet=m1.wallet)
예제 #7
0
def buy():
    form = BuyForm()
    if form.validate_on_submit():
        bookid = form.id.data
        bookname = form.name.data
        bookauthor = form.author.data
        bookstorage = form.storage.data
        conn = mysql.connector.connect(user='******',
                                       password='',
                                       database='Bookdata')
        cursor = conn.cursor()
        cursor.execute(
            "insert into Book (id,name,author,storage,borrow) values (%s,%s,%s,%s,0)",
            (
                bookid,
                bookname,
                bookauthor,
                bookstorage,
            ))
        conn.commit()
        cursor.close()
        return redirect('/buyresult/' + bookid)
    return render_template('buy.html', form=form)
예제 #8
0
def buy():
    """
    @author: EM
    Functionality for the user to buy some stocks.
    """
    # Initialise the relevant forms
    buyForm = BuyForm()
    searchForm = SearchForm()

    # calling the utility function for autocomplete
    quotes = search_autocomplete()

    if buyForm.validate_on_submit():
        # Get form information
        symbol = buyForm.symbol.data.upper()
        is_symbol = quote_validate(symbol)
        if is_symbol is None:
            flash("Please enter a valid quote to buy some shares.", "warning")
            return redirect(url_for("buy"))

        noOfShares = int(buyForm.shares.data)
        if noOfShares < 1:
            flash(
                "Please enter a number greater than zero to buy some stocks.",
                "warning")
            return redirect(url_for("buy"))

        # contact API
        company_info = get_company_info(symbol)
        # confirm the symbol exists in the database
        if type(get_current_share_quote(symbol)) is not dict:
            flash(get_current_share_quote(symbol))
            return redirect(url_for("buy"))
        else:
            current_price = get_current_share_quote(symbol)['latestPrice']

        # Now it is certain the user has entered the correct data
        # obtaining graph information
        graphdata = plotter(symbol)

        # Query database
        # Based on the id of the currently logged in user , obtain this id from the session variable
        us = User.query.filter_by(username=session['username']).first()
        userid = us.id
        user = User.query.get(userid)

        total_cost = (float(noOfShares) * current_price)
        # Check if the user can afford the stocks they want to buy
        if total_cost > user.cash:
            # send the user to thier dashboard
            flash("Check that you have enough money to buy stocks.", "warning")
            return redirect(url_for("dashboard"))
        else:
            # update cash for user in the database
            user.cash -= total_cost
            # update portfolio table
            portf = Portfolio(userid=userid,
                              symbol=symbol.upper(),
                              quantity=noOfShares,
                              transaction_type="buy")
            db.session.add(portf)
            # update history table
            hist = History(userid=userid,
                           symbol=symbol.upper(),
                           quantity=noOfShares,
                           transaction_type="buy")
            db.session.add(hist)
            # commit the changes made to the database
            db.session.commit()

            # Notify the user about their recent trade
            send_buy_confirmation(symbol, noOfShares)

        # Putting together a summary of the users current transaction
        data = {}
        data["symbol"] = symbol.upper()
        data["noOfShares"] = noOfShares
        data["current_price"] = usd(current_price)
        data["amount"] = usd(user.cash)

        company_in = get_company_info(symbol)

        data['exchange'] = company_in['exchange']
        data['industry'] = company_in['industry']
        data['description'] = company_in['description']
        data['sector'] = company_in['sector']
        data['companyName'] = company_in['companyName']

        # Prepare some information to show the user thier portfolio
        stocks = Portfolio.query.all()
        ptf = Portfolio.query.filter_by(userid=int(1)).all()
        if ptf is not None:
            for stock in ptf:
                grand_total = user.cash + (
                    stock.quantity *
                    get_current_share_quote(stock.symbol)['latestPrice'])
                data["grand_total"] = usd(grand_total)

        flash(
            f"You have bought shares from {data['companyName']} worth {usd(current_price)}!",
            "success")

        return render_template('index.html',
                               data=data,
                               searchForm=searchForm,
                               stocks=stocks,
                               graphdata=graphdata,
                               quotes=quotes)

    # the code below is executed if the request method
    # was GET or there was some sort of error
    return render_template("buy.html",
                           buyForm=buyForm,
                           searchForm=searchForm,
                           quotes=quotes)
예제 #9
0
def buy():
    form = BuyForm()
    if request.method == "GET":
        return render_template("buy.html", form=form)
    if form.validate_on_submit():
        return 1