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"
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')
def _sell(apikey): pk, username = api_authenticate(apikey) if not pk: return errormsg("could not authenticate") if not request.json: return errormsg("no sell 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.sell(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": "Sell order succeeded" })
def sell(): if request.method == 'GET': return render_template('sell.html') else: ticker_symbol = request.form['sellone'] trade_volume = request.form['selltwo'] x = model.sell(ticker_symbol, trade_volume, session['guid']) return render_template('sell.html', message=x)
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'
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 '''
def sell(username): (ticker_symbol, trade_volume) = view.sell_menu() order_status = model.sell(ticker_symbol, int(trade_volume), username) if order_status == 'SUCCESS': view.display_success() elif order_status == 'NO_FUNDS': holding_volume = model.get_holding_volume_by_symbol( username, ticker_symbol) view.display_insufficient_holdings(ticker_symbol, holding_volume)
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()
def sell(): if request.method == 'GET': message = 'What do you wanna sell {}?'.format(session['username']) return render_template('sell.html', message=message) elif request.method == 'POST': ticker = request.form["ticker"] trade_volume = request.form["quantity"] message = model.sell(session['username'], ticker, trade_volume) return render_template('sell.html', message=message)
def sell(): balance = model.check_balance() if request.method == 'GET': return render_template('sell_menu.html', balance=balance) else: ticker_symbol = (request.form['ticker_symbol']).upper() trade_volume = request.form['trade_volume'] x = model.sell(ticker_symbol, trade_volume) return render_template('homepage.html', x=x, balance=balance)
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!')
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)
def sell(): username = m.current_user() if request.method == "GET": return render_template('sell.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.sell(username, submitted_symbol, submitted_volume) result = f"You sold {submitted_volume} shares of {submitted_symbol} at {m.quote_last(submitted_symbol)}" if confirmation_message == True: return render_template('sell.html', result=result) else: return render_template('sell.html')
def get_sell(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.sell(ticker, shares, user_name))
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)
def sell(): 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']) 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)
def sell(balance, earnings, idno, xbal, xearn): if request.method == 'GET': return render_template('sell.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.sell(tickersym, tradevolume, bal, earn, idno) zeez = x.split() if "Sorry," in zeez: message2 = "An error occured..." + x return render_template('sell.html', balance=balance, earnings=earnings, idno=idno, xbal=xbal, xearn=xearn, message2=message2) else: mess = "Successfully sold 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))
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. ")
while pk == None: username, password = view.login_prompt(True) pk = model.login(username, password) exit_terminal = False while exit_terminal == False: option = view.main_menu() if option.strip() == "0": exit_terminal = True elif option.strip() == "1": balance = model.get_balance(pk) holdings = model.get_holdings(pk) view.show_status(balance, holdings) view.pause() elif option.strip() == '3': ticker_symbol, number_of_shares = view.sell_menu() status = model.sell(pk, ticker_symbol, number_of_shares) 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()
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)
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)
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