pass username = input() if password == "": password = getpass.getpass() logged_in = robinhood.login(username=username, password=password) if logged_in == False: password = "" print("Invalid username or password. Try again.\n") fields = collections.defaultdict(dict) trade_count = 0 queued_count = 0 # fetch order history and related metadata from the Robinhood API orders = robinhood.get_endpoint('orders') # load a debug file # raw_json = open('debug.txt','rU').read() # orders = ast.literal_eval(raw_json) # store debug if args.debug: # save the CSV try: with open("debug.txt", "w+") as outfile: outfile.write(str(orders)) print("Debug infomation written to debug.txt") except IOError: print('Oops. Unable to write file to debug.txt')
password=password, mfa_code=mfa_code) if logged_in != True: password = "" print("Invalid username or password. Try again.\n") print("Pulling trades. Please wait...") fields = collections.defaultdict(dict) trade_count = 0 queued_count = 0 # fetch order history and related metadata from the Robinhood API #orders = robinhood.get_endpoint('orders') orders = robinhood.get_endpoint('optionsOrders') # load a debug file # raw_json = open('debug.txt','rU').read() # orders = ast.literal_eval(raw_json) # store debug if args.debug: # save the CSV try: with open("debug.txt", "w+") as outfile: outfile.write(str(orders)) print("Debug infomation written to debug.txt") except IOError: print('Oops. Unable to write file to debug.txt') # Vignesh save the CSV
print "Robinhood username:"******"": password = getpass.getpass() logged_in = robinhood.login(username=username, password=password) if logged_in == False: password = "" print "Invalid username or password. Try again.\n", fields = collections.defaultdict(dict) trade_count = 0 queued_count = 0 # fetch order history and related metadata from the Robinhood API orders = robinhood.get_endpoint('orders') # load a debug file # raw_json = open('debug.txt','rU').read() # orders = ast.literal_eval(raw_json) # store debug if args.debug: # save the CSV try: with open("debug.txt", "w+") as outfile: outfile.write(str(orders)) print "Debug infomation written to debug.txt" except IOError: print 'Oops. Unable to write file to debug.txt'
class RobinhoodDataFetcher(PortfolioDataFetcher): """ """ def __init__(self, username, password): self.username = username self.password = password self.robinhood = Robinhood() self.loggedin = self.robinhood.login(username=username, password=password) self.trades = self.prep_data() def prep_data(self): if not self.loggedin: return None orders = self.robinhood.get_endpoint('orders') trade_count = 0 queued_count = 0 trades = collections.defaultdict(dict) # do/while for pagination paginated = True page = 0 while paginated: for i, order in enumerate(orders['results']): executions = order['executions'] instrument = self.robinhood.get_custom_endpoint( order['instrument']) trades[i + (page * 100)]['symbol'] = instrument['symbol'] for key, value in enumerate(order): if value != "executions": trades[i + (page * 100)][value] = order[value] if order['state'] == "filled": trade_count += 1 for key, value in enumerate(executions[0]): trades[i + (page * 100)][value] = executions[0][value] elif order['state'] == "queued": queued_count += 1 # paginate if orders['next'] is not None: page = page + 1 orders = self.robinhood.get_custom_endpoint(str( orders['next'])) else: paginated = False return trades def add_trades_to_app(self): if self.trades: for t in self.trades: ticker = self.trades[t]['symbol'] trade_id = self.trades[t]['id'] price = self.trades[t]['price'] quantity = self.trades[t]['quantity'] side = self.trades[t]['side'] state = self.trades[t]['state'] created_at = self.trades[t]['created_at'] updated_at = self.trades[t]['updated_at'] # trade = TradeModel.objects.all() # print(ticker, trade_id, price, quantity, side, state, ticker) trade = TradeModel.objects.filter(uuid=trade_id) stock = StockModel.objects.filter(ticker=ticker) if not stock: stock = StockModel(ticker=ticker) stock.save() if not trade: try: stock = StockModel.objects.filter(ticker=ticker)[0] trade = TradeModel( stock=stock, quantity=quantity, price=price, uuid=trade_id, side=side, state=state, ) trade.save() except Exception as e: sys.stderr.write('error in add_trades_to_app') def addCurrentPositionsToPortfolio(trades, portfolio_name): p = PortfolioModel.objects.filter(name=portfolio_name) portfolio = {} portfolio_keys = [ 'current shares', 'exit profit', 'avg cost', 'total cost', 'unrealized profit', 'realized profits' ] if not p: return for entry in trades: if entry['average_price'] == 'None': trades.remove(entry) portfolio[entry]['symbol'] = {} for company in portfolio: for k in portfolio_keys: portfolio[company][k] = 0 portfolio[company]['profits on sale'] = [] test_stock = None for entry in trades: stock = portfolio[entry['symbol']] if test_stock and entry['symbol'] == test_stock: print('testing') return if entry['side'] == 'buy': stock['current shares'] += float(entry['quantity']) stock['total cost'] += (float(entry['quantity']) * float(entry['price'])) stock[ 'avg cost'] = stock['total cost'] / stock['current shares'] if entry['side'] == 'sell': stock['current shares'] -= float(entry['quantity']) # total cost - (current total avg cots * quantity selling) stock['total cost'] = stock['total cost'] - ( stock['avg cost'] * float(entry['quantity'])) profit_on_sale = (float(entry['price']) - stock['avg cost']) * float(entry['quantity']) stock['profits on sale'].append(profit_on_sale) #profit? # stock['total cost'] = stock['total cost'] - (float(entry['quantity']) * float(entry['price'])) # stock['avg cost'] = stock['total cost'] / stock['current shares'] for stock in portfolio: portfolio[stock]['realized profits'] = sum( portfolio[stock]['profits on sale']) portfolio.pop('YANG', None) current_stocks = [] for stock in portfolio: if portfolio[stock]['quantity'] is not 0: current_stocks.append(stock) p = PortfolioModel.objects.filter(name=portfolio_name) p.stocks = stocks p.save() return portfolio
username=username, password=password, device_token=device_token, mfa_code=mfa_code) print("Pulling trades. Please wait...") fields = collections.defaultdict(dict) trade_count = 0 queued_count = 0 #holds instrument['symbols'] to reduce API ovehead {instrument_url:symbol} cached_instruments = {} # fetch order history and related metadata from the Robinhood API orders = robinhood.get_endpoint('orders') # load a debug file # raw_json = open('debug.txt','rU').read() # orders = ast.literal_eval(raw_json) # store debug if args.debug: # save the CSV try: with open("debug.txt", "w+") as outfile: outfile.write(str(orders)) print("Debug infomation written to debug.txt") except IOError: print('Oops. Unable to write file to debug.txt')
input = raw_input except NameError: pass mfa_code = input() logged_in = robinhood.login(username=username, password=password, mfa_code=mfa_code) if logged_in != True: password = "" print("Invalid username or password. Try again.\n") print("Pulling trades. Please wait...") # fetch transfer history and related metadata from the Robinhood API transfers = robinhood.get_endpoint('ach_transfers') # do/while for pagination paginated = True page = 0 TransferList = pd.DataFrame() while paginated: #create and append transferlist TransferList = TransferList.append( pd.DataFrame.from_dict(transfers['results'], orient='columns')) # paginate if transfers['next'] is not None: page = page + 1 transfers = robinhood.get_custom_endpoint(str(transfers['next']))
def getRobinhoodTrades(username, password, debug=False): robinhood = Robinhood() logged_in = robinhood.login(username=username, password=password) if logged_in == False: print("Invalid username or password. Try again.\n") return None trades = [] cached_instruments = {} #{instrument:symbol} robinhood_cache = {} last_page_url = None if os.path.isfile("robinhood_cache"): robinhood_cache = pickle.load(open("robinhood_cache", "rb")) # last_page_url = robinhood_cache['last_page_url'] print(last_page_url) cached_instruments = robinhood_cache['instruments'] # trades = robinhood_cache['trades'] if not os.path.isfile("robinhood_cache") or last_page_url is None: # fetch order history and related metadata from the Robinhood API orders = robinhood.get_endpoint('orders') else: orders = robinhood.get_custom_endpoint(last_page_url) # do/while for pagination #pagination paginated = True page = 0 length_of_trades_at_last_page = len(trades) while paginated: for i, order in enumerate(orders['results']): executions = order['executions'] if len(executions) > 0: # Iterate over all the different executions for execution in executions: # Get the Symbol of the order trades.append({}) if order['instrument'] not in cached_instruments: cached_instruments[order['instrument']] = robinhood.get_custom_endpoint(order['instrument'])['symbol'] trades[-1]['symbol'] = cached_instruments[order['instrument']] # Get all the key,value from the order for key, value in enumerate(order): if value != "executions": trades[-1][value] = order[value] # Get specific values from the execution of the order trades[-1]['timestamp'] = execution['timestamp'] trades[-1]['quantity'] = execution['quantity'] trades[-1]['price'] = execution['price'] elif order['state'] == "queued": pass if orders['next'] is not None: page = page + 1 #get the next order, a page is essentially one order if debug: print(str(page) + "," + orders['next']) last_page_url = orders['next'] length_of_trades_at_last_page = len(trades) orders = robinhood.get_custom_endpoint(orders['next']) else: paginated = False robinhood_cache['last_page_url'] = last_page_url robinhood_cache['instruments'] = cached_instruments robinhood_cache['trades'] = trades[:length_of_trades_at_last_page] # dont include trades of the last page, because they will be queried for again pickle.dump(robinhood_cache, open("robinhood_cache", "wb")) # check we have trade data to export if len(trades) > 0: print("%d executed trades found in your account." % len(trades)) else: print("No trade history found in your account.") quit() # parse float keys float_keys = ["price","fees","quantity"] for trade in trades: for key in float_keys: try: trade[key] = round(float(trade[key]),2) except: continue return trades