def price(ticker): price = util.get_price(ticker) if price == False: return jsonify(NOTFOUND), 404 return jsonify({"ticker": ticker, "price": price})
def sell(self, ticker, amount): #Get account and positions details account = self.get_account() position = self.get_position_for(ticker) amount = int(amount) #Check stock exists and if so retrieve current price quote_price = get_price(ticker) if not quote_price: # raise KeyError msg = "Input Ticker doesn't exist" else: #Check sufficient shares if position.shares == 0 or amount > position.shares: # raise ValueError msg = "Insufficient shares" else: #Insert Trade row new_trade = Trade(accounts_pk=self.pk, ticker=ticker, \ volume=amount*-1, price=quote_price) new_trade.save() #Update Position row new_position = Position(pk=position.pk, accounts_pk=self.pk, ticker=ticker, \ shares=position.shares - amount) new_position.save() #Update balance on Account row new_balance = Account(pk=self.pk, username=account.username, \ password_hash=account.password_hash, \ balance=account.balance + (amount*quote_price), \ api_key=account.api_key) new_balance.save() msg = "Sell transaction completed successfully" return msg
def lookupticker(ticker): quote = util.get_price(ticker) if not quote: msg = "The Ticker Symbol entered does not exist" else: msg = "Current price for Ticker Symbol: {} = ${}".format(ticker, quote) return jsonify({'message': msg})
def trades(api_key, ticker): account = Account.authenticate_api(api_key) ticker = get_price(ticker) if not account: return jsonify({'invalid': ticker}), 404 position = account.get_position_for_json(ticker) return jsonify({'position': position})
def positions_sum(api_key): account = Account.api_authenticate(api_key) if not account: return jsonify(UNAUTHORIZED), 401 positions = account.get_positions() tot_sum = 0 for position in positions: tot_sum += util.get_price(position.ticker) * position.shares return jsonify({"account_sum": tot_sum})
def price(): if request.method == 'GET': return render_template('ticker.html') elif request.method == 'POST': ticker = request.form['ticker'] try: price = util.get_price(ticker) message = view.show_ticker_price(ticker, price) except ConnectionError: return render_template('ticker.html', message="Ticker not found please enter new valid ticker") return render_template('ticker.html', message=message)
def sell(self, ticker, amount): position = self.get_position_for(ticker) price = get_price(ticker)[1] trade = Trade(accounts_pk = self.pk, ticker=ticker, price=price, volume=amount) if position.shares < int(amount): raise ValueError("You do not have enough shares to sell") else: position.shares -= int(amount) # position.shares -= int(amount) print(position.shares) self.balance += int(amount) * price position.save() trade.save() self.save()
def buy_stocks(account): try: view.enter_symbol() symbol = input() view.enter_amount() amount = input() amount = float(amount) account.buy(str(symbol).upper(), amount) sharecost = util.get_price(symbol) * amount view.buy_success_message( str(symbol).upper(), amount, account.balance, sharecost) except ValueError: view.insufficient_funds_message() return main_menu(account)
def lookup(ticker, api_key): user = Account.api_authenticate(api_key) if user: price = get_price(ticker) description = stock_description(ticker) chart_data = chart(ticker) logo = Logo(ticker) related = related_Companies(ticker) return jsonify({ 'current_price': price, "des": description, "chartData": chart_data, "logo": logo }) return jsonify({"error": "failed"})
def sell(api_key, ticker, amount): account = Account.authenticate_api(api_key) if not account: return jsonify({'error': 'authentication error'}), 401 if not request.json: return jsonify({'error': 'bad request'}) price = get_price(ticker) total_cost = int(amount) * int(price) try: if request.json['amount'] and request.json['ticker']: if account.balance > total_cost: account.sell(ticker, int(amount)) except (ValueError, KeyError): return jsonify({"error": "bad request"}), 400 return jsonify({"username": account.username, "balance": account.balance})
def sell(self, ticker, amount): """ make a sale. raise KeyErrror for a non-existent stock and ValueError for insufficient shares. will create a new Trade object, modify a Position, and alter the self.balance. returns nothing.""" position = self.get_position_for(ticker) price = get_price(ticker)[1] trade = Trade(accounts_pk=self.pk, ticker=ticker, price=price, volume=-int(amount)) position.shares -= int(amount) self.balance += int(amount) * price position.save() trade.save() self.save()
def balance(): account = Account.api_authenticate(session['api_key']) if not account: return redirect(url_for('login')) cash = account.balance positions = account.get_positions() if len(positions) == 0: return render_template('balance.html', Title=view.bal_and_pos(cash) + " " + view.no_positions()) else: bal = 0 for position in positions: ticker = position.ticker shares = position.shares px = util.get_price(ticker) bal += px * shares return render_template('balance.html', Title=view.totbal(bal) + "\n" + view.totport(bal + cash), Title2=view.api_key(account.api_key))
def buy(self, ticker, amount): price = get_price(ticker) if self.balance < price * amount: raise ValueError("Insufficient Funds") self.balance -= price * amount trade = Trade() trade.account_pk = self.pk trade.ticker = ticker trade.price = price trade.volume = amount trade.time = time.time() position = self.get_position_for(ticker) position.shares += amount self.save() trade.save() position.save()
def buy(api_key, ticker, amount): account = Account.authenticate_api(api_key) price = util.get_price(ticker)[1] purchase = int(amount) * int(price) if not account: return jsonify({"error": "authentication error"}), 401 if not price: return jsonify({"error": "bad ticker data"}), 400 if not request.json: return jsonify({"error": "bad request"}), 400 try: if request.json['amount'] and request.json['ticker']: if account.balance > purchase: account.buy(ticker, int(amount), int(price), purchase) except (ValueError, KeyError): return jsonify({'error': 'bad request'}), 400 return jsonify({'username': account.username, "balance": account.balance})
def sell(self, ticker, amount): price = get_price(ticker) position = self.get_position_for(ticker) if position.shares < amount: raise ValueError("Insufficient Shares to Sell or Position Does not Exist") self.balance += price * amount trade = Trade() trade.account_pk = self.pk trade.ticker = ticker trade.price = price trade.volume = -1 * amount trade.time = time.time() position.shares -= amount self.save() trade.save() position.save()
def positions(): account = Account.api_authenticate(session['api_key']) if not account: return redirect(url_for('login')) positions = account.get_positions() if len(positions) == 0: return render_template('positions.html', Title=view.no_positions()) else: bal = 0 textlist = [] for position in positions: ticker = position.ticker shares = position.shares px = util.get_price(ticker) bal += px * shares textlist.append(view.stockbal(shares, ticker, px * shares)) totals = view.totbal(bal) return render_template('positions.html', Total=totals, Title=textlist)
def sell(self, ticker, amount): """ if current Postion.number_shares is greater than or equal to amount, updates a Position, saves a new Trade object and updates self.balance""" position = self.get_position_for(ticker) price = get_price(ticker) * amount if position.number_shares < amount: raise ValueError("Insufficient stocks") print(position.ticker, ": ", position.number_shares) position.number_shares -= amount self.balance += price trade = Trade(ticker=ticker, quantity=amount, type=0, price=price, account_pk=self.pk) # changed type from 1 to 0 trade.save() position.save() self.save()
def buy(self,symbol,amount): price=get_price(symbol) if self.balance<price*amount: raise ValueError("You do not have enough money for this stock") self.balance-=price*amount trade=Trade() trade.account_pk=self.pk trade.ticker=symbol trade.price=price trade.volume=amount trade.time=time.time() position=self.get_position_for(symbol) position.shares+=amount self.save() trade.save() position.save()
def buy(self, ticker, amount): """ if balance is greater than equal to amount * current price, updates a Position if it exists, or creates a new Position for this ticker in our datase. saves a new Trade object ans updates self.balance""" price = get_price(ticker) * amount if self.balance < price: raise ValueError("Insufficient Funds") position = self.get_position_for(ticker) print(position.ticker, ": ", position.number_shares) position.number_shares += amount self.balance -= price trade = Trade(ticker=ticker, quantity=amount, type=1, price=price, account_pk=self.pk) trade.save() position.save() self.save()
def mainmenu(account): while True: view.mainmenu() selection = view.get_input() if selection == "8": break elif selection == "1": view.your_balance() print(account.balance) view.your_positions() pos = account.get_positions() for position in pos: print(position.ticker, ":", position.number_shares) elif selection == "2": amount = int(view.get_amount_input()) account.balance += amount view.your_balance() print(account.balance) account.save() elif selection == "3": ticker = view.get_ticker_input() ticker = ticker.lower() print("Price: $", get_price(ticker)) elif selection == "4": ticker = view.get_ticker_input() amount = int(view.get_amount_input()) account.buy(ticker, amount) elif selection == "5": ticker = view.get_ticker_input() amount = int(view.get_amount_input()) account.sell(ticker, amount) elif selection == "6": trades = account.get_trades() for trade in trades: date = time.ctime(int(trade.date)) if trade.type == 1: trade.type = "bought" if trade.type == 0: trade.type = "sold" print(date, ":", trade.ticker.upper(), ":", trade.type, trade.quantity) elif selection == "7": print("Your API Key: ", account.api_key)
def buy(self, ticker, amount): #Get account details account = self.get_account() #Check stock exists and if so retrieve current price quote_price = get_price(ticker) if not quote_price: # raise KeyError msg = "Input Ticker doesn't exist" else: #Check sufficient funds quote_price = float(quote_price) amount = float(amount) if not account.balance >= amount * quote_price: #raise ValueError msg = "Insufficient funds" else: #Insert Trade row new_trade = Trade(accounts_pk=self.pk, ticker=ticker, \ volume=amount, price=quote_price) new_trade.save() #Update or Insert Position row position = self.get_position_for(ticker) if position.shares == 0: #Insert new_position = Position(accounts_pk=self.pk, ticker=ticker, shares=amount) else: #Update new_position = Position(pk=position.pk, accounts_pk=self.pk, ticker=ticker, \ shares=position.shares + amount) new_position.save() #Update balance on Account row new_balance = Account(pk=self.pk, username=account.username, \ password_hash=account.password_hash, \ balance=account.balance - (amount*quote_price), \ api_key=account.api_key) new_balance.save() msg = "Buy transaction completed successfully" return msg
def sell(self, ticker, quantity): """ SELL stock. checks if a stock exists in the user's positions and has sufficient shares. creates a new Trade and modifies the Position as well as adding to the user's balance. returns nothing """ trade = Trade() current_price = get_price(ticker) mv = current_price * int(quantity) trade.account_id = self.account_id trade.volume = quantity trade.ticker = ticker trade.price = current_price trade.market_value = mv * -1 self.balance += mv self.update_balance() position = Position() position.account_id = self.account_id position.ticker = trade.ticker stored_position = Position.select_one_where( 'WHERE account_id=? and ticker=?', (position.account_id, position.ticker)) if stored_position: position.num_shares = stored_position.num_shares position.position_id = stored_position.position_id if stored_position.num_shares < trade.volume or stored_position.num_shares == 0: transaction_error('Not enough shares') else: trade.save() if stored_position: position.num_shares = trade.volume else: position.num_shares -= trade.volume position.save() else: transaction_error('Ticker {} is invalid'.format(trade.ticker))
def buy(api_key, ticker, amount): account = Account.authenticate_api(api_key) price = round(get_price(ticker)[1]) purchase = int(amount) * price if account.balance == None or account.balance < purchase: return jsonify({"error": "bad request"}) elif not price: return jsonify({"error": "bad ticker data"}) if request.json['amount'] and request.json[ 'ticker'] and account.balance > int(purchase): account.buy(ticker, amount, price, purchase) return jsonify({ "username": account.username, "balance": round(account.balance) }) else: return jsonify({"error": "bad ticker data"}) if not account: return jsonify({"error": "authentication error"}), 401
def buy(self, ticker, quantity): """ BUY stock. checks if a stock exists in the user's positions and has sufficient shares. creates a new Trade and modifies the Position as well as adding to the user's balance. returns nothing """ trade = Trade() current_price = get_price(ticker) mv = current_price * int(quantity) if self.balance < mv: transaction_error('Insufficient funds') else: trade.account_id = self.account_id trade.volume = quantity trade.ticker = ticker trade.price = current_price trade.market_value = mv self.balance -= mv self.update_balance() position = Position() position.account_id = self.account_id position.ticker = trade.ticker stored_position = Position.select_one_where( 'WHERE account_id=? and ticker=?', (position.account_id, position.ticker)) if stored_position: position.position_id = stored_position.position_id position.num_shares = stored_position.num_shares position.num_shares += trade.volume else: position.num_shares = trade.volume trade.save() position.save()
def logged_in_homepage(account): while True: print(account.username, account.balance) selection = view.logged_in_screen(account.username, account.balance) if selection not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: view.improper_selection() time.sleep(3) if selection == '1': Account.get_positions(account) elif selection == '2': deposit = view.deposit_funds() if not deposit.isdigit() or int(deposit) < 1: view.improper_balance() time.sleep(3) else: account.balance = int(account.balance) + int(deposit) account.save() continue elif selection == '3': ticker_request = view.request_ticker_symbol() ticker_response = get_price(ticker_request) if type(ticker_response) == list: view.return_ticker_symbol_price(ticker_response) time.sleep(2) else: view.improper_ticker() time.sleep(3) elif selection == '4': ticker = view.request_ticker_symbol() current_price = get_price(ticker) share_amount = view.get_shares(current_price) if share_amount: try: Account.buy(account, ticker, share_amount, current_price) except ValueError: view.insufficient_funds() else: view.improper_ticker() time.sleep(3) # elif selection == '5': # Account.get_positions(account) # # time.sleep(3) # ticker_to_sell = view.sell_shares() # has_stock = get_price(ticker_to_sell) # print(has_stock) # amount = view.sell_shares_amount() # current_price = get_price(ticker_to_sell) # if has_stock: # Account.sell(account, ticker_to_sell, amount, current_price) # else: # view.improper_ticker() # time.sleep(3) elif selection == '5': Account.get_positions(account) ticker = view.request_ticker_symbol() shares = int(view.sell_shares()) try: Account.sell(account, ticker, shares) except ValueError: view.wups() time.sleep(3) # view.clearscreen() elif selection == '6': selection = view.select_trade_option(account.username) if len(selection) != 1 or selection.lower() not in ['a', 'b', 'c']: view.improper_selection() time.sleep(3) elif selection.lower() == 'a': account_trades = Account.get_trades(account) for trade in account_trades: view.show_trades(account.username, trade) time.sleep(1) elif selection.lower() == 'b': ticker_symbol = view.request_ticker_symbol() account_trades_by_ticker = Account.trades_for( account, ticker_symbol) if account_trades_by_ticker: for trade in account_trades_by_ticker: view.show_trades(account.username, trade) time.sleep(3) else: view.improper_ticker() time.sleep(3) elif selection.lower() == 'c': continue elif selection == '7': view.goodbye() welcome_homepage() return elif selection == '8': view.goodbye() return elif selection == '9': top_traded( 'https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,fb&types=quote,news,chart&range=1m&last=5' ) time.sleep(3)
def lookup(ticker): ticker = util.get_price(ticker) if not ticker: return jsonify({'error': "ticker error"}), 400 return jsonify({'ticker': ticker})
def main_loop(): while True: choice = user_menu() if choice is None: # incorrect selection bad_input('Please select option') elif choice == '4': # exit goodbye() break elif choice == '1': login_input = login_username_pw() verified_account = Account.login(login_input) if verified_account: db_password_hash = verified_account[2] password_verify = checkpw(login_input[1].encode(), db_password_hash) if password_verify: account = Account(account_id = verified_account[0]) account.username = verified_account[1] account.balance = int(verified_account[3]) while True: choice = main_menu() if choice is None: bad_input('Please select option') elif choice == '1': # view account balance display_balance(account.balance) elif choice == '2': # deposit funds account.balance += deposit() Account.update_balance(account) elif choice == '3': # buy stock buy_stock = trade_stock() account.buy(buy_stock[0], buy_stock[1]) elif choice == '4': #sell stock buy_stock = trade_stock() account.sell(buy_stock[0], buy_stock[1]) elif choice == '5': # view positions display_positions(Account.get_positions(account)) elif choice == '6': # view trades display_trade_history(Account.get_trades(account)) elif choice == '7': # lookup price of stock ticker = view.lookup_ticker() print("Ticker: {} is currently: ${}".format(ticker, get_price(ticker))) elif choice == '8': # See API Keys display_api(Account.retrieve_api_key(account)) elif choice == '9': # logout goodbye() else: bad_input('Retry') else: bad_input('Incorrect password') else: bad_input('Incorrect username') elif choice == '2': # login with api user_api_key = login_api_key() # print(user_api_key) user = Account.api_authenticate(user_api_key) display_user_from_api_key(user) elif choice == '3': # create new account account_details[0] = "mark" account_details[1] = "1234" account_details[2] = 1000 account_details = create_account() account = Account() account.username = account_details[0] account.password_hash = account_details[1] account.balance = account_details[2] account.api_key = account.generate_api_key() Account.save(account)
def lookup(ticker): response = get_price(ticker) if response: return jsonify({"symbol": response[0], "price": response[1]}) else: return jsonify({"error": "404 not found"}), 404
def main_menu_ctrl(user): while True: input() os.system("clear") answer = view.main_menu(user.username) if int(answer) == 9: view.program_end() return None elif int(answer) == 8: user.set_password(util.hash_pass(view.set_password_inpt())) user.save() view.saving_change() elif int(answer) == 7: trades = user.get_trades() view.total_trades(len(trades)) for trade in trades: view.trade_detail(trade.volume, trade.ticker, trade.price, trade.price * trade.volume, trade.time) elif int(answer) == 6: positions = user.get_positions() if len(positions) == 0: view.no_positions() else: bal = 0 for position in positions: ticker = position.ticker shares = position.shares px = util.get_price(ticker) bal += px * shares view.stockbal(shares, ticker, px * shares) view.totbal(bal) elif int(answer) == 5: val_ord = True while val_ord == True: ticker = view.ask_ticker() px = float(util.get_price(ticker)) view.show_ticker_price(ticker, px) if user.get_position_for(ticker).shares != 0: shares = view.ask_num_shares() try: y_n = view.confirm_order("sell", ticker, shares, px * shares) if y_n == "y" or "Y": user.sell(ticker, shares) view.total_trades(1) val_ord = False else: view.choose_valid() val_ord = True except ValueError: view.insuf_funds() val_ord = True else: view.no_position_stock() elif int(answer) == 4: val_ord = True while val_ord == True: ticker = view.ask_ticker() px = float(util.get_price(ticker)) view.show_ticker_price(ticker, px) view.bal_and_pos(user.balance) shares = view.ask_num_shares() try: y_n = view.confirm_order("buy", ticker, shares, px * shares) if y_n == "y" or "Y": user.buy(ticker, shares) view.total_trades(1) val_ord = False else: view.choose_valid() val_ord = True except ValueError: view.insuf_funds() val_ord = True elif int(answer) == 3: amt = view.deposit_inpt() user.deposit(amt) view.deposit_outp(amt) view.newbalance_statement(user.balance) elif int(answer) == 2: x = True while x == True: ticker = view.ask_ticker() try: px = util.get_price(ticker) view.show_ticker_price(ticker, px) x = False except requests.ConnectionError: view.choose_valid() elif int(answer) == 1: view.api_key(user.api_key) view.bal_and_pos(user.balance) positions = user.get_positions() if len(positions) == 0: view.no_positions() else: bal = 0 for position in positions: ticker = position.ticker shares = position.shares px = util.get_price(ticker) bal += px * shares view.totbal(bal) view.totport(bal + user.balance) else: view.choose_valid()
def logged_in_homepage(account): while True: selection = view.logged_in_screen(account.username, account.balance) if selection not in ["1", "2", "3", "4", "5", "6", "7", "8"]: view.improper_selection() time.sleep(3) if selection == "1": view.account_positions(account.username) Account.get_positions(account) time.sleep(3) elif selection == "2": deposit = view.deposit_funds() if not deposit.isdigit() or int(deposit) < 1: view.improper_balance() time.sleep(3) else: account.balance = int(account.balance) + int(deposit) account.save() continue elif selection == "3": ticker_request = view.request_ticker_symbol() ticker_response = get_price(ticker_request) if type(ticker_response) == list: view.return_ticker_symbol_price(ticker_response) time.sleep(3) else: view.improper_ticker() time.sleep(3) elif selection == "4": ticker = view.request_ticker_symbol() ticker_price = get_price(ticker) if ticker_price == False: view.improper_ticker() time.sleep(3) continue purchase_amount = view.get_shares(ticker_price) if not purchase_amount.isdigit(): view.improper_money() time.sleep(3) continue total_cost = int(purchase_amount) * int(ticker_price[1]) if total_cost < int(account.balance): Account.buy(account, ticker, purchase_amount, ticker_price[1], total_cost) elif int(total_cost) > int(account.balance): view.not_enough_money() time.sleep(3) elif selection == "5": Account.get_positions(account) time.sleep(3) ticker_to_sell = view.sell_shares() has_stock = get_price(ticker_to_sell) position = account.get_position_for(ticker_to_sell) amount = view.sell_shares_amount() if has_stock and position.shares >= int(amount): Account.sell(account, ticker_to_sell, amount) elif not has_stock: view.improper_ticker() time.sleep(3) else: view.not_enough_shares() elif selection == "6": selection = view.select_trade_option(account.username) if len(selection) != 1 or selection.lower() not in ["a", "b", "c"]: view.improper_selection() time.sleep(3) elif selection.lower() == "a": account_trades = Account.get_trades(account) if not account_trades: view.no_trades(account.username) time.sleep(3) for trade in account_trades: view.show_trades(account.username, trade) time.sleep(3) elif selection.lower() == "b": ticker_symbol = view.request_ticker_symbol() account_trades_by_ticker = Account.trades_for(account, ticker_symbol) if get_price(ticker_symbol) == False: view.improper_ticker() time.sleep(3) elif not account_trades_by_ticker: view.no_trades(account.username) time.sleep(3) else: for trade in account_trades_by_ticker: view.show_trades(account.username, trade) time.sleep(3) elif selection.lower() == "c": continue elif selection == "7": view.goodbye() welcome_homepage() return elif selection == "8": view.goodbye() return