Ejemplo n.º 1
0
def game_loop():
    view.Welcome()
    buy_inputs = ['b', 'buy']
    sell_inputs = ['s', 'sell']
    lookup_inputs = ['l', 'lookup']
    quote_inputs = ['q', 'quote']
    value_inputs = ['a', 'add']
    leader_inputs = ['lb', 'leaderboard']
    balance_inputs = ['c', 'current balance']
    view_inputs = ['v', 'view']
    acceptable_inputs = buy_inputs + sell_inputs + lookup_inputs \
    + quote_inputs + value_inputs + leader_inputs + balance_inputs \
    + view_inputs
    user_input = input(
        'What would you like to do:\n[b]uy,\n[s]ell,\n[l]ookup,\n[q]uote,\n[a]dd funds,\n[l]eader[b]oard,\n[c]urrent balance,\n[v]iew portfolio\n: '
    )

    if user_input in acceptable_inputs:
        if user_input in buy_inputs:
            model.buy(str(input('Ticker Symbol: ')),
                      int(input('Number of Shares to buy: ')))
            input('Press any key to exit: ')
        elif user_input in sell_inputs:
            print(
                model.sell(input('Ticker Symbol: '),
                           input('Number of Shares to sell: ')))
            input('Press any key to exit: ')
        elif user_input in lookup_inputs:
            print(
                model.get_lookup(
                    input('Which company would you like to lookup?: ')))
            input('Press any key to exit: ')
        elif user_input in quote_inputs:
            print(
                model.get_quote(
                    input('Enter ticker symbol of company for quote: ')))
            input('Press any key to exit: ')
        elif user_input in value_inputs:
            print(
                model.add_value(
                    input(
                        'How much would you like to your account balance?: ')))
            input('Press any key to exit: ')
        elif user_input in leader_inputs:
            model.leaderboard()
            input('Press any key to exit: ')
        elif user_input in balance_inputs:
            model.current_balance()
            input('Press any key to exit: ')
        elif user_input in view_inputs:
            model.view_portfolio()
            input('Press any key to exit: ')
        game_loop()
    else:
        print('incorrect entry')
        input('Press any key to exit: ')
        game_loop()
Ejemplo n.º 2
0
def game_loop(username):
    # Main menu (balance, buy, sell, lookup, quote, portfolio, exit)
    main_done = False
    while not main_done:
        balance_inputs = ["a", "balance"]
        buy_inputs = ["b", "buy"]
        sell_inputs = ["s", "sell"]
        lookup_inputs = ["l", "lookup"]
        quote_inputs = ["q", "quote"]
        portfolio_inputs = ["p", "portfolio"]
        exit_inputs = ["e", "exit"]

        acceptable_inputs = balance_inputs\
           +buy_inputs\
           +sell_inputs\
           +lookup_inputs\
           +quote_inputs\
           +portfolio_inputs\
           +exit_inputs

        user_input = view.main_menu(username)
        # If the user input is acceptable.
        if user_input.lower() in acceptable_inputs:
            # Balance
            if user_input.lower() in balance_inputs:
                balance = model.get_balance(username)
                view.balance_menu(balance)
            # Buy
            elif user_input.lower() in buy_inputs:
                ticker_symbol, trade_volume = view.buy_menu()
                res = model.buy(ticker_symbol, trade_volume, username)
                view.display_response(res)
            # Sell
            elif user_input.lower() in sell_inputs:
                ticker_symbol, trade_volume = view.sell_menu()
                res = model.sell(ticker_symbol, trade_volume, username)
                view.display_response(res)
            # Lookup
            elif user_input.lower() in lookup_inputs:
                company_name = view.lookup_menu()
                ticker_symbol = model.get_ticker_symbol(company_name)
                view.display_ticker_symbol(ticker_symbol)
            # Quote
            elif user_input.lower() in quote_inputs:
                ticker_symbol = view.quote_menu()
                last_price = model.get_last_price(ticker_symbol)
                view.display_last_price(last_price)
            # Portfolio (Holdings)
            elif user_input.lower() in portfolio_inputs:
                df = model.get_holdings_dataframe(username)
                balance = model.get_balance(username)
                earnings = model.get_earnings(username)
                view.display_dataframe(df, balance, earnings, username)
            # Exit
            elif user_input.lower() in exit_inputs:
                view.exit_message()
                main_done = True
            # Otherwise
            else:
                return "Error"
Ejemplo n.º 3
0
def _buy(apikey):
    pk, username = api_authenticate(apikey)
    if not pk:
        return errormsg("could not authenticate")
    if not request.json:
        return errormsg("no buy order")
    if "symbol" not in request.json or "amount" not in request.json:
        return errormsg("bad order")
    try:
        amount = int(request.json["amount"])
    except:
        return errormsg("bad amount")
    symbol = request.json["symbol"]

    response = m.buy(username, symbol, amount)
    if not response:
        return jsonify({
            "error": True,
            "symbol": symbol,
            "amount": amount,
            "message": "Buy order failed"
        })
    else:
        return jsonify({
            "error": False,
            "symbol": symbol,
            "amount": amount,
            "message": "Buy order succeeded"
        })
