コード例 #1
0
def newtrade():
    form = TradeForm()
    acclist = AccountInfo.query.filter_by(user_id=current_user.username)
    accounts = []
    for item in acclist:
        accounts.append((item.account_longname, item.account_longname))
    form.trade_account.choices = accounts

    if request.method == "POST":

        if form.validate_on_submit():
            # Need to include two sides of trade:
            if form.trade_operation.data in ("B"):
                qop = 1
            elif form.trade_operation.data in ("S"):
                qop = -1
            else:
                qop = 0
                flash(
                    "Trade Operation Error. Should be B for buy or S for sell.",
                    "warning")

            # Calculate Trade's cash value
            cvfail = False

            try:
                p = float(clean_float(form.trade_price.data))
                q = float(clean_float(form.trade_quantity.data))
                f = float(clean_float(form.trade_fees.data))
                cv = qop * (q * p) + f

            except ValueError:
                flash(
                    "Error on calculating fiat amount \
                for transaction - TRADE NOT included",
                    "danger",
                )
                cvfail = True
                cv = 0

            # Check what type of trade this is
            # Cash and/or Asset

            try:
                tquantity = float(form.trade_quantity.data) * qop
            except ValueError:
                tquantity = 0

            try:
                tprice = float(form.trade_price.data)
            except ValueError:
                tprice = 0

            trade = Trades(
                user_id=current_user.username,
                trade_date=form.trade_date.data,
                trade_account=form.trade_account.data,
                trade_currency=form.trade_currency.data,
                trade_asset_ticker=form.trade_asset_ticker.data,
                trade_quantity=tquantity,
                trade_operation=form.trade_operation.data,
                trade_price=tprice,
                trade_fees=form.trade_fees.data,
                trade_notes=form.trade_notes.data,
                cash_value=cv,
            )
            if not cvfail:
                current_app.db.session.add(trade)
                current_app.db.session.commit()
                regenerate_nav()
                flash("Trade included", "success")

            return redirect(url_for("warden.warden_page"))
        else:
            flash("Trade Input failed. Something went wrong. Try Again.",
                  "danger")

    form.trade_currency.data = current_app.fx['code']
    form.trade_date.data = datetime.utcnow()
    return render_template("warden/newtrade.html",
                           form=form,
                           title="New Trade",
                           current_app=current_app,
                           current_user=fx_rate())
コード例 #2
0
def edittransaction():
    form = TradeForm()
    reference_id = request.args.get("reference_id")
    id = request.args.get("id")
    if reference_id:
        trade = Trades.query.filter_by(
            user_id=current_user.username).filter_by(
                trade_reference_id=reference_id).first()
        if trade.count() == 0:
            abort(404, "Transaction not found")
        id = trade.id

    trade = Trades.query.filter_by(user_id=current_user.username).filter_by(
        id=id).first()

    if trade is None:
        abort(404)

    if trade.user_id != current_user.username:
        abort(403)

    acclist = AccountInfo.query.filter_by(user_id=current_user.username)
    accounts = []
    for item in acclist:
        accounts.append((item.account_longname, item.account_longname))
    form.trade_account.choices = accounts
    form.submit.label.text = 'Edit Trade'

    if request.method == "POST":

        if form.validate_on_submit():
            # Write changes to database
            if form.trade_operation.data in ("B", "D"):
                qop = 1
            elif form.trade_operation.data in ("S", "W"):
                qop = -1
            else:
                qop = 0

            # Calculate Trade's cash value
            cvfail = False

            try:
                p = float(clean_float(form.trade_price.data))
                q = float(clean_float(form.trade_quantity.data))
                f = float(clean_float(form.trade_fees.data))
                cv = qop * (q * p) + f

            except ValueError:
                flash(
                    "Error on calculating cash amount \
                for transaction - TRADE NOT edited. Try Again.",
                    "danger",
                )
                cvfail = True
                cv = 0

            trade.trade_date = form.trade_date.data
            trade.trade_asset_ticker = form.trade_asset_ticker.data
            trade.trade_currency = form.trade_currency.data
            trade.trade_operation = form.trade_operation.data
            trade.trade_quantity = float(form.trade_quantity.data) * qop
            trade.trade_price = float(clean_float(form.trade_price.data))
            trade.trade_fees = float(clean_float(form.trade_fees.data))
            trade.trade_account = form.trade_account.data
            trade.trade_notes = form.trade_notes.data
            trade.cash_value = cv

            if not cvfail:
                current_app.db.session.commit()
                regenerate_nav()
                flash("Trade edit successful", "success")

            return redirect(url_for("warden.warden_page"))

        flash("Trade edit failed. Something went wrong. Try Again.", "danger")

    # Pre-populate the form
    form.trade_date.data = trade.trade_date
    form.trade_currency.data = trade.trade_currency
    form.trade_asset_ticker.data = trade.trade_asset_ticker
    form.trade_operation.data = trade.trade_operation
    form.trade_quantity.data = abs(float(trade.trade_quantity))
    form.trade_price.data = trade.trade_price
    form.trade_fees.data = trade.trade_fees
    form.trade_account.data = trade.trade_account
    form.trade_notes.data = trade.trade_notes

    return render_template("warden/edittransaction.html",
                           title="Edit Transaction",
                           form=form,
                           trade=trade,
                           id=id,
                           current_app=current_app,
                           current_user=fx_rate())
