### Install Robin Stocks from Source Source: https://robin-stocks.readthedocs.io/en/latest/install.html After cloning the repository, navigate to the directory containing setup.py and use this command to install. ```bash $ pip install . ``` -------------------------------- ### Install Robin Stocks using Pip Source: https://robin-stocks.readthedocs.io/en/latest/install.html Use this command to install the Robin Stocks library globally or within a virtual environment. ```bash $ pip install robin_stocks ``` -------------------------------- ### Custom GET Request Example Source: https://robin-stocks.readthedocs.io/en/latest/advanced.html Demonstrates how to make a custom GET request to the option instruments API endpoint to retrieve all call options. It shows the use of `robin_stocks.request_get` with a URL, data type, and payload. ```APIDOC ## Custom GET Request Example ### Description This example shows how to make a custom GET request to the option instruments API endpoint to retrieve all call options. It utilizes the `robin_stocks.request_get` function, specifying the URL, a data type, and a payload. ### Method GET (simulated via `robin_stocks.request_get`) ### Endpoint `https://api.robinhood.com/options/instruments/` ### Parameters #### Query Parameters - **type** (string) - Optional - Specifies the type of option, e.g., 'call'. #### Request Body Not applicable for this GET request example. ### Request Example ```python url = 'https://api.robinhood.com/options/instruments/' payload = { 'type' : 'call'} robin_stocks.request_get(url,'regular',payload) ``` ### Response #### Success Response (200) The response is typically a dictionary containing 'previous', 'results', and 'next' keys. The 'results' key can contain a list or a single dictionary. #### Response Example ```json { "previous": null, "results": [], "next": null } ``` ``` -------------------------------- ### login Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/tda/authentication.html Sets the authorization token so the API can be used. Gets a new authorization token every 30 minutes using the refresh token. Gets a new refresh token every 60 days. ```APIDOC ## login(encryption_passcode) ### Description Set the authorization token so the API can be used. Gets a new authorization token every 30 minutes using the refresh token. Gets a new refresh token every 60 days. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **encryption_passcode** (str) - Encryption key created by generate_encryption_passcode(). ### Request Example ```python import robin_stocks # Assuming you have already called login_first_time and have your encryption passcode encryption_passcode = "your_encryption_passcode" try: robin_stocks.tda.authentication.login(encryption_passcode) print("Successfully logged in.") except FileExistsError as e: print(e) except ValueError as e: print(e) ``` ### Response #### Success Response (200) - None (This function updates internal state and potentially local files) #### Response Example - None ### Error Handling - **FileExistsError**: Raised if the pickle file does not exist, indicating `login_first_time()` needs to be called first. - **ValueError**: Raised if the refresh token is no longer valid, indicating `login_first_time()` needs to be called again to obtain new tokens. ``` -------------------------------- ### check_notional_balances Source: https://robin-stocks.readthedocs.io/en/latest/gemini.html Gets a list of all available balances in every currency, including notional values. ```APIDOC ## robin_stocks.gemini.account.check_notional_balances ### Description Gets a list of all available balances in every currency. ### Parameters * **jsonify** (_Optional_ _[__str_ _]_) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format. ### Returns Returns a tuple where the first entry in the tuple is a requests reponse object or a list of dictionaries parsed using the JSON format and the second entry is an error string or None if there was not an error. The keys for the dictionaries are listed below. ### Dictionary Keys * currency - The currency code. * amount - The current balance * amountNotional - Amount, in notional * available - The amount that is available to trade * availableNotional - Available, in notional * availableForWithdrawal - The amount that is available to withdraw * availableForWithdrawalNotional - AvailableForWithdrawal, in notional ``` -------------------------------- ### Custom GET Request to Option Instruments API Source: https://robin-stocks.readthedocs.io/en/latest/advanced.html Use `robin_stocks.request_get` to make a custom GET request to the option instruments API endpoint. This example retrieves all call options. ```python >>> url = 'https://api.robinhood.com/options/instruments/' >>> payload = { 'type' : 'call'} >>> robin_stocks.request_get(url,'regular',payload) ``` -------------------------------- ### Initial TDA Login Setup Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/tda/authentication.html Use this function to store your TDA API credentials securely in a local pickle file. This function should only be called once. Subsequent logins can use the `login()` function. ```python import pickle from datetime import datetime, timedelta from pathlib import Path from cryptography.fernet import Fernet from robin_stocks.tda.globals import DATA_DIR_NAME, PICKLE_NAME from robin_stocks.tda.helper import ( request_data, set_login_state, update_session ) from robin_stocks.tda.urls import URLS def login_first_time(encryption_passcode, client_id, authorization_token, refresh_token): """ Stores log in information in a pickle file on the computer. After being used once, user can call login() to automatically read in information from pickle file and refresh authorization tokens when needed. :param encryption_passcode: Encryption key created by generate_encryption_passcode(). :type encryption_passcode: str :param client_id: The Consumer Key for the API account. :type client_id: str :param authorization_token: The authorization code returned from post request to https://developer.tdameritrade.com/authentication/apis/post/token-0 :type authorization_token: str :param refresh_token: The refresh code returned from post request to https://developer.tdameritrade.com/authentication/apis/post/token-0 :type refresh_token: str """ if type(encryption_passcode) is str: encryption_passcode = encryption_passcode.encode() cipher_suite = Fernet(encryption_passcode) # Create necessary folders and paths for pickle file as defined in globals. data_dir = Path.home().joinpath(DATA_DIR_NAME) if not data_dir.exists(): data_dir.mkdir(parents=True) pickle_path = data_dir.joinpath(PICKLE_NAME) if not pickle_path.exists(): Path.touch(pickle_path) # Write information to the file. with pickle_path.open("wb") as pickle_file: pickle.dump( { 'authorization_token': cipher_suite.encrypt(authorization_token.encode()), 'refresh_token': cipher_suite.encrypt(refresh_token.encode()), 'client_id': cipher_suite.encrypt(client_id.encode()), 'authorization_timestamp': datetime.now(), 'refresh_timestamp': datetime.now() }, pickle_file) def login(encryption_passcode): """ Set the authorization token so the API can be used. Gets a new authorization token every 30 minutes using the refresh token. Gets a new refresh token every 60 days. :param encryption_passcode: Encryption key created by generate_encryption_passcode(). :type encryption_passcode: str """ if type(encryption_passcode) is str: encryption_passcode = encryption_passcode.encode() cipher_suite = Fernet(encryption_passcode) # Check that file exists before trying to read from it. data_dir = Path.home().joinpath(DATA_DIR_NAME) pickle_path = data_dir.joinpath(PICKLE_NAME) if not pickle_path.exists(): raise FileExistsError( "Please Call login_first_time() to create pickle file.") # Read the information from the pickle file. with pickle_path.open("rb") as pickle_file: pickle_data = pickle.load(pickle_file) access_token = cipher_suite.decrypt(pickle_data['authorization_token']).decode() refresh_token = cipher_suite.decrypt(pickle_data['refresh_token']).decode() client_id = cipher_suite.decrypt(pickle_data['client_id']).decode() authorization_timestamp = pickle_data['authorization_timestamp'] refresh_timestamp = pickle_data['refresh_timestamp'] # Authorization tokens expire after 30 mins. Refresh tokens expire after 90 days, # but you need to request a fresh authorization and refresh token before it expires. authorization_delta = timedelta(seconds=1800) refresh_delta = timedelta(days=60) url = URLS.oauth() # If it has been longer than 60 days. Get a new refresh and authorization token. # Else if it has been longer than 30 minutes, get only a new authorization token. if (datetime.now() - refresh_timestamp > refresh_delta): payload = { "grant_type": "refresh_token", "access_type": "offline", "refresh_token": refresh_token, "client_id": client_id } data, _ = request_data(url, payload, True) if "access_token" not in data and "refresh_token" not in data: raise ValueError( "Refresh token is no longer valid. Call login_first_time() to get a new refresh token.") access_token = data["access_token"] refresh_token = data["refresh_token"] with pickle_path.open("wb") as pickle_file: pickle.dump( { 'authorization_token': cipher_suite.encrypt(access_token.encode()), 'refresh_token': cipher_suite.encrypt(refresh_token.encode()), 'client_id': cipher_suite.encrypt(client_id.encode()), ``` -------------------------------- ### Get Transactions Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/tda/accounts.html Retrieves transaction history for a specific account. You can filter transactions by type, symbol, start date, and end date. ```APIDOC ## get_transactions ### Description Get account information for a specific account. ### Parameters #### Path Parameters - **id** (str) - Required - The account id. #### Query Parameters - **type_value** (Optional[str]) - Optional - Only transactions with the specified type will be returned. ALL, TRADE, BUY_ONLY, SELL_ONLY, CASH_IN_OR_CASH_OUT, CHECKING, DIVIDEND, INTEREST, OTHER, ADVISOR_FEES - **symbol** (Optional[str]) - Optional - Only transactions with the specified symbol will be returned. - **start_date** (Optional[str]) - Optional - Only transactions after the Start Date will be returned. Note: The maximum date range is one year. Valid ISO-8601 formats are :yyyy-MM-dd. - **end_date** (Optional[str]) - Optional - Only transactions before the End Date will be returned. Note: The maximum date range is one year. Valid ISO-8601 formats are :yyyy-MM-dd. - **jsonify** (Optional[str]) - Optional - If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format. ### Returns A tuple where the first entry is a requests response object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error. ``` -------------------------------- ### login_first_time Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/tda/authentication.html Stores login information in a pickle file on the computer. After being used once, the `login()` function can be called to automatically read in information from the pickle file and refresh authorization tokens when needed. ```APIDOC ## login_first_time(encryption_passcode, client_id, authorization_token, refresh_token) ### Description Stores login information in a pickle file on the computer. After being used once, user can call login() to automatically read in information from pickle file and refresh authorization tokens when needed. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **encryption_passcode** (str) - Encryption key created by generate_encryption_passcode(). - **client_id** (str) - The Consumer Key for the API account. - **authorization_token** (str) - The authorization code returned from post request to https://developer.tdameritrade.com/authentication/apis/post/token-0 - **refresh_token** (str) - The refresh code returned from post request to https://developer.tdameritrade.com/authentication/apis/post/token-0 ### Request Example ```python # Assuming you have obtained these values from TDAmeritrade developer portal encryption_passcode = "your_encryption_passcode" client_id = "your_client_id" authorization_token = "your_authorization_token" refresh_token = "your_refresh_token" robin_stocks.tda.authentication.login_first_time(encryption_passcode, client_id, authorization_token, refresh_token) ``` ### Response #### Success Response (200) - None (This function modifies local files) #### Response Example - None ``` -------------------------------- ### Get TDA Account Transactions Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/tda/accounts.html Retrieves transaction history for a specific TDA account. You can filter transactions by type, symbol, start date, and end date. Note that the maximum date range is one year. ```python from robin_stocks.tda.helper import format_inputs, login_required, request_get from robin_stocks.tda.urls import URLS [docs] @login_required @format_inputs def get_transactions(id, type_value=None, symbol=None, start_date=None, end_date=None, jsonify=None): """ Get account information for a specific account. :param id: The account id. :type id: str :param type_value: Only transactions with the specified type will be returned. ALL, TRADE, \n BUY_ONLY, SELL_ONLY, CASH_IN_OR_CASH_OUT, CHECKING, DIVIDEND, INTEREST, OTHER, ADVISOR_FEES :type type_value: Optional[str] param symbol: Only transactions with the specified symbol will be returned. :type symbol: Optional[str] param start_date: Only transactions after the Start Date will be returned. \n Note: The maximum date range is one year. Valid ISO-8601 formats are :yyyy-MM-dd. :type start_date: Optional[str] param end_date: Only transactions before the End Date will be returned. \n Note: The maximum date range is one year. Valid ISO-8601 formats are :yyyy-MM-dd. :type end_date: Optional[str] :param jsonify: If set to false, will return the raw response object. \n If set to True, will return a dictionary parsed using the JSON format. :type jsonify: Optional[str] :returns: Returns a tuple where the first entry in the tuple is a requests reponse object \n or a dictionary parsed using the JSON format and the second entry is an error string or \n None if there was not an error. """ url = URLS.transactions(id) payload = {} if type_value: payload["type"] = type_value if symbol: payload["symbol"] = symbol if start_date: payload["startDate"] = start_date if end_date: payload["endDate"] = end_date data, error = request_get(url, payload, jsonify) return data, error ``` -------------------------------- ### Login and Authentication Handling Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/authentication.html Handles the login process, including checking existing authentication tokens, prompting for username and password if not provided, and managing MFA or challenge responses. It updates the session with the authorization token and optionally stores the session for future use. ```python # Try to load account profile to check that authorization token is still valid. res = request_get( positions_url(), 'pagination', {'nonzero': 'true'}, jsonify_data=False) # Raises exception is response code is not 200. res.raise_for_status() return({'access_token': access_token, 'token_type': token_type, 'expires_in': expiresIn, 'scope': scope, 'detail': 'logged in using authentication in {0}'.format(creds_file), 'backup_code': None, 'refresh_token': refresh_token}) except: print( "ERROR: There was an issue loading pickle file. Authentication may be expired - logging in normally.", file=get_output()) set_login_state(False) update_session('Authorization', None) else: os.remove(pickle_path) # Try to log in normally. if not username: username = input("Robinhood username: ") payload['username'] = username if not password: password = getpass.getpass("Robinhood password: ") payload['password'] = password data = request_post(url, payload) # Handle case where mfa or challenge is required. if data: if 'mfa_required' in data: mfa_token = input("Please type in the MFA code: ") payload['mfa_code'] = mfa_token res = request_post(url, payload, jsonify_data=False) while (res.status_code != 200): mfa_token = input( "That MFA code was not correct. Please type in another MFA code: ") payload['mfa_code'] = mfa_token res = request_post(url, payload, jsonify_data=False) data = res.json() elif 'challenge' in data: challenge_id = data['challenge']['id'] sms_code = input('Enter Robinhood code for validation: ') res = respond_to_challenge(challenge_id, sms_code) while 'challenge' in res and res['challenge']['remaining_attempts'] > 0: sms_code = input('That code was not correct. {0} tries remaining. Please type in another code: '.format( res['challenge']['remaining_attempts'])) res = respond_to_challenge(challenge_id, sms_code) update_session( 'X-ROBINHOOD-CHALLENGE-RESPONSE-ID', challenge_id) data = request_post(url, payload) # Update Session data with authorization or raise exception with the information present in data. if 'access_token' in data: token = '{0} {1}'.format(data['token_type'], data['access_token']) update_session('Authorization', token) set_login_state(True) data['detail'] = "logged in with brand new authentication code." if store_session: with open(pickle_path, 'wb') as f: pickle.dump({'token_type': data['token_type'], 'access_token': data['access_token'], 'refresh_token': data['refresh_token'], 'device_token': payload['device_token']}, f) else: raise Exception(data['detail']) else: raise Exception('Error: Trouble connecting to robinhood API. Check internet connection.') return(data) ``` -------------------------------- ### Get Deposit Addresses Source: https://robin-stocks.readthedocs.io/en/latest/gemini.html Gets a list of all deposit addresses for a specified network. Optionally filters by timestamp. ```APIDOC ## GET /gemini/account/deposit_addresses ### Description Retrieves a list of deposit addresses for a given cryptocurrency network. Addresses can be filtered by creation timestamp. ### Method GET ### Endpoint /gemini/account/deposit_addresses ### Parameters #### Query Parameters - **network** (str) - Required - The cryptocurrency network (e.g., bitcoin, ethereum, bitcoincash, litecoin, zcash, filecoin). - **timestamp** (Optional[str]) - Optional - Only returns addresses created on or after this timestamp. - **jsonify** (Optional[str]) - Optional - If set to 'false', returns the raw response object. If set to 'true', returns a dictionary parsed using JSON format. ### Response #### Success Response (200) - Returns a list of dictionaries, where each dictionary contains: - **address** (str) - String representation of the deposit address. - **timestamp** (str) - Creation date of the address. - **label** (Optional[str]) - Optional label provided when creating the address. ``` -------------------------------- ### Set Up Conditional Sell Order for Stock Source: https://robin-stocks.readthedocs.io/en/latest/quickstart.html Prepare to sell a portion of your stock holdings if the price drops to a specified limit. This involves fetching current positions and then placing a limit sell order. ```python >>> positions_data = robin_stocks.get_current_positions() >>> ## Note: This for loop adds the stock ticker to every order, since Robinhood >>> ## does not provide that information in the stock orders. >>> ## This process is very slow since it is making a GET request for each order. >>> for item in positions_data: >>> item['symbol'] = robin_stocks.get_symbol_by_url(item['instrument']) >>> TSLAData = [item for item in positions_data if item['symbol'] == 'TSLA'] >>> sellQuantity = float(TSLAData['quantity'])//2.0 >>> robin_stocks.order_sell_limit('TSLA',sellQuantity,200.00) ``` -------------------------------- ### Buy Fractional Shares by Dollar Amount Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/orders.html Submits a market order for fractional shares by specifying the dollar amount. Ensures the amount meets the minimum of $1.00. Converts the dollar amount to fractional shares based on the current ask price. ```python order_buy_fractional_by_price(symbol, amountInDollars, account_number=None, timeInForce='gfd', extendedHours=False, jsonify=True, market_hours='regular_hours') ``` -------------------------------- ### Find Options by Expiration and Strike Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/options.html Fetches option orders matching specified symbols, expiration date, and strike price. Requires login. ```python @login_required def find_options_by_expiration_and_strike(inputSymbols, expirationDate, strikePrice, optionType=None, info=None): """Returns a list of all the option orders that match the seach parameters :param inputSymbols: The ticker of either a single stock or a list of stocks. :type inputSymbols: str ``` -------------------------------- ### Get Crypto Ticker Information Source: https://robin-stocks.readthedocs.io/en/latest/gemini.html Retrieves the most recent trading information for a specified cryptocurrency ticker. You can choose to get the raw response or a JSON-parsed dictionary. ```APIDOC ## GET /gemini/crypto/get_ticker ### Description Gets the recent trading information for a crypto. ### Method GET ### Endpoint /gemini/crypto/get_ticker ### Parameters #### Query Parameters - **ticker** (str) - Required - The ticker of the crypto. - **jsonify** (Optional[str]) - Optional - If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format. ### Response #### Success Response (200) Returns a tuple where the first entry is a requests response object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error. The keys for the dictionary are: - **symbol** (str) - BTCUSD etc. - **open** (float) - Open price from 24 hours ago - **high** (float) - High price from 24 hours ago - **low** (float) - Low price from 24 hours ago - **close** (float) - Close price (most recent trade) - **changes** (list) - Hourly prices descending for past 24 hours - **bid** (float) - Current best bid - **ask** (float) - Current best offer ``` -------------------------------- ### Generic GET Request Handler Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/tda/helper.html A utility function for performing HTTP GET requests. It handles URL, payload, and JSON parsing options, returning the response and any errors encountered. ```python def request_get(url, payload, parse_json): """ Generic function for sending a get request. :param url: The url to send a get request to. :type url: str :param payload: Dictionary of parameters to pass to the url. Will append the requests url as url/?key1=value1&key2=value2. :type payload: dict :param parse_json: Requests serializes data in the JSON format. Set this parameter true to parse the data to a dictionary \ using the JSON format. :type parse_json: bool :returns: Returns a tuple where the first entry is the response and the second entry will be an error message from the \ get request. If there was no error then the second entry in the tuple will be None. The first entry will either be \ the raw request response or the parsed JSON response based on whether parse_json is True or not. """ response_error = None try: response = SESSION.get(url, params=payload) response.raise_for_status() except Exception as e: response_error = e # Return either the raw request object so you can call response.text, response.status_code, response.headers, or response.json() # or return the JSON parsed information if you don't care to check the status codes. if parse_json: return response.json(), response_error else: return response, response_error ``` -------------------------------- ### Build User Profile - Robin Stocks Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/account.html Constructs a dictionary containing key account information such as total equity, extended hours equity, cash balance, and total dividends. Requires prior login. ```python from robin_stocks.robinhood.account import build_user_profile user_profile = build_user_profile() print(user_profile) ``` -------------------------------- ### Get Gemini Account Details Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/gemini/account.html Retrieves information about the profile associated with your API key. Use this to get account name, type, creation date, user details, and memo reference code. ```python from robin_stocks.gemini.authentication import generate_signature from robin_stocks.gemini.helper import ( format_inputs, login_required, request_post ) from robin_stocks.gemini.urls import URLS @login_required @format_inputs def get_account_detail(jsonify=None): """ Gets information about the profile attached to your API key. :param jsonify: If set to false, will return the raw response object. \ If set to True, will return a dictionary parsed using the JSON format. :type jsonify: Optional[str] :returns: Returns a tuple where the first entry in the tuple is a requests reponse object \ or a dictionary parsed using the JSON format and the second entry is an error string or \ None if there was not an error. \ The keys for the dictionary are listed below. :Dictionary Keys: * account - Contains information on the requested account -- accountName - The name of the account provided upon creation. Will default to Primary -- shortName - Nickname of the specific account (will take the name given, remove all symbols, replace all " " with "-" and make letters lowercase) -- type - The type of account. Will return either exchange or custody -- created - The timestamp of account creation, displayed as number of milliseconds since 1970-01-01 UTC. This will be transmitted as a JSON number * users - Contains an array of JSON objects with user information for the requested account -- name - Full legal name of the user -- lastSignIn - Timestamp of the last sign for the user. Formatted as yyyy-MM-dd'T'HH:mm:ss.SSS'Z' -- status - Returns user status. Will inform of active users or otherwise not active -- countryCode - 2 Letter country code indicating residence of user. -- isVerified - Returns verification status of user. * memo_reference_code - Returns wire memo reference code for linked bank account. """ url = URLS.account_detail() payload = { "request": URLS.get_endpoint(url) } generate_signature(payload) data, err = request_post(url, payload, jsonify) return data, err ``` -------------------------------- ### Import All Robin Stocks Functions Source: https://robin-stocks.readthedocs.io/en/latest/quickstart.html Alternatively, import all functions directly. This is not recommended as it can obscure function origins. ```python >>> from robin_stocks import * ``` -------------------------------- ### build_user_profile Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/account.html Builds a dictionary containing key user account information such as total equity, extended hours equity, cash balance, and total dividends. ```APIDOC ## build_user_profile ### Description Builds a dictionary of important information regarding the user account. ### Parameters * `account_number` (str, optional): The specific account number to retrieve data for. Defaults to None. ### Returns A dictionary containing: * `equity` (float): The total equity of the user's account. * `extended_hours_equity` (float): The extended hours equity of the user's account. * `cash` (str): The available cash balance, formatted to two decimal places. * `dividend_total` (float): The total amount of dividends received. ### Example ```python user_profile = robin_stocks.robinhood.account.build_user_profile() print(user_profile) ``` ``` -------------------------------- ### Download All Documents - Python Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/account.html Downloads all documents associated with an account and saves them as PDFs. Documents are named using their creation date, type, and ID. If a doctype is specified, only documents of that type are downloaded. Defaults to saving in 'robin_documents/'. ```python from robin_stocks import robinhood from robin_stocks.robinhood.account import download_all_documents # Download all documents download_all_documents() # Download only account statements download_all_documents(doctype='account_statement', dirpath='statements/') ``` -------------------------------- ### Generic GET Request - Gemini API Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/gemini/helper.html A generic function for performing HTTP GET requests. It handles URL, payload, and JSON parsing, returning the response and any potential errors. Use this for fetching data from the Gemini API. ```python from robin_stocks.gemini.globals import SESSION def request_get(url, payload, parse_json): """ Generic function for sending a get request. :param url: The url to send a get request to. :type url: str :param payload: Dictionary of parameters to pass to the url. Will append the requests url as url/?key1=value1&key2=value2. :type payload: dict :param parse_json: Requests serializes data in the JSON format. Set this parameter true to parse the data to a dictionary \ using the JSON format. :type parse_json: bool :returns: Returns a tuple where the first entry is the response and the second entry will be an error message from the \ get request. If there was no error then the second entry in the tuple will be None. The first entry will either be \ the raw request response or the parsed JSON response based on whether parse_json is True or not. """ response_error = None try: response = SESSION.get(url, params=payload) response.raise_for_status() except Exception as e: response_error = e # Return either the raw request object so you can call response.text, response.status_code, response.headers, or response.json() # or return the JSON parsed information if you don't care to check the status codes. if parse_json: return response.json(), response_error else: return response, response_error ``` -------------------------------- ### Clone Robin Stocks Repository Source: https://robin-stocks.readthedocs.io/en/latest/install.html Clone the Robin Stocks repository from GitHub to install the source code directly. ```bash $ git clone https://github.com/jmfernandes/robin_stocks.git ``` -------------------------------- ### Perform GET Request and Process Data Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/helper.html Handles GET requests to a given URL with optional payload and data processing. Can return raw response, JSON data, specific parts of JSON ('results', 'indexzero'), or paginated results. ```python def request_get(url, dataType='regular', payload=None, jsonify_data=True): """For a given url and payload, makes a get request and returns the data. :param url: The url to send a get request to. :type url: str :param dataType: Determines how to filter the data. 'regular' returns the unfiltered data. \ 'results' will return data['results']. 'pagination' will return data['results'] and append it with any \ data that is in data['next']. 'indexzero' will return data['results'][0]. :type dataType: Optional[str] :param payload: Dictionary of parameters to pass to the url. Will append the requests url as url/?key1=value1&key2=value2. :type payload: Optional[dict] :param jsonify_data: If this is true, will return requests.post().json(), otherwise will return response from requests.post(). :type jsonify_data: bool :returns: Returns the data from the get request. If jsonify_data=True and requests returns an http code other than <200> \ then either '[None]' or 'None' will be returned based on what the dataType parameter was set as. """ if (dataType == 'results' or dataType == 'pagination'): data = [None] else: data = None res = None if jsonify_data: try: res = SESSION.get(url, params=payload) res.raise_for_status() data = res.json() except (requests.exceptions.HTTPError, AttributeError) as message: print(message, file=get_output()) return(data) else: res = SESSION.get(url, params=payload) return(res) # Only continue to filter data if jsonify_data=True, and Session.get returned status code <200>. if (dataType == 'results'): try: data = data['results'] except KeyError as message: print("{0} is not a key in the dictionary".format(message), file=get_output()) return([None]) elif (dataType == 'pagination'): counter = 2 nextData = data try: data = data['results'] except KeyError as message: print("{0} is not a key in the dictionary".format(message), file=get_output()) return([None]) if nextData['next']: print('Found Additional pages.', file=get_output()) while nextData['next']: try: res = SESSION.get(nextData['next']) res.raise_for_status() nextData = res.json() except: print('Additional pages exist but could not be loaded.', file=get_output()) return(data) ``` -------------------------------- ### Get Option Market Data by ID Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/options.html Fetches detailed market data for a specific option contract using its ID. This includes greeks, open interest, and adjusted mark price. This function is useful for getting real-time or near-real-time data for a particular option. ```python from robin_stocks.robinhood.options import get_option_market_data_by_id # Example usage: # option_id = 'd1058013-09a2-4063-b6b0-92717e17d0c0' # Replace with a valid option ID # market_data = get_option_market_data_by_id(id=option_id) # print(market_data) ``` -------------------------------- ### Submit Fractional Sell Order by Price Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/orders.html Submits a market order for fractional shares by specifying the dollar amount. Requires a minimum of $1.00 and supports 'good for day' time in force. ```python order_sell_fractional_by_price(symbol, amountInDollars, account_number=None, timeInForce='gfd', extendedHours=False, jsonify=True) ``` -------------------------------- ### Getting Market Information Source: https://robin-stocks.readthedocs.io/en/latest/index.html Functions for retrieving general market data. ```APIDOC ## `get_all_stocks_from_market_tag()` ### Description Retrieves all stocks associated with a specific market tag. ### Method GET ### Endpoint [Endpoint path] ## `get_currency_pairs()` ### Description Retrieves available currency pairs. ### Method GET ### Endpoint [Endpoint path] ## `get_market_hours()` ### Description Retrieves the trading hours for a specific market. ### Method GET ### Endpoint [Endpoint path] ## `get_market_next_open_hours()` ### Description Retrieves the next opening hours for a market. ### Method GET ### Endpoint [Endpoint path] ## `get_market_next_open_hours_after_date()` ### Description Retrieves the next opening hours for a market after a specified date. ### Method GET ### Endpoint [Endpoint path] ## `get_market_today_hours()` ### Description Retrieves the trading hours for the current day for a market. ### Method GET ### Endpoint [Endpoint path] ## `get_markets()` ### Description Retrieves a list of all available markets. ### Method GET ### Endpoint [Endpoint path] ## `get_top_100()` ### Description Retrieves the top 100 stocks by market capitalization. ### Method GET ### Endpoint [Endpoint path] ## `get_top_movers()` ### Description Retrieves the top moving stocks in the market. ### Method GET ### Endpoint [Endpoint path] ## `get_top_movers_sp500()` ### Description Retrieves the top moving stocks in the S&P 500. ### Method GET ### Endpoint [Endpoint path] ``` -------------------------------- ### Get All Stock Orders Source: https://robin-stocks.readthedocs.io/en/latest/robinhood.html Retrieves a list of all stock orders processed for the account. ```APIDOC ## get_all_stock_orders ### Description Returns a list of all the orders that have been processed for the account. ### Parameters #### Query Parameters - **info** (Optional[str]) - Will filter the results to get a specific value. ### Returns Returns a list of dictionaries of key/value pairs for each order. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. ``` -------------------------------- ### build_user_profile() Source: https://robin-stocks.readthedocs.io/en/latest/genindex.html Builds the user profile. ```APIDOC ## build_user_profile() ### Description Builds the user profile. ### Module robin_stocks.robinhood.account ``` -------------------------------- ### Get All Option Orders Source: https://robin-stocks.readthedocs.io/en/latest/robinhood.html Retrieves a list of all option orders processed for the account. ```APIDOC ## get_all_option_orders ### Description Returns a list of all the option orders that have been processed for the account. ### Parameters #### Query Parameters - **info** (Optional[str]) - Will filter the results to get a specific value. ### Returns Returns a list of dictionaries of key/value pairs for each option order. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. ``` -------------------------------- ### Download a Single Document - Python Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/account.html Downloads a specified document from a URL and saves it as a PDF. If no name is provided, it uses the document's name from the URL. If no directory is specified, it saves to 'robin_documents/'. ```python from robin_stocks import robinhood from robin_stocks.custom_orders import get_orders from robin_stocks.robinhood.account import download_document # Example usage: # Assuming you have a document URL from get_documents(info='download_url') doc_url = 'YOUR_DOCUMENT_URL_HERE' download_document(doc_url, name='my_document', dirpath='/path/to/save') ``` -------------------------------- ### Get All Crypto Orders Source: https://robin-stocks.readthedocs.io/en/latest/robinhood.html Retrieves a list of all crypto orders processed for the account. ```APIDOC ## get_all_crypto_orders ### Description Returns a list of all the crypto orders that have been processed for the account. ### Parameters #### Query Parameters - **info** (Optional[str]) - Will filter the results to get a specific value. ### Returns Returns a list of dictionaries of key/value pairs for each option order. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. ``` -------------------------------- ### Buy Crypto by Price Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/orders.html Submits a market order for cryptocurrency by specifying the dollar amount to trade. Supports fractional shares up to 8 decimal places. ```python order_buy_crypto_by_price(symbol, amountInDollars, timeInForce='gtc', jsonify=True) ``` -------------------------------- ### check_available_balances Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/gemini/account.html Fetches a list of all available balances across all currencies. It provides details on the total amount, available amount for trading, and available amount for withdrawal for each currency. ```APIDOC ## check_available_balances ### Description Gets a list of all available balances in every currency. ### Parameters * `jsonify` (Optional[str]): If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format. ### Returns Returns a tuple where the first entry is a requests response object or a list of dictionaries parsed using the JSON format and the second entry is an error string or None if there was not an error. ### Dictionary Keys: * `currency` - The currency code. * `amount` - The current balance * `available` - The amount that is available to trade * `availableForWithdrawal` - The amount that is available to withdraw * `type` - "exchange" ``` -------------------------------- ### Get Latest Notification Source: https://robin-stocks.readthedocs.io/en/latest/robinhood.html Retrieves the timestamp of the latest notification received by the account. ```APIDOC ## GET /account/latest_notification ### Description Returns the time of the latest notification. ### Response #### Success Response (200) - Returns a dictionary of key/value pairs. But there is only one key, ‘last_viewed_at’. ``` -------------------------------- ### Get Order Source: https://robin-stocks.readthedocs.io/en/latest/tda.html Retrieves information for a specific order within a given account. ```APIDOC ## get_order ### Description Gets information for an order for a given account. ### Parameters #### Path Parameters - **account_id** (str) - The account id. - **order_id** (str) - The order id. - **jsonify** (Optional[str]) - If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format. ### Returns Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error. ``` -------------------------------- ### Import Robin Stocks Library Source: https://robin-stocks.readthedocs.io/en/latest/quickstart.html Import the Robin Stocks library. It is recommended to import it with an alias for easier use. ```python >>> import robin_stocks ``` -------------------------------- ### get_all_positions() Source: https://robin-stocks.readthedocs.io/en/latest/genindex.html Retrieves all positions. (in module robin_stocks.robinhood.account) ```APIDOC ## get_all_positions() ### Description Retrieves all positions. ### Module robin_stocks.robinhood.account ``` -------------------------------- ### search_instruments Source: https://robin-stocks.readthedocs.io/en/latest/tda.html Gets a list of all the instruments data for tickers that match a search string. ```APIDOC ## search_instruments ### Description Gets a list of all the instruments data for tickers that match a search string. ### Parameters #### Path Parameters - **ticker_string** (str) - Required - Value to pass to the search. See projection description for more information. - **projection** (str) - Required - The type of request: * symbol-search: Retrieve instrument data of a specific symbol or cusip * symbol-regex: Retrieve instrument data for all symbols matching regex. Example: symbol=XYZ.* will return all symbols beginning with XYZ * desc-search: Retrieve instrument data for instruments whose description contains the word supplied. Example: symbol=FakeCompany will return all instruments with FakeCompany in the description. * desc-regex: Search description with full regex support. Example: symbol=XYZ.[A-C] returns all instruments whose descriptions contain a word beginning with XYZ followed by a character A through C. * fundamental: Returns fundamental data for a single instrument specified by exact symbol. #### Query Parameters - **jsonify** (Optional[str]) - If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format. ### Returns Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error. ``` -------------------------------- ### get_referrals Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/account.html Retrieves a list of referrals. Can filter results to get a specific value. ```APIDOC ## get_referrals ### Description Returns a list of referrals. Can filter results to get a specific value. ### Parameters #### Query Parameters - **info** (Optional[str]) - Optional - Will filter the results to get a specific value. ### Returns Returns a list of dictionaries of key/value pairs for each referral. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. ``` -------------------------------- ### robin_stocks.robinhood.account.build_user_profile Source: https://robin-stocks.readthedocs.io/en/latest/robinhood.html Builds a dictionary of important information regarding the user account. ```APIDOC ## build_user_profile ### Description Builds a dictionary of important information regarding the user account. ### Parameters #### Query Parameters - **account_number** (str) - Optional - The account number. ### Returns Returns a dictionary that has total equity, extended hours equity, cash, and dividend total. ``` -------------------------------- ### Submit Fractional Sell Order by Quantity Source: https://robin-stocks.readthedocs.io/en/latest/_modules/robin_stocks/robinhood/orders.html Submits a market order for fractional shares by specifying the quantity. Supports up to 6 decimal places and 'good for day' time in force. ```python order_sell_fractional_by_quantity(symbol, quantity, account_number=None, timeInForce='gfd', priceType='bid_price', extendedHours=False, jsonify=True, market_hours='regular_hours') ``` -------------------------------- ### Get All Open Crypto Orders Source: https://robin-stocks.readthedocs.io/en/latest/robinhood.html Retrieves a list of all crypto orders that are currently open. ```APIDOC ## get_all_open_crypto_orders ### Description Returns a list of all the crypto orders that have been processed for the account. ### Parameters #### Query Parameters - **info** (Optional[str]) - Will filter the results to get a specific value. ### Returns Returns a list of dictionaries of key/value pairs for each option order. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. ``` -------------------------------- ### Get Total Dividends Source: https://robin-stocks.readthedocs.io/en/latest/robinhood.html Returns the total amount of dividends paid to the account as a float. ```APIDOC ## robin_stocks.robinhood.account.get_total_dividends ### Description Returns a float number representing the total amount of dividends paid to the account. ### Returns Total dollar amount of dividends paid to the account as a 2 precision float. ```