Ejemplo n.º 4
0
def game_loop():
    buy_input = ['b', 'buy']
    sell_input = ['s', 'sell']
    quit_input = ['q','quit']

    valid_input = buy_input + sell_input + quit_input

    switched_on = True
    while switched_on:
        user_input = view.menu().lower()
        if user_input in valid_input:
            if user_input in buy_input:
                #print('Progress to business logic for buy')
                x = model.buy()
                return x
            elif user_input in sell_input:
                print('Progress to business logic for sell')
            elif user_input in quit_input:
                print('Thanks for playing.  Goodbye!')
                break
                #switched_on = False
            print('Progress to next step')
        else:
            print('Invalid input')
            game_loop()
Ejemplo n.º 5
0
def game_loop():
    while True:
        #x = input('what do you want to do?')
        buy_inputs = ['b', 'buy']
        sell_inputs = ['s', 'sell']
        lookup_inputs = ['l', 'lookup']
        quote_inputs = ['q', 'quote']
        exit_inputs = ['e', 'exit']
        acceptable_inputs = buy_inputs \
              + sell_inputs \
              + lookup_inputs \
              + quote_inputs \
              + exit_inputs
        user_input = view.main_menu()
        if user_input.lower() in acceptable_inputs:
            if user_input.lower() in buy_inputs:
                (ticker_symbol, trade_volume) = view.buy_menu()
                order_status = model.buy(ticker_symbol, trade_volume)
                return order_status
            elif user_input.lower() in sell_inputs:
                pass
            elif user_input.lower() in lookup_inputs:
                company_name = view.lookup_menu()
                ticker_symbol = model.get_ticker_symbol(company_name)
                return ticker_symbol
            elif user_input.lower() in quote_inputs:
                ticker_symbol = view.quote_menu()
                last_price = model.get_last_price(ticker_symbol)
                return last_price
            elif user_input.lower() in exit_inputs:
                #TODO add exit message in the view module
                break
            else:
                return 'Error'
Ejemplo n.º 6
0
def trade():
    if request.method == 'GET':
        return render_template('trade.html')
    else:
        submitted_ticker_symbol = request.form['ticker_symbol']
        submitted_trade_volume = request.form['trade_volume']
        submitted_order_type = request.form['order_type']
        if submitted_order_type == 'Buy':
            #calculate , display confirmation message with preview of trade, and execute if yes selected
            (confirmation, return_list) = model.buy(session['username'],
                                                    submitted_ticker_symbol,
                                                    submitted_trade_volume)
            if confirmation:
                model.buy_db(return_list)
            else:
                pass
                #User doesn't have enough balance
        else:
            #result = model.sell()
            (confirmation, return_list) = model.sell(session['username'],
                                                     submitted_ticker_symbol,
                                                     submitted_trade_volume)
            if confirmation:
                model.sell_db(return_list)
            else:
                pass
        return render_template('trade.html')
Ejemplo n.º 7
0
def buy():
    if request.method == 'GET':
        return render_template('buy.html')
    else:
        ticker_symbol = request.form['thingone']
        trade_volume = request.form['thingtwo']
        x = model.buy(ticker_symbol, trade_volume, session['guid'])
        return render_template('buy.html', message=x)
Ejemplo n.º 8
0
def game_loop():
    user_input = view.main_menu()
    buy_inputs = ['b', 'buy']
    sell_inputs = ['s', 'sell']
    lookup_inputs = ['l', 'lookup']
    quote_inputs = ['q', 'quote']
    exit_inputs = ['e', 'exit']
    view_inputs = ['v', 'view']
    pl_inputs = ['p', 'p']
    acceptable_inputs = buy_inputs      \
        + sell_inputs   \
        + lookup_inputs \
        + quote_inputs  \
        + exit_inputs   \
        + view_inputs   \
        + pl_inputs
    on_off_switch = True
    while on_off_switch:
        if user_input.lower() in acceptable_inputs:
            if user_input.lower() in buy_inputs:
                (ticker_symbol, trade_volume) = view.buy_menu()
                x = model.buy(ticker_symbol, trade_volume)
                return x

            elif user_input.lower() in sell_inputs:
                (ticker_symbol, trade_volume) = view.sell_menu()
                x = model.sell(ticker_symbol, trade_volume)
                return x

            elif user_input.lower() in lookup_inputs:
                company_name = view.lookup_menu()
                x = model.lookup(company_name)
                return x

            elif user_input.lower() in quote_inputs:
                ticker_symbol = view.quote_menu()
                x = model.quote(ticker_symbol)
                return x

            elif user_input.lower() in view_inputs:
                balance = view.portfolio_menu()
                x = model.portfolio(balance)
                return x

            elif user_input.lower() in pl_inputs:
                p = view.pl_menu()
                x = model.pl(p)
                return x

            elif user_input.lower() in exit_inputs:
                break
                #on_off_switch = False
            else:
                print('Bad input. Restarting game in five seconds...')
                time.sleep(5)
                game_loop()
        else:
            return 'Plese Start Over'