コード例 #3
0
ファイル: app.py プロジェクト: tommygeiger/stonks
def trade():

    if 'loggedin' not in session:
        flash('Log In or Sign Up to start trading!')
        return redirect(url_for('login'))

    form = TradeForm()
    if form.validate_on_submit():

        #Get stock
        symbol = form.symbol.data.upper()
        quantity = form.quantity.data
        try:
            stock = yf.Ticker(symbol)
            ask = stock.info['ask']
            trade_amount = ask * quantity

            if form.buy.data:
                #Get cash
                cursor.execute("SELECT * FROM Users WHERE id=%s",
                               session['id'])
                for row in cursor:
                    cash = row[4]

                if trade_amount <= cash:
                    #Subtract ask from cash, insert stock
                    cursor.execute("UPDATE Users SET cash=cash-%s WHERE id=%s",
                                   (trade_amount, session['id']))

                    #Increment quantity if owned, otherwise add
                    cursor.execute(
                        "SELECT * FROM Stocks WHERE id=%s AND symbol=%s",
                        (session['id'], symbol))
                    if cursor.fetchone():
                        cursor.execute(
                            "UPDATE Stocks SET quantity=quantity+%s, date=%s WHERE id=%s",
                            (quantity, datetime.now().date(), session['id']))
                    else:
                        cursor.execute(
                            "INSERT INTO Stocks VALUES (%s, %s, %s, %s)",
                            (session['id'], symbol, quantity,
                             datetime.now().date()))

                    db.commit()
                    flash('Transaction completed!')
                else:
                    flash('Insufficient funds.')
                    return render_template('trade.html', form=form)

            elif form.sell.data:

                #Check quantity
                cursor.execute(
                    "SELECT quantity FROM Stocks WHERE id=%s AND symbol=%s",
                    (session['id'], symbol))
                owned = cursor.fetchone()[0]
                if owned:
                    if quantity > owned:
                        flash('You can\'t sell more stock than you own!')
                        return render_template('trade.html', form=form)
                    elif quantity == owned:
                        cursor.execute(
                            "DELETE FROM Stocks WHERE id=%s AND symbol=%s",
                            (session['id'], symbol))
                    else:
                        cursor.execute(
                            "UPDATE Stocks SET quantity=quantity-%s, date=%s WHERE id=%s AND symbol=%s",
                            (quantity, datetime.now().date(), session['id'],
                             symbol))

                    #Increment cash
                    cursor.execute("UPDATE Users SET cash=cash+%s WHERE id=%s",
                                   (trade_amount, session['id']))
                    db.commit()
                    flash('Transaction completed!')

                else:
                    flash('You can\'t sell a stock you don\'t own!')
                    return render_template('trade.html', form=form)

        except:
            flash('An error occurred.')
        return redirect(url_for('trade'))

    return render_template('trade.html', form=form)