def get_instrument_by_url(url,info=None): """Takes a single url for the stock. Should be located at ``https://api.robinhood.com/instruments/<id>`` where <id> is the id of the stock. :param url: The url of the stock. Can be found in several locations including \ in the dictionary returned from get_instruments_by_symbols(inputSymbols,info=None) :type url: str :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. """ data = helper.request_get(url,'regular') return(helper.filter(data,info))
def get_option_market_data_by_id(id, info=None): """Returns the option market data for a stock, including the greeks, open interest, change of profit, and adjusted mark price. :param id: The id of the stock. :type id: str :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a dictionary of key/value pairs for the stock. \ If info parameter is provided, the value of the key that matches info is extracted. """ url = urls.marketdata(id) data = helper.request_get(url) return (helper.filter(data, info))
def get_pricebook_by_id(stock_id, info=None): """ Represents Level II Market Data provided for Gold subscribers :param stock_id: robinhood stock id :type stock_id: str :param info: Will filter the results to get a specific value. Possible options are url, instrument, execution_date, \ divsor, and multiplier. :type info: Optional[str] :return: Returns a dictionary of asks and bids. """ url = urls.marketdata_pricebook(stock_id) data = helper.request_get(url) return (helper.filter(data, info))
def get_bank_transfers(direction=None, info=None): """Returns all bank transfers made for the account. :param direction: Possible values are 'received'. If left blank, function will return all withdrawls and deposits \ that are initiated from Robinhood. If the value is 'received', funciton will return transfers intiated from \ your bank rather than Robinhood. :type direction: Optional[str] :param info: Will filter the results to get a specific value. 'direction' gives if it was deposit or withdrawl. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for each transfer. If info parameter is provided, \ a list of strings is returned where the strings are the value of the key that matches info. """ url = urls.banktransfers(direction) data = helper.request_get(url, 'pagination') return (helper.filter_data(data, info))
def find_tradable_options(symbol, expirationDate=None, strikePrice=None, optionType=None, info=None): """Returns a list of all available options for a stock. :param symbol: The ticker of the stock. :type symbol: str :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param strikePrice: Represents the strike price of the option. :type strikePrice: str :param optionType: Can be either 'call' or 'put' or left blank to get both. :type optionType: Optional[str] :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all calls of the stock. If info parameter is provided, \ a list of strings is returned where the strings are the value of the key that matches info. """ try: symbol = symbol.upper().strip() except AttributeError as message: print(message) return [None] url = urls.option_instruments() if not helper.id_for_chain(symbol): print("Symbol {} is not valid for finding options.".format(symbol)) return [None] payload = { 'chain_id': helper.id_for_chain(symbol), 'chain_symbol': symbol, 'state': 'active' } if expirationDate: payload['expiration_date'] = expirationDate if strikePrice: payload['strike_price'] = strikePrice if optionType: payload['type'] = optionType data = helper.request_get(url, 'pagination', payload) return (helper.filter(data, info))
def find_options_for_list_of_stocks_by_expiration_date(inputSymbols,expirationDate,optionType='both',info=None): """Returns a list of all the option orders that match the seach parameters :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param optionType: Can be either 'call' or 'put'. :type optionType: Optional[str] :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all options of the stock that match the search parameters. \ If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ symbols = helper.inputs_to_set(inputSymbols) try: optionType = optionType.lower().strip() except AttributeError as message: print(message) return [None] data = [] url = urls.option_instruments() for symbol in symbols: if (optionType == 'put' or optionType == 'call' ): payload = { 'chain_id' : helper.id_for_chain(symbol), 'expiration_date' : expirationDate, 'state' : 'active', 'tradability' : 'tradable', 'type' : optionType} else: payload = { 'chain_id' : helper.id_for_chain(symbol), 'expiration_date' : expirationDate, 'state' : 'active', 'tradability' : 'tradable'} otherData = helper.request_get(url,'pagination',payload) for item in otherData: if item['expiration_date'] == expirationDate: data.append(item) for item in data: marketData = get_option_market_data_by_id(item['id']) item.update(marketData) return(helper.filter(data,info))
def get_option_historicals(symbol,expirationDate,strike,optionType,span='week'): """Returns the data that is used to make the graphs. :param symbol: The ticker of the stock. :type symbol: str :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param strike: Represents the price of the option. :type strike: str :param optionType: Can be either 'call' or 'put'. :type optionType: str :param span: Sets the range of the data to be either 'day', 'week', 'year', or '5year'. Default is 'week'. :type span: Optional[str] :returns: Returns a list that contains a list for each symbol. \ Each list contains a dictionary where each dictionary is for a different time. """ try: symbol = symbol.upper().strip() optionType = optionType.lower().strip() except AttributeError as message: print(message) return [None] span_check = ['day','week','year','5year'] if span not in span_check: print('ERROR: Span must be "day","week","year",or "5year"') return([None]) if span == 'day': interval = '5minute' elif span == 'week': interval = '10minute' elif span == 'year': interval = 'day' else: interval = 'week' optionID = helper.id_for_option(symbol,expirationDate,strike,optionType) url = urls.option_historicals(optionID) payload = { 'span' : span, 'interval' : interval} data = helper.request_get(url,'regular',payload) return(data)
def get_name_by_url(url): """Returns the name of a stock from the instrument url. Should be located at ``https://api.robinhood.com/instruments/<id>`` where <id> is the id of the stock. :param url: The url of the stock as a string. :type url: str :returns: [str] Returns the simple name of the stock. If the simple name does not exist then returns the full name. """ data = helper.request_get(url) if not data: return (None) # If stock doesn't have a simple name attribute then get the full name. filter = helper.filter(data, info='simple_name') if not filter or filter == "": filter = helper.filter(data, info='name') return (filter)
def cancel_all_open_orders(): """Cancels all open orders. :returns: The list of orders that were cancelled. """ url = urls.orders() items = helper.request_get(url,'pagination') items = [item['id'] for item in items if item['cancel'] is not None] for item in items: cancel_url = urls.cancel(item) data = helper.request_post(cancel_url) print('All Orders Cancelled') return(items)
def export_completed_option_orders(file_path): """Write all completed option orders to a csv :param file_path: absolute path to the location the file will be written. :type file_path: str """ all_orders = orders.get_all_option_orders() with open(f"{file_path}option_orders_{dt.date.today().strftime('%b-%d-%Y')}.csv", 'w', newline='') as f: writer = csv.writer(f) writer.writerow([ 'chain_symbol', 'expiration_date', 'strike_price', 'option_type', 'side', 'order_created_at', 'direction', 'order_quantity', 'order_type', 'opening_strategy', 'closing_strategy', 'price', 'processed_quantity' ]) for order in all_orders: if order['state'] == 'filled': for leg in order['legs']: instrument_data = helper.request_get(leg['option']) writer.writerow([ order['chain_symbol'], instrument_data['expiration_date'], instrument_data['strike_price'], instrument_data['type'], leg['side'], order['created_at'], order['direction'], order['quantity'], order['type'], order['opening_strategy'], order['closing_strategy'], order['price'], order['processed_quantity'] ]) f.close()
def export_option_orders_date_range(dir_path, start_date, end_date, file_name=None, page_limit=sys.maxsize): """Write all of the option orders within a date range to a csv :param dir_path: Absolute or relative path to the directory the file will be written. :type dir_path: str :param file_name: An optional argument for the name of the file. If not defined, filename will be option_orders_{current date} :type file_name: Optional[str] :param start_date: The start of the date range in format 2020-12-21 :type start_date: str :param end_date: The end of the date range in format 2020-12-21 :type end_date: str """ file_path = create_absolute_csv(dir_path, file_name, 'option') all_orders = orders.get_all_option_orders(page_limit) with open(file_path, 'w', newline='') as f: csv_writer = writer(f) csv_writer.writerow([ 'chain_symbol', 'expiration_date', 'strike_price', 'option_type', 'side', 'order_created_at', 'direction', 'order_quantity', 'order_type', 'opening_strategy', 'closing_strategy', 'processed_premium', 'processed_quantity' ]) for order in all_orders: orderDate = datetime.strptime(order['created_at'][:10], "%Y-%m-%d") start = datetime.strptime(str(start_date), "%Y-%m-%d") end = datetime.strptime(str(end_date), "%Y-%m-%d") if start <= orderDate <= end: for leg in order['legs']: instrument_data = helper.request_get(leg['option']) csv_writer.writerow([ order['chain_symbol'], instrument_data['expiration_date'], instrument_data['strike_price'], instrument_data['type'], leg['side'], order['created_at'], order['direction'], order['quantity'], order['type'], order['opening_strategy'], order['closing_strategy'], order['processed_premium'], order['processed_quantity'] ]) f.close()
def get_card_transactions(cardType=None, info=None): """Returns all debit card transactions made on the account :param cardType: Will filter the card transaction types. Can be 'pending' or 'settled'. :type cardType: Optional[str] :param info: Will filter the results to get a specific value. 'direction' gives if it was debit or credit. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for each transfer. If info parameter is provided, \ a list of strings is returned where the strings are the value of the key that matches info. """ payload = None if type: payload = {'type': type} url = urls.cardtransactions() data = helper.request_get(url, 'pagination', payload) return (helper.filter(data, info))
def get_crypto_historical(symbol, interval, span, bound, info=None): """Gets historical information about a crypto including open price, close price, high price, and low price. :param symbol: The crypto ticker. :type symbol: str :param interval: The time between data points. :type interval: str :param span: The entire time frame to collect data points. :type span: str :param bound: The times of dat to collect data points. :type bound: str :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. """ interval_check = ['15second', '5minute', '10minute', 'hour', 'day', 'week'] span_check = ['hour', 'day', 'week', 'month', '3month', 'year', '5year'] bounds_check = ['24_7', 'extended', 'regular', 'trading'] if interval not in interval_check: print( 'ERROR: Interval must be "15second","5minute","10minute","hour","day",or "week"' ) return ([None]) if span not in span_check: print( 'ERROR: Span must be "hour","day","week","month","3month","year",or "5year"' ) return ([None]) if bound not in bounds_check: print('ERROR: Bounds must be "24_7","extended","regular",or "trading"') return ([None]) if (bound == 'extended' or bound == 'trading') and span != 'day': print( 'ERROR: extended and trading bounds can only be used with a span of "day"' ) return ([None]) id = get_crypto_info(symbol, info='id') url = urls.crypto_historical(id, interval, span, bound) data = helper.request_get(url) return (helper.filter(data, info))
def get_popularity(symbol, info=None): """Returns the number of open positions. :param symbol: The stock ticker. :type symbol: str :param info: Will filter the results to be a string value. :type info: Optional[str] :returns: If the info parameter is provided, then the function will extract the value of the key \ that matches the info parameter. Otherwise, the whole dictionary is returned. """ try: symbol = symbol.upper().strip() except AttributeError as message: print(message) return None url = urls.popularity() payload = {'ids': helper.id_for_stock(symbol)} data = helper.request_get(url, payload) res = helper.filter(data, info) return res[0]
def get_crypto_info(symbol, info=None): """Gets information about a crpyto currency. :param symbol: The crypto ticker. :type symbol: str :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. """ url = urls.crypto_currency_pairs() data = helper.request_get(url, 'results') data = [x for x in data if x['asset_currency']['code'] == symbol] if len(data) > 0: data = data[0] else: data = None return(helper.filter(data, info))
def find_instrument_data(query): """Will search for stocks that contain the query keyword and return the instrument data. :param query: The keyword to search for. :type query: str :returns: [list] Returns a list of dictionaries that contain the instrument data for each stock that matches the query. :Dictionary Keys: * id * url * quote * fundamentals * splits * state * market * simple_name * name * tradeable * tradability * symbol * bloomberg_unique * margin_initial_ratio * maintenance_ratio * country * day_trade_ratio * list_date * min_tick_size * type * tradable_chain_id * rhs_tradability * fractional_tradability * default_collar_fraction """ url = urls.instruments() payload = {'query': query} data = helper.request_get(url, 'pagination', payload) if len(data) == 0: print('No results found for that keyword', file=helper.get_output()) return ([None]) else: print('Found ' + str(len(data)) + ' results', file=helper.get_output()) return (data)
def find_instrument_data(query): """Will search for stocks that contain the query keyword and return the instrument data. :param query: The keyword to search for. :type query: str :returns: Returns a list of dictionaries that contain the instrument data for each stock that matches the query. """ url = urls.instruments() payload = {'query': query} data = helper.request_get(url, 'pagination', payload) if len(data) == 0: print('No results found for that keyword') return ([None]) else: print('Found ' + str(len(data)) + ' results') return (data)
def get_quotes(inputSymbols, info=None): """Takes any number of stock tickers and returns information pertaining to its price. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: [list] If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. :Dictionary Keys: * ask_price * ask_size * bid_price * bid_size * last_trade_price * last_extended_hours_trade_price * previous_close * adjusted_previous_close * previous_close_date * symbol * trading_halted * has_traded * last_trade_price_source * updated_at * instrument """ symbols = helper.inputs_to_set(inputSymbols) url = urls.quotes() payload = {'symbols': ','.join(symbols)} data = helper.request_get(url, 'results', payload) if (data == None or data == [None]): return data for count, item in enumerate(data): if item is None: print(helper.error_ticker_does_not_exist(symbols[count]), file=helper.get_output()) data = [item for item in data if item is not None] return (helper.filter(data, info))
def find_tradable_options_for_stock(symbol, optionType='both', info=None): """Returns a list of all available options for a stock. :param symbol: The ticker of the stock. :type symbol: str :param optionType: Can be either 'call' or 'put' or left blank to get both. :type optionType: Optional[str] :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all calls of the stock. If info parameter is provided, \ a list of strings is returned where the strings are the value of the key that matches info. """ try: symbol = symbol.upper().strip() optionType = optionType.lower().strip() except AttributeError as message: print(message) return [None] url = urls.option_instruments() if not helper.id_for_chain(symbol): print("Symbol {} is not valid for finding options.".format(symbol)) if (optionType == 'call' or optionType == 'put'): payload = { 'chain_id': helper.id_for_chain(symbol), 'chain_symbol': symbol, 'state': 'active', 'tradability': 'tradable', 'type': optionType } else: payload = { 'chain_id': helper.id_for_chain(symbol), 'chain_symbol': symbol, 'state': 'active', 'tradability': 'tradable' } data = helper.request_get(url, 'pagination', payload) return (helper.filter(data, info))
def find_options_for_stock_by_expiration_and_strike(symbol,expirationDate,strike,optionType='both',info=None): """Returns a list of all the option orders that match the seach parameters :param symbol: The ticker of the stock. :type symbol: str :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param strike: Represents the price of the option. :type strike: str :param optionType: Can be either 'call' or 'put' or leave blank to get both. :type optionType: Optional[str] :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all options of the stock that match the search parameters. \ If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ try: symbol = symbol.upper().strip() option_type = optionType.lower().strip() except AttributeError as message: print(message) return [None] url = urls.option_instruments() payload = {'chain_id': helper.id_for_chain(symbol), 'expiration_date': expirationDate, 'strike_price': strike, 'state': 'active', 'tradability': 'tradable', 'rhs_tradability': 'tradable'} if option_type == 'put' or option_type == 'call': payload['type'] = option_type data = helper.request_get(url, 'pagination', payload) data = [item for item in data if item['expiration_date'] == expirationDate and item['tradability'] == 'tradable'] for item in data: market_data = get_option_market_data_by_id(item['id']) item.update(market_data) return helper.filter(data, info)
def load_crypto_profile(info=None): """Gets the information associated with the crypto account. :param info: The name of the key whose value is to be returned from the function. :type info: Optional[str] :returns: [dict] The function returns a dictionary of key/value pairs. \ If a string is passed in to the info parameter, then the function will return \ a string corresponding to the value of the key whose name matches the info parameter. :Dictionary Keys: * apex_account_number * created_at * id * rhs_account_number * status * status_reason_code * updated_at * user_id """ url = urls.crypto_account() data = helper.request_get(url, 'indexzero') return (helper.filter_data(data, info))
def get_watchlist_by_name(name='Default', info=None): """Returns a list of information related to the stocks in a single watchlist. :param name: The name of the watchlist to get data from. :type name: Optional[str] :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries that contain the instrument urls and a url that references itself. """ #Get id of requested watchlist all_watchlists = get_all_watchlists() watchlist_id = '' for wl in all_watchlists['results']: if wl['display_name'] == name: watchlist_id = wl['id'] url = urls.watchlists(name) data = helper.request_get(url, 'list_id', {'list_id': watchlist_id}) return (helper.filter(data, info))
def get_chains(symbol,info=None): """Returns the chain information of an option. :param symbol: The ticker of the stock. :type symbol: str :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a dictionary of key/value pairs for the option. If info parameter is provided, \ a list of strings is returned where the strings are the value of the key that matches info. """ try: symbol = symbol.upper().strip() except AttributeError as message: print(message) return None url = urls.chains(symbol) data = helper.request_get(url) return(helper.filter(data,info))
def get_events(symbol, info=None): """Returns the events related to a stock that the user owns. For example, if you owned options for USO and that stock \ underwent a stock split resulting in you owning shares of newly created USO1, then that event will be returned when calling \ get_events('uso1') :param symbol: The stock ticker. :type symbol: str :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: [list] If the info parameter is provided, then the function will extract the value of the key \ that matches the info parameter. Otherwise, the whole dictionary is returned. :Dictionary Keys: * account * cash_component * chain_id * created_at * direction * equity_components * event_date * id * option * position * quantity * state * total_cash_amount * type * underlying_price * updated_at """ try: symbol = symbol.upper().strip() except AttributeError as message: print(message, file=helper.get_output()) return None payload = {'equity_instrument_id': helper.id_for_stock(symbol)} url = urls.events() data = helper.request_get(url, 'results', payload) return (helper.filter(data, info))
def get_instrument_by_url(url, info=None): """Takes a single url for the stock. Should be located at ``https://api.robinhood.com/instruments/<id>`` where <id> is the id of the stock. :param url: The url of the stock. Can be found in several locations including \ in the dictionary returned from get_instruments_by_symbols(inputSymbols,info=None) :type url: str :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: [dict or str] If info parameter is left as None then will return a dictionary of key/value pairs for a specific url. \ Otherwise, it will be the string value of the key that corresponds to info. :Dictionary Keys: * id * url * quote * fundamentals * splits * state * market * simple_name * name * tradeable * tradability * symbol * bloomberg_unique * margin_initial_ratio * maintenance_ratio * country * day_trade_ratio * list_date * min_tick_size * type * tradable_chain_id * rhs_tradability * fractional_tradability * default_collar_fraction """ data = helper.request_get(url, 'regular') return (helper.filter(data, info))
def get_crypto_positions(info=None): """Returns crypto positions for the account. :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: [list] Returns a list of dictionaries of key/value pairs for each option. If info parameter is provided, \ a list of strings is returned where the strings are the value of the key that matches info. :Dictionary Keys: * account_id * cost_basis * created_at * currency * id * quantity * quantity_available * quantity_held_for_buy * quantity_held_for_sell * updated_at """ url = urls.crypto_holdings() data = helper.request_get(url, 'pagination') return (helper.filter_data(data, info))
def get_events(symbol, info=None): """Returns the events related to a stock. :param symbol: The stock ticker. :type symbol: str :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: If the info parameter is provided, then the function will extract the value of the key \ that matches the info parameter. Otherwise, the whole dictionary is returned. """ try: symbol = symbol.upper().strip() except AttributeError as message: print(message) return None payload = {'equity_instrument_id': helper.id_for_stock(symbol)} url = urls.events() data = helper.request_get(url, 'results', payload) return (helper.filter(data, info))
def get_news(symbol, info=None): """Returns news stories for a stock. :param symbol: The stock ticker. :type symbol: str :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries. If info parameter is provided, \ a list of strings is returned where the strings are the value \ of the key that matches info. """ try: symbol = symbol.upper().strip() except AttributeError as message: print(message) return None url = urls.news(symbol) data = helper.request_get(url, 'results') return (helper.filter(data, info))
def get_markets(info=None): """Returns a list of available markets. :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for each market. If info parameter is provided, \ a list of strings is returned where the strings are the value of the key that matches info. :Dictionary Keys: * url * todays_hours * mic * operating_mic * acronym * name * city * country * timezone * website """ url = urls.markets() data = helper.request_get(url, 'pagination') return(helper.filter(data, info))
def get_splits(symbol, info=None): """Returns the date, divisor, and multiplier for when a stock split occureed. :param symbol: The stock ticker. :type symbol: str :param info: Will filter the results to get a specific value. Possible options are \ url, instrument, execution_date, divsor, and multiplier. :type info: Optional[str] :returns: Returns a list of dictionaries. If info parameter is provided, \ a list of strings is returned where the strings are the value \ of the key that matches info. """ try: symbol = symbol.upper().strip() except AttributeError as message: print(message) return None url = urls.splits(symbol) data = helper.request_get(url, 'results') return (helper.filter(data, info))