Ejemplo n.º 1
0
def createPost():
    form = SellForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            post = Posts(form.posttitle.data, form.price.data,
                         form.email.data, form.description.data)
            db.session.add(post)
            db.session.commit()
            #flash('Post saved on database.')
            return redirect(url_for('list_posts'))
    return render_template('post.html', form=form)
Ejemplo n.º 2
0
def editPost(post_uid):
    post = Posts.query.get_or_404(post_uid)
    form = SellForm(obj=post)
    if request.method == 'POST':
        print request.form
        if form.validate_on_submit():
            print request.form['posttitle']
            post.posttitle = request.form['posttitle']
            post.price = request.form['price']
            post.email = request.form['email']
            post.description = request.form['description']
            db.session.add(post)
            db.session.commit()
            #flash('post editted')
        return redirect(url_for('list_posts'))
    else:
        return render_template('post.html', form=form)
Ejemplo n.º 3
0
def sell_crypto(crypto_name):

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

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

    update_crypto_price(crypto_name)

    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]
    try:
        sold_coin = users_cryptos_names.index(crypto.name)
        crypto_amount = user.crypto[sold_coin].amount
    except ValueError:
        crypto_amount = 0

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

    USDT = user_money.amount

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

    sellform = SellForm()

    if sellform.validate_on_submit():

        update_crypto_price(crypto_name)

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

        users_cryptos = [crypto for crypto in user.crypto]

        users_cryptos_names = [crypto.name for crypto in users_cryptos]

        for user_crypto in users_cryptos:
            if crypto.name == user_crypto.name:
                usdt = users_cryptos_names.index("USDCUSDT")
                sold_coin = users_cryptos_names.index(crypto.name)

                if float(sellform.amount.data
                         ) <= user.crypto[sold_coin].amount and float(
                             sellform.amount.data) > 0.00000000:
                    user.crypto[sold_coin].amount -= float(
                        sellform.amount.data)
                    user.crypto[usdt].amount += user_crypto.price * float(
                        sellform.amount.data)

                    db.session.add(user)
                    db.session.commit()

                    return redirect(f'/user/{g.user.id}')
                else:
                    flash("You can't sell that much", "danger")
                    return redirect(f"/cryptos/{crypto.name}/sell")

    return render_template('crypto_sell.html',
                           crypto=crypto,
                           sellform=sellform,
                           USDT=USDT,
                           crypto_amount=crypto_amount)
Ejemplo n.º 4
0
def sell():
    """
    @author: EM
    Functionality for the user sell function.
    """
    # Enable selling of shares
    # Remove stock from user's portfolio // or // add a new row with a negative value for the number of shares
    # You can use DELETE or log the sale as a negative quantity
    # Update cash/value of user [the stock is sold at its current price]
    # return success or failure message

    # Initialise the relevant forms and relevant variables
    sellForm = SellForm()
    searchForm = SearchForm()
    error = None

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

    # Validate that the sell form was submitted via post and that the contents of the form were valid
    if sellForm.validate_on_submit():
        # Get form information
        symbol = sellForm.symbol.data.upper()
        is_symbol = quote_validate(symbol)
        if is_symbol is None:
            flash("Please enter a valid quote to sell some shares.", "warning")
            return redirect(url_for("sell"))
        noOfShares = int(sellForm.shares.data)

        # contact API
        company_info = get_company_info(symbol)
        current_price = get_current_share_quote(symbol)['latestPrice']

        # 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
        current_user = User.query.filter_by(
            username=session['username']).first()
        userid = current_user.id
        user = User.query.get(userid)

        # Calculate the total cost of shares the user wants to sell based on the current price
        total_cost = (float(noOfShares) * current_price)
        # Query the database to confirm the user owns a particular share they wish to sell
        share = Portfolio.query.filter_by(symbol=symbol).first()
        if share is None:
            flash("You attempted to sell a share you do not currently own.",
                  "warning")
            return redirect(url_for("sell"))

        # Query the database to confirm the user is selling the proper amount of shares
        # In other words, the user must not sell 3 shares if they only own 1 share for a particular stock
        if share.quantity < noOfShares:
            flash("You attempted to sell more shares than you currently own.",
                  "warning")
            return redirect(url_for("sell"))

        # update portfolio table if the user is able to sell the shares
        # if number of shares is 2 or more then update row otherwise just delete the row
        portf = Portfolio.query.filter_by(userid=userid, symbol=symbol).first()
        if portf is not None:
            if portf.quantity > 1:
                # update the number of shares in the users portfolio
                portf.quantity = portf.quantity - noOfShares
                # update the users cash value
                user.cash = user.cash + total_cost
                # Commit the above changes to the database
                db.session.commit()
            else:
                # update the number of shares in the users portfolio
                db.session.delete(portf)
                # update the users cash value
                user.cash = user.cash + total_cost
                # Commit the above changes to the database
                db.session.commit()
            flash(f"You have sold some shares worth {usd(current_price)}.",
                  "success")
        else:
            # no such stock exist
            flash("You attempted to sell a share you do not currently own.",
                  "warning")
            return redirect(url_for("sell"))

        # update history table
        History().add_hist(userid, symbol.upper(), -noOfShares, "sell")

        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']

        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)

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

    return render_template("sell.html",
                           sellForm=sellForm,
                           searchForm=searchForm,
                           error=error,
                           quotes=quotes)