Ejemplo n.º 9
0
def select_page(current_user):
    choice = view.select()
    if choice == 'B':
        #Buy
        currency = view.get_currency()
        if not model.check_currency(currency):
            _ = input('\n\nHit any key to return')
            print("Going to selection page")
            return
        amount = view.get_amount('Buy')
        #print(amount)
        date = '2018-07-30'
        model.buy(current_user, currency, amount, date)
        return

    elif choice == 'S':
        #Sell
        currency = view.get_currency()
        if not model.check_currency(currency):
            _ = input('\n\nHit any key to return')
            print("Going to selection page")
            return
        amount = view.get_amount('Sell')
        date = '2018-07-30'
        model.sell(current_user, currency, amount, date)
        return
        '''
    elif choice == 'L':
        #lookup ticker
        model.get_all_ticker_information()
        _ = input("\n\nHit any key to return")
        return
    elif choice == 'Q':
        #Quote symbol
        return
        '''

    elif choice == 'V':
        #View balance
        #print("You currently have %s in your balance" % model.get_balance(current_user))
        date = '2018-08-03'
        model.check_portfolio(current_user, date)
        _ = input('\n\nHit any key to return')
        return
    '''
Ejemplo n.º 10
0
def buy():
    balance = model.check_balance()
    if request.method == 'GET':
        return render_template('buy_menu.html', balance=balance)
    else:
        ticker_symbol = (request.form['ticker_symbol']).upper()
        trade_volume = request.form['trade_volume']
        x = model.buy(ticker_symbol, trade_volume)
        return render_template('homepage.html', x=x, balance=balance)
Ejemplo n.º 11
0
def hompepage():
    if request.method == 'GET':
        message = 'Welcome to web trader, time to make some $$'
        return render_template('homepage.html', message=message)
    elif request.method == 'POST':
        look_up = request.form["look_up"]
        ticker = request.form["ticker"]
        trade_volume = request.form["quantity"]
        if look_up:
            message = model.lookup(look_up)
            return render_template('homepage.html', message=message)
        elif trade_volume:
            model.buy(session['username'], ticker, trade_volume)
            message = "Congratulations you have purchased stuff"
            return render_template('homepage.html', message=message)
        else:
            message = "Come again?"
            return render_template('homepage.html', message=message)
Ejemplo n.º 12
0
def get_buy(apikey):
    if not request.json or not 'Ticker' and 'Shares' in request.json:
        abort(400)
    if not isinstance(request.json['Ticker'], (str)):
        abort(400)
    if not isinstance(request.json['Shares'], (int)):
        abort(400)
    user_name = model.api_authenticate(apikey)
    if not user_name:
        return (jsonify({"error": "count not authenticate"}))
    ticker = request.json['Ticker']
    shares = request.json['Shares']
    return jsonify(model.buy(ticker, shares, user_name))
Ejemplo n.º 13
0
def buy(username):
    ticker_symbol = view.buy_menu_ticker_symbol()
    # Gets the current price so can show it to user before buying it.
    last_price = model.get_last_price(ticker_symbol)
    view.display_last_price(last_price, False)

    trade_volume = view.buy_menu_volume_confirmation()
    order_status = model.buy(ticker_symbol, int(trade_volume), username)
    if order_status == 'SUCCESS':
        view.display_success()
    elif order_status == 'NO_FUNDS':
        balance = model.get_current_balance(username)
        view.display_insufficient_funds(balance)
Ejemplo n.º 14
0
def buy():
    if request.method == 'GET':
        message = 'Make your purchases {}'.format(session['username'])
        return render_template('buy.html', message=message)
    elif request.method == 'POST':
        ticker = request.form["ticker"]
        trade_volume = request.form["quantity"]
        try:
            message = model.buy(session['username'], ticker, trade_volume)
            return render_template('buy.html', message=message)
        except:
            message = "Something went wrong with the buy function"
            return render_template('buy.html', message=message)
Ejemplo n.º 15
0
def controlla(username):
	while True:
		buy_inputs    = ['buy','b']
		sell_inputs   = ['sell','s']
		lookup_inputs = ['lookup','l']
		quote_inputs  = ['quote','q']
		performance   = ['performance','p']
		holdings      = ['holdings','h']
		exit_inputs   = ['exit','e']
		allowed_inputs = buy_inputs + sell_inputs\
						 + lookup_inputs + quote_inputs\
						 + performance + holdings + exit_inputs
		user_input = view.main_menu_UI().lower()
		if user_input in allowed_inputs:
			if user_input in buy_inputs:
				ticker_symbol,trade_volume = view.buy_UI()
				order_status = model.buy(ticker_symbol,trade_volume,username)
				print(order_status)
				input("\nPress Enter to continue...")
			elif user_input in sell_inputs:
				ticker_symbol,trade_volume = view.sell_UI()
				order_status = model.sell(ticker_symbol,trade_volume,username)
				print(order_status)
				input("\nPress Enter to continue...")
			elif user_input in lookup_inputs:
				company_name = view.lookup_UI()
				ticker_symbol = wrapper.get_ticker_symbol(company_name)
				print(ticker_symbol)
				input("\nPress Enter to continue...")
			elif user_input in quote_inputs:
				ticker_symbol = view.quote_UI()
				last_price = wrapper.get_last_price(ticker_symbol)
				print(last_price)
				input("\nPress Enter to continue...")
			elif user_input in performance:
				view.performance_UI()
				perf = model.portfolio_performance(username)
				print(perf)
				input("\nPress Enter to continue...")
			elif user_input in holdings:
				df  = model.holdings_performance(username)
				df2 = model.portfolio_performance(username)
				print(df2,'\n')
				print(df)
				input("\nPress Enter to continue...")
			elif user_input in exit_inputs:
				print('\nYou are about to exit!')
				input("\nPress Enter to continue...")
				return 'exit'
		else:
			print('\nNot A Command, Try Again!')
Ejemplo n.º 16
0
def trade():
    current_user = m.current_user()
    if request.method == "GET":
        if current_user == "randomuser":
            return redirect("/")
        else:
            return render_template("trade.html")
    elif request.method == "POST":
        try:
            submitted_symbol = request.form["ticker_symbol"].upper()
            submitted_volume = request.form["number_of_shares"]
            submitted_volume = int(submitted_volume)
            confirmation_message, transaction = m.buy(
                username, submitted_symbol, submitted_volume
            )
            if submitted_volume == 1:
                result = "You bought {} share of {}.".format(
                    submitted_volume, submitted_symbol
                )
            else:
                result = "You bought {} shares of {}.".format(
                    submitted_volume, submitted_symbol
                )
            m.update_holdings()
            if confirmation_message:
                m.buy_db(transaction)
                return render_template("trade.html", result=result)
            else:
                return render_template("trade.html")
        except Exception:
            submitted_symbols = request.form["ticker_symb"].upper()
            submitted_volumes = request.form["number_shares"]
            submitted_volumes = int(submitted_volumes)
            confirmation_message, transaction = m.sell(
                username, submitted_symbols, submitted_volumes
            )
            if submitted_volumes == 1:
                results = "You sold {} share of {}.".format(
                    submitted_volumes, submitted_symbols
                )
            else:
                results = "You sold {} shares of {}.".format(
                    submitted_volumes, submitted_symbols
                )
            m.update_holdings()
            if confirmation_message:
                m.sell_db(transaction)
                return render_template("trade.html", results=results)
            else:
                return render_template("trade.html", cannot_sell=True)
Ejemplo n.º 17
0
def buy():
    username = m.current_user()
    if request.method == "GET":
        return render_template('buy.html')
    else:
        submitted_symbol = request.form['ticker_symbol']
        submitted_volume = request.form['number_of_shares']
        submitted_volume = int(submitted_volume)
        confirmation_message, return_list = m.buy(username, submitted_symbol,
                                                  submitted_volume)
        result = f"You paid {m.quote_last(submitted_symbol)} for {submitted_volume} shares of {submitted_symbol}."
        if confirmation_message == True:
            return render_template('buy.html', result=result)
        else:
            return render_template('buy.html')
Ejemplo n.º 18
0
def buy():
    if request.method == 'GET':
        return render_template('dashboard.html')
    else:

        Ticker = request.form['Ticker']
        Shares = int(request.form['Shares'])
        user_name = '%s' % escape(session['username'])
        #buy=model.buy(Ticker,Shares, user_name)
        info = model.dashboard(user_name)
        if request.form.get('inlineCheckbox1'):
            buy = model.buy(Ticker, Shares, user_name)
            info = model.dashboard(user_name)
            if buy:
                mes = buy['User'] + ' bought ' + str(
                    buy['Shares']
                ) + ' share(s) of ' + buy['Ticker'] + ' for ' + str(
                    buy['Cost'])
                return render_template('dashboard.html',
                                       buy_info=mes,
                                       info=info)
            else:
                mes = "You don't have enough money"
                return render_template('dashboard.html',
                                       buy_info=mes,
                                       info=info)
        elif request.form.get('inlineCheckbox2'):
            sell = model.sell(Ticker, Shares, user_name)
            info = model.dashboard(user_name)
            if sell:
                message = sell['username'] + ' sold ' + str(
                    sell['Shares']
                ) + ' shares of ' + sell['Ticker'] + ' for ' + str(
                    sell['Cost'])
                return render_template('dashboard.html',
                                       sell_info=message,
                                       info=info)
            else:
                message = "You don't have enough shares"
                return render_template('dashboard.html',
                                       sell_info=message,
                                       info=info)
        else:
            mes = "Click Buy or Sell box"
            return render_template('dashboard.html', buy_info=mes, info=info)
Ejemplo n.º 19
0
def buy(balance, earnings, idno, xbal, xearn):
    if request.method == 'GET':
        return render_template('buy.html',
                               balance=balance,
                               earnings=earnings,
                               idno=idno,
                               xbal=xbal,
                               xearn=xearn)
    else:
        # x= model.buy(ticker_symbol, trade_volume, bal, earn, idno)
        # return x
        tickersym = request.form['tickersymz']
        tradevolume = request.form['tradevol']
        bal, earn = model.create(idno)
        x = model.buy(tickersym, tradevolume, bal, earn, idno)
        zeez = x.split()
        if "Sorry," in zeez:
            message2 = "An error occured..." + x
            return render_template('buy.html',
                                   balance=balance,
                                   earnings=earnings,
                                   idno=idno,
                                   xbal=xbal,
                                   xearn=xearn,
                                   message2=message2)
        else:
            mess = "Successfully bought ticker and volume." + x
            idz1 = captureid(idno)
            bal, earn = model.create(idz1)

            return redirect(
                url_for("landing",
                        message1=mess,
                        balance=bal.balancez,
                        earnings=earn.earningz,
                        idno=idno,
                        xbal=bal,
                        xearn=earn))
Ejemplo n.º 20
0
def game_loop():
    start = view.start_up_menu()
    if start == "s":
        (user_name, password) = view.sign_up_menu()
        model.sign_up(user_name, password)
    else:
        (user_name, password) = view.logg_in_menu()
        _id = model.user_check(password)
        print(_id)

    while 1:
        buy_inputs = ['b', 'buy']
        sell_inputs = ['s', 'sell']
        lookup_inputs = ['l', 'lookup', 'look up', 'look-up']
        quote_inputs = ['q', 'quote']
        exit_inputs = ['e', 'exit', 'quit']
        view_inputs = ['v']
        acceptable_inputs = buy_inputs     \
                            +sell_inputs   \
                            +lookup_inputs \
                            +quote_inputs  \
                            +exit_inputs   \
                            +view_inputs
        user_input = view.main_menu()
        if user_input in acceptable_inputs:
            if user_input in buy_inputs:
                balance = model.check_balance(user_name)
                fee = 6.25
                ticker_symbol = view.quote_menu()
                price = model.quote(ticker_symbol)
                trade_volume = view.transaction_menu(balance, ticker_symbol,
                                                     price)
                transaction_cost = (float(trade_volume) * price) + fee
                if transaction_cost <= balance:
                    balance -= transaction_cost
                    model.update_cash(user_name, balance)
                    model.buy(user_name, ticker_symbol, float(trade_volume),
                              float(price))
                    model.buy_holdings(user_name, ticker_symbol,
                                       float(trade_volume), price)
                else:
                    print("Not enough monay")

            elif user_input in sell_inputs:
                ticker_symbol = view.quote_menu()
                price = model.quote(ticker_symbol)
                trade_volume = view.sell_menu()
                owned = model.check_holdings(user_name, ticker_symbol)
                if owned and int(trade_volume) <= owned:
                    model.sell_holdings(user_name, ticker_symbol, trade_volume,
                                        price, owned)

            elif user_input in lookup_inputs:
                return model.lookup(view.lookup_menu())
            elif user_input in quote_inputs:
                return model.quote(view.quote_menu())
            elif user_input in view_inputs:
                users = model.get_users()
                users_list = [
                ]  # this is a list of all the users that currenttly have holdings
                for i in users:
                    users_list.append(i[0])

                users_holdings = [
                ]  # users holdings by tickers but not numbers
                for i in users_list:
                    user_holdings = model.get_holdings(i)
                    a = []
                    for i in user_holdings:
                        a.append(i[0])
                    users_holdings.append(a)

                tickers = [
                ]  # is all the stocks the users, un "set'd" and joinined together
                for i in users_holdings:
                    for j in i:
                        tickers.append(j)
                prices = {
                }  # this has all the prices for all the stocks owned in the holdings
                for i in set(tickers):  #
                    price = model.quote(i)
                    prices[i] = price

                volumes = [
                ]  # a list of lists of amount of stock each of them own
                for i in users_list:
                    volumes.append(model.holdings_volumes(i))
                # print(users_holdings)
                # print(volumes)
                values_final = {}
                for i in range(len(users_holdings)):
                    total = 0
                    for j in range(len(users_holdings[i])):
                        total += (prices[users_holdings[i][j]]) * (
                            volumes[i][j][0])
                    values_final[users_list[i]] = total
                highest = 0
                sorted_words = {}
                while values_final:
                    for i in values_final:
                        if values_final[i] >= highest:
                            highest = values_final[i]
                            word = i
                    sorted_words[word] = highest
                    values_final.pop(i)
                    highest = 0
                for i in sorted_words:
                    print("{} : {}".format(i, sorted_words[i]))
                    # highest = 0
                # while values_final:
                #     for i in range(len(values))
                #     if values[i]

                # need to add total balance
                #work vwamp

            elif user_input in exit_inputs:
                break
Ejemplo n.º 21
0
def select_page():
    current_user = session['username']
    print(session)
    error = None
    #choice = view.select()
    if request.method == 'POST':
        choice = request.form['choice']
        #level = request.args['level']
        #print(level, choice)
        if choice == 'SL':
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:# request.args['level'] == 1:
                print('333')
                print('new leverage %s' % request.form['leverage'])
                session['leverage'] = request.form['leverage']
                session['level'] = 0
                print('new leverage %s' % session['leverage'])
                return render_template('trader_select.html', choice=choice, leverage=session['leverage'], level=session['level'])

        elif choice == 'B':
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                currency = request.form['currency']
                if not model.check_currency(currency):
                    error = 'No such currency found'
                    return render_template('trader_select.html', error=error, choice=choice, leverage=session['leverage'], level=session['level'])      
                amount = request.form['amount']
                date = request.form['date']
                session['level'] = 0
                print(currency,amount, date)
                msg = model.buy(session['username'], currency, amount, date, session['leverage'])
                return render_template('trader_select.html', choice=choice, leverage=session['leverage'], level=session['level'], msg=msg) 

        elif choice == 'S':
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                currency = request.form['currency']
                if not model.check_currency(currency):
                    error = 'No such currency found'
                    return render_template('trader_select.html', error=error, choice=choice, leverage=session['leverage'], level=session['level'])      

                amount = request.form['amount']
                date =  request.form['date']
                session['level'] = 0
                msg = model.sell(session['username'], currency, amount, date, session['leverage'])
                return render_template('trader_select.html', choice=choice, leverage=session['leverage'], level=session['level'], msg=msg) 
            
        elif choice == 'D':
            #Delete all transactions
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                if request.form['delete'] == '1':
                    msg = model.delete_all_transactions(session['username'])
                    session['level'] = 0
                    return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'], msg=msg) 
                else:
                    return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])
        
        elif choice == 'L':
            #lookup currency price
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                date = request.form['date']
                msg, _ = model.get_all_currency_information(date)
                session['level'] = 0
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'], msg=msg) 
             
        elif choice == 'LR':
            #lookup currency real-time price
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                currency = request.form['currency']
                msg = model.get_real_time_currency_information(currency)
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'], msg=msg) 

            
        elif choice == 'V':
            #View balance
            #print("You currently have %s in your balance" % model.get_balance(current_user))
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                date = request.form['date']
           # try:
                msg, _ = model.check_portfolio(session['username'], date)
        #    except:
         #       print('No price found')
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'], msg=msg) 

        elif choice == 'P':
            #See P/L
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                #date = request.form['date']
                def build_index(date):
                    indexes = {}
                    for row in model.get_all_currency_information(date)[1]:
                        if row[1] == 'JPY' or row[1] == 'CNY' or row[1] == 'GBP' or row[1] == 'CAD' or row[1] == 'EUR':
                            indexes[row[1]] = row[2]
                    return indexes

                start_date = request.form['start_date']
                end_date = request.form['end_date']
                start_date = list(map(int,start_date.split('-')))
                end_date = list(map(int,end_date.split('-')))
                start_date = date_module(start_date[0], start_date[1], start_date[2])
                end_date = date_module(end_date[0], end_date[1], end_date[2])
                date = []
                balance = []
                market = []
                base_index = build_index(start_date)

                for single_date in API.daterange(start_date, end_date):
                    DATE = single_date.strftime("%Y-%m-%d")
                    balance.append(model.check_portfolio(session['username'], DATE)[1])
                    date.append(single_date)
                    performance = 0
                    for key, value in build_index(DATE).items():
                        performance = base_index[key]*1.0/value + performance
                    market.append(performance*20000)
                    
                p = figure(plot_width=800, plot_height=250)   
                p.xaxis[0].formatter = DatetimeTickFormatter()
                p.line(date, balance, color='navy', alpha=0.5,legend='Your Algorithm')
                p.line(date, market, color='red', alpha=0.5, legend='Market Performance')

                p.legend.location = "top_left"
                p.legend.click_policy="hide"
                script, div = components(p)

                return render_template("plot.html", the_div=div, the_script=script)

        elif choice == 'A1':
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
            elif session['level'] == 1:
                def build_index(date):
                    indexes = {}
                    for row in model.get_all_currency_information(date)[1]:
                        if row[1] == 'JPY' or row[1] == 'CNY' or row[1] == 'GBP' or row[1] == 'CAD' or row[1] == 'EUR':
                            indexes[row[1]] = row[2]
                    return indexes

                start_date = request.form['start_date']
                end_date = request.form['end_date']
                start_date = list(map(int,start_date.split('-')))
                end_date = list(map(int,end_date.split('-')))
                start_date = date_module(start_date[0], start_date[1], start_date[2])
                end_date = date_module(end_date[0], end_date[1], end_date[2])
                date = []
                balance = []
                market = []
                base_index = build_index(start_date)
                
                model.algo_1(start_date, end_date, session['username'])
               
                for single_date in API.daterange(start_date, end_date):
                    DATE = single_date.strftime("%Y-%m-%d")
                    balance.append(model.check_portfolio(session['username'], DATE)[1])
                    date.append(single_date)
                    performance = 0
                    for key, value in build_index(DATE).items():
                        performance = base_index[key]*1.0/value + performance
                    market.append(performance*20000)
                    
                p = figure(plot_width=800, plot_height=250)   
                p.xaxis[0].formatter = DatetimeTickFormatter()
                p.line(date, balance, color='navy', alpha=0.5,legend='Your Algorithm')
                p.line(date, market, color='red', alpha=0.5, legend='Market Performance')

                p.legend.location = "top_left"
                p.legend.click_policy="hide"
                script, div = components(p)

                return render_template("plot.html", the_div=div, the_script=script)
        elif choice == 'A2':
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
 
        elif choice == 'A3':
            if session['level'] == 0:
                session['level'] = 1
                return render_template('trader_select.html', choice=choice,leverage=session['leverage'],level=session['level'])      
 
        elif choice == 'E':
            # quit
            session.clear()
            return redirect(url_for('welcome'))
        else:
            _ = input('Entered wrong choice!!! Hit any key to retry')
            return
    session['level'] = 0
    return render_template('trader_select.html', error=error)
Ejemplo n.º 22
0
def game_loop():
    current_username = ''
    condition = True
    while 1:
        user_choice = view.log_or_sign()
        user_choice = user_choice.lower()
        log_in = ['l','login']
        create_ = ['c','create']
        exit_ = ['e','exit']
        accept_input = log_in    \
                    +create_     \
                    +exit_
        if user_choice in accept_input:
            if user_choice in log_in:
                (user_name, password) = view.log_menu()
                current_username = user_name
                has_account = model.log_in(user_name, password)
                if has_account:
                    break
                else:
                    input("You have entered the wrong login information. \nPlease try again. Press enter to continue. ")
            elif user_choice in exit_:
                condition = False
                m.log_out()
                view.clear_screen()
                break
            elif user_choice in create_:
                model.create_()
                print("You have signed up!")
                input("Press enter to continue. ")
    while condition: #while true, the loop continues
        buy_inputs = ['b', 'buy']
        sell_inputs = ['s', 'sell']
        lookup_inputs = ['l', 'lookup']
        quote_inputs = ['q', 'quote']
        funds = ['f', 'funds']
        holdings = ['h', 'holdings']
        transactions = ['t', 'transactions']
        exit_inputs = ['e', 'exit']
        acceptable_inputs = buy_inputs     \
                            +sell_inputs   \
                            +lookup_inputs \
                            +quote_inputs  \
                            +funds         \
                            +holdings      \
                            +transactions  \
                            +exit_inputs
        user_input = view.main_menu()
        user_input = user_input.lower()
        if user_input in acceptable_inputs:
            if user_input in buy_inputs:
                (ticker_symbol, trade_volume) = view.buy_menu()
                confirmation_message, return_list = model.buy(current_username, ticker_symbol, trade_volume)
                if confirmation_message == True: #if the transaction cost is less than the current balance
                    yes = ['y', 'yes']
                    no = ['n', 'no']
                    choice = input("You have enough money. Would you like to buy this stock?\n[y] Yes\n[n] No\n")
                    if choice in yes:
                        model.buy_db(return_list)
                        print("You have bought {} shares of {}. ".format(trade_volume, ticker_symbol))
                    else:
                        print("Returning to main menu.")
                else:
                    print("You do not have enough money to buy this stock.")
            elif user_input in sell_inputs:
                (ticker_symbol, trade_volume) = view.sell_menu()
                confirmation_message, return_list = model.sell(current_username, ticker_symbol, trade_volume)
                if confirmation_message == True:
                    yes = ['y', 'yes']
                    no = ['n', 'no']
                    choice = input("You have enough shares to sell. Would you like to sell this stock?\n[y] Yes\n[n] No\n")
                    if choice.lower() in yes:
                        model.sell_db(return_list)
                        print("You have sold {} shares of {}. ".format(trade_volume, ticker_symbol))
                    else:
                        print("Returning to main menu.")
                else:
                    print("You do not have enough shares to sell.")
            elif user_input in lookup_inputs:
                company_name = view.lookup_menu()
                ticker_symbol = model.lookup_ticker_symbol(company_name)
                if len(ticker_symbol) <=6: #if it returns an actual ticker symbol instead of the error message
                    print("The ticker symbol for {} is {}.".format(company_name, ticker_symbol))
                else: #error message
                    print("The ticker symbol for the company you searched cannot be found. \nPlease try again.")
            elif user_input in quote_inputs:
                ticker_symbol = view.quote_menu()
                last_price = model.quote_last_price(ticker_symbol)
                if len(str(last_price)) <= 6:
                    print("The last price for {} is ${}.".format(ticker_symbol, last_price))
                else:
                    print("The last price for the company you searched cannot be found. \nPlease try again.")
            elif user_input in funds:
                view.clear_screen()
                bal = model.funds()
                print("Your current balance is ${}.".format(bal))
            elif user_input in holdings:
                view.clear_screen()
                holdings = m.holdings()
                print("Your current holdings: \n{}".format(holdings))
            elif user_input in transactions:
                view.clear_screen()
                transactions = m.transactions()
                print("All of your previous transactions: \n{}".format(transactions))
            elif user_input in exit_inputs:
                view.clear_screen()
                condition = False
                m.log_out()
                break
            else:
                print("Error.")
        else:
            print("Error.")
        model.update_holdings()
        input("\nPress enter to continue. ")
Ejemplo n.º 23
0
     if status == False:
         view.sell_error()
         view.pause()
     else:
         view.sell_good()
         view.pause()
 elif option.strip() == '5':
     ticker_symbol = view.quote_prompt()
     quote = model.quote(ticker_symbol)
     view.display_quote(ticker_symbol, quote)
     view.pause()
 elif option.strip() == "2":
     account_pk = pk
     ticker_symbol = view.getsymbol()
     number_of_shares = view.volume()
     finalbuy = model.buy(account_pk, ticker_symbol, number_of_shares)
     if finalbuy == False:
         view.failuremessage()
     else:
         view.successmessage()
 elif option.strip() == "4":
     account_pk = pk
     ticker_symbol = view.ticker_request()
     orders = model.get_orders(account_pk, ticker_symbol)
     view.display_order_hist(account_pk, ticker_symbol, orders)
 elif option.strip() == '6':
     username, password, balance = view.create_account()
     model.save_create_account(username, password, balance)
 elif option.strip() == '7':
     switch = view.switch_accounts()
     if switch == True:
Ejemplo n.º 24
0
def game_loop():
    current_username = ''
    condition = True
    while 1:
        user_choice = view.log_or_sign()
        user_choice = user_choice.lower()
        log_in = ['l', 'login']
        create_ = ['c', 'create']
        exit_ = ['e', 'exit']
        accept_input = log_in     \
                      +create_     \
                      +exit_
        if user_choice in accept_input:
            if user_choice in log_in:
                (user_name, password) = view.log_menu()
                current_username = user_name
                has_account = model.log_in(user_name, password)
                if has_account:
                    break
                else:
                    print('WRONG LOGIN INFORMATION. TRY AGAIN')
                    import time
                    time.sleep(3)
            elif user_choice in exit_:
                condition = False
                m.log_out()
                os.system('clear')
                break

            elif user_choice in create_:
                #(new_user,new_password,new_funds) = view.create_menu()
                #       new_user = input("username:"******"password:"******"""INSERT INTO user(
                        username,
                        password,
                        current_balance
                    ) VALUES(?,?,?
                    )""", newuser)
                connection.commit()
                cursor.close()
                connection.close()

                print("You have signed up!")
                import time
                time.sleep(3)

    while condition:
        buy_inputs = ['b', 'buy']
        sell_inputs = ['s', 'sell']
        lookup_inputs = ['l', 'lookup']
        quote_inputs = ['q', 'quote']
        exit_inputs = ['e', 'exit']
        acceptable_inputs = buy_inputs     \
                            +sell_inputs   \
                            +lookup_inputs \
                            +quote_inputs  \
                            +exit_inputs
        user_input = view.main_menu()
        if user_input in acceptable_inputs:
            if user_input in buy_inputs:
                (ticker_symbol, trade_volume) = view.buy_menu()
                confirmation_message, return_list = model.buy(
                    current_username, ticker_symbol, trade_volume)
                if confirmation_message == True:
                    yes = ['y', 'yes']
                    no = ['n', 'no']
                    choice = input(
                        "You have enough money. Would you like to buy this stock?\n[y] Yes\n[n] No\n"
                    )
                    if choice in yes:
                        model.buy_db(return_list)
                    else:
                        print("Returning to main menu.")
                else:
                    print("You do not have enough money to buy this stock.")
            elif user_input in sell_inputs:
                (ticker_symbol, trade_volume) = view.sell_menu()
                confirmation_message, return_list = model.sell(
                    current_username, ticker_symbol, trade_volume)  #TODO
                if confirmation_message == True:
                    yes = ['y', 'yes']
                    no = ['n', 'no']
                    choice = input(
                        "You have enough shares to sell. Would you like to sell this stock?\n[y] Yes\n[n] No\n"
                    )
                    if choice.lower() in yes:
                        model.sell_db(return_list)  #TODO
                    else:
                        print("Returning to main menu.")
                else:
                    print("You do not have enough shares to sell.")

            elif user_input in lookup_inputs:
                company_name = view.lookup_menu()
                print(model.lookup_ticker_symbol(company_name))
            elif user_input in quote_inputs:
                #TODO
                ticker_symbol = view.quote_menu()
                print(model.quote_last_price(ticker_symbol))
                #import time
                #time.sleep(5)
            elif user_input in exit_inputs:
                os.system('clear')
                break
            else:
                #catches huge error
                #should contain a fallback function
                pass
        else:
            pass
        model.updateHoldings()
        import time
        time.sleep(3)
Ejemplo n.º 25
0
def user_trade(user_name):
    i = 1
    while True:
        choice = input(
            '\n' +
            'Enter 1 - To enter a stock name. 2 - To enter a stock symbol. ')
        if choice == '1':
            name = input('\n' +
                         'Enter full or partial name of stock for lookup. ')
            symbol = markit.symbol_lookup(name)
            if len(symbol) == 0:
                print(
                    '\n' +
                    'No match found for that name. You have a total of five attempts'
                )
                i += 1
            elif len(symbol) > 1:
                print(
                    '\n' +
                    'Too many matches found. You have a total of five attempts'
                )
                print(symbol)
                i += 1
            elif len(symbol) == 1:
                print('\n' + 'Lookup successful!', '\n', symbol)
                symbol = symbol[0]['Symbol']
                stock_data = markit.get_quote(symbol)
                print('\n' + 'Stock data:', '\n', stock_data)
                break
            else:
                print('Unknown error. You have a total of five attempts')
                print(symbol)
        elif choice == '2':
            symbol = input('\n' + 'Enter stock symbol. ')
            symbol = symbol.upper()
            stock_data = markit.get_quote(symbol)
            if 'Message' in stock_data:
                print(stock_data['Message'], '\n',
                      'You have a total of 5 attempts.')
                i += 1
            elif stock_data['Status'] == 'SUCCESS':
                print(stock_data)
                break
            else:
                print(stock_data)
        else:
            print('Incorrect choice. You have a total of 5 attempts.')
            i += 1
        if i > 5:
            return
    i = 1
    while True:
        choice = input('\n' + 'Enter 1 - To Buy. 2 - To Sell. ')
        try:
            qty = int(input('Enter Quantity '))
        except Exception as e:
            print("qty error ", e)
            i += 1
        if choice == '1':
            action = model.buy(user_name, stock_data['Name'], symbol, qty,
                               stock_data['LastPrice'])
            if action:
                print('Insuffienct balance of ' + str(action) +
                      ' to complete transaction.')
            else:
                print('Transaction completed ')
                break
        elif choice == '2':
            action = model.sell(user_name, symbol, qty,
                                stock_data['LastPrice'])
            if action:
                if action == -1:
                    print('You do not own this stock')
                else:
                    print('Insuffienct quantity of ' + str(action) +
                          ' to complete transaction.')
            else:
                print('Transaction completed ')
                break
        else:
            print('Incorrect choice. You have a total of five attempts')
            i += 1
        if i > 5:
            return