### Install Robin Stocks from Source Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/install.md After cloning the repository, navigate to the directory containing setup.py and use this command to install the library. ```bash pip install . ``` -------------------------------- ### Clone and Install Robin-Stocks Locally Source: https://github.com/jmfernandes/robin_stocks/blob/master/README.rst Clone the repository and install the package locally to make changes and experiment with your own code. ```bash git clone https://github.com/jmfernandes/robin_stocks.git cd robin_stocks pip install . ``` -------------------------------- ### Get All Crypto Orders Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves all crypto orders. No setup or imports are required beyond having the robin_stocks library installed. ```python orders = rh.get_all_crypto_orders() ``` -------------------------------- ### Install Robin Stocks using Pip Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/install.md Use this command to install the Robin Stocks library globally or within a virtual environment. ```bash pip install robin_stocks ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/jmfernandes/robin_stocks/blob/master/README.rst Install pytest and pytest-dotenv for automatic testing. You will need to fill out the .test.env file. ```bash pip install pytest pip install pytest-dotenv ``` -------------------------------- ### Example API Calls Source: https://github.com/jmfernandes/robin_stocks/blob/master/README.rst Import and use functions from robin_stocks to interact with different APIs. Ensure necessary imports are made. ```python import robin_stocks.robinhood as rh import robin_stocks.gemini as gem import robin_stocks.tda as tda # Here are some example calls gem.get_pubticker("btcusd") # gets ticker information for Bitcoin from Gemini rh.get_all_open_crypto_orders() # gets all cypto orders from Robinhood tda.get_price_history("tsla") # get price history from TD Ameritrade ``` -------------------------------- ### Make Custom GET Request to Robinhood API Source: https://github.com/jmfernandes/robin_stocks/blob/master/Robinhood.rst Use `request_get` for custom GET requests to the Robinhood API. Specify the URL, response format ('regular', 'results', 'pagination', 'indexzero'), and a payload. 'pagination' is recommended for retrieving all results when data exceeds a single response. ```python >>> url = 'https://api.robinhood.com/' >>> payload = { 'key1' : 'value1', 'key2' : 'value2'} >>> r.request_get(url,'regular',payload) ``` -------------------------------- ### Place Market and Limit Orders Source: https://github.com/jmfernandes/robin_stocks/blob/master/Robinhood.rst Examples of placing market orders for stocks, limit orders for crypto, buying crypto by price, and buying option contracts. ```python #Buy 10 shares of Apple at market price r.order_buy_market('AAPL',10) ``` ```python #Sell half a Bitcoin is price reaches 10,000 r.order_sell_crypto_limit('BTC',0.5,10000) ``` ```python #Buy $500 worth of Bitcoin r.order_buy_crypto_by_price('BTC',500) ``` ```python #Buy 5 $150 May 1st, 2020 SPY puts if the price per contract is $1.00. Good until cancelled. r.order_buy_option_limit('open','debit',1.00,'SPY',5,'2020-05-01',150,'put','gtc') ``` -------------------------------- ### Get Account Information Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves specific account details or a list of all accounts. ```APIDOC ## GET /api/accounts ### Description Retrieves a list of all accounts associated with the authenticated user. ### Method GET ### Endpoint /api/accounts ### Response #### Success Response (200) - **accounts** (list) - A list of account objects, each containing details like `account_id`, `cash_balance`, and `positions`. #### Response Example ```json { "accounts": [ { "account_id": "123456789", "currentBalances": { "cashBalance": 10000.00 }, "positions": [] } ] } ``` ## GET /api/accounts/{account_id} ### Description Retrieves detailed information for a specific account. ### Method GET ### Endpoint /api/accounts/{account_id} ### Parameters #### Path Parameters - **account_id** (string) - Required - The unique identifier for the account. ### Response #### Success Response (200) - **account** (object) - An object containing detailed information about the specified account. #### Response Example ```json { "account": { "account_id": "123456789", "currentBalances": { "cashBalance": 10000.00 }, "positions": [] } } ``` ``` -------------------------------- ### Get Open Crypto Orders Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves only the open crypto orders. Ensure the robin_stocks library is imported. ```python open_orders = rh.get_all_open_crypto_orders() ``` -------------------------------- ### Get Market Hours Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves market opening and closing hours for specified markets and dates. ```APIDOC ## GET /api/marketdata/hours ### Description Retrieves market hours for specified markets on a given date. ### Method GET ### Endpoint /api/marketdata/hours ### Parameters #### Query Parameters - **market** (string) - Required - The market type (e.g., 'EQUITY', 'OPTION', 'FUTURE', 'BOND', 'FOREX'). - **date** (string) - Required - The date for which to retrieve market hours (YYYY-MM-DD). ### Response #### Success Response (200) - **hours** (object) - An object containing market hours information. #### Response Example ```json { "equity": { "EQ": { "date": "2024-01-15", "marketType": "EQUITY", "isOpen": true, "sessionHours": { "preMarket": [], "regularMarket": [ { "start": "09:30-05:00", "end": "16:00-05:00" } ], "postMarket": [] } } } } ``` ## GET /api/marketdata/hours/multiple ### Description Retrieves market hours for multiple market types on a given date. ### Method GET ### Endpoint /api/marketdata/hours/multiple ### Parameters #### Query Parameters - **markets** (string) - Required - A comma-separated string of market types (e.g., 'EQUITY,OPTION'). - **date** (string) - Required - The date for which to retrieve market hours (YYYY-MM-DD). ### Response #### Success Response (200) - **hours** (object) - An object containing market hours for each requested market type. #### Response Example ```json { "equity": { ... }, "option": { ... } } ``` ``` -------------------------------- ### Get Crypto Positions Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Returns all cryptocurrency positions currently held in the account. Includes details like available quantity and cost bases. ```python import robin_stocks.robinhood as rh # Get all crypto positions positions = rh.get_crypto_positions() # Returns: [{'currency': {'code': 'BTC', 'name': 'Bitcoin', ...}, # 'quantity_available': '0.5', 'cost_bases': [...], ...}] ``` -------------------------------- ### Get Open Option Positions Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves all currently held option positions. Can fetch specific information like quantity. ```python import robin_stocks.robinhood as rh # Get all open option positions positions = rh.get_open_option_positions() # Get specific data quantities = rh.get_open_option_positions(info="quantity") ``` -------------------------------- ### Get Option Market Data Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves market data for options including greeks, open interest, and profit probability. ```APIDOC ## Get Option Market Data ### Description Retrieves market data for options including greeks, open interest, and profit probability. ### Method GET ### Endpoint /options/market_data/ ### Parameters #### Query Parameters - **inputSymbols** (string) - Required - The stock symbol(s) to find options for. - **expirationDate** (string) - Required - The expiration date in 'YYYY-MM-DD' format. - **strikePrice** (string) - Required - The strike price to filter by. - **optionType** (string) - Required - The type of option ('call' or 'put'). ### Response #### Success Response (200) - **adjusted_mark_price** (string) - The adjusted mark price. - **bid_price** (string) - The current bid price. - **ask_price** (string) - The current ask price. - **high_price** (string) - The high price for the trading period. - **low_price** (string) - The low price for the trading period. - **volume** (integer) - The trading volume for the option. - **open_interest** (integer) - The open interest for the option. - **delta** (string) - The option's delta. - **gamma** (string) - The option's gamma. - **theta** (string) - The option's theta. - **vega** (string) - The option's vega. - **rho** (string) - The option's rho. - **implied_volatility** (string) - The implied volatility of the option. - **chance_of_profit_short** (string) - The probability of profit for a short position. - **chance_of_profit_long** (string) - The probability of profit for a long position. #### Response Example ```json [ { "adjusted_mark_price": "6.50", "bid_price": "6.45", "ask_price": "6.55", "high_price": "7.00", "low_price": "6.00", "volume": 1500, "open_interest": 25000, "delta": "0.55", "gamma": "0.03", "theta": "-0.12", "vega": "0.25", "rho": "0.05", "implied_volatility": "0.32", "chance_of_profit_short": "0.45", "chance_of_profit_long": "0.55" } ] ``` ``` -------------------------------- ### Get All Stock Orders Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Returns a list of all stock orders that have been processed for the account. Can be filtered to show only open orders. ```APIDOC ## GET /api/orders/stock ### Description Returns a list of all stock orders processed for the account. Can be filtered. ### Method GET ### Endpoint /api/orders/stock ### Parameters #### Query Parameters - **info** (string) - Optional - Specifies the type of information to retrieve (e.g., "state" to get order states). ### Request Example (Get all orders) ``` GET /api/orders/stock ``` ### Request Example (Get only open orders) ``` GET /api/orders/stock/open ``` ### Response #### Success Response (200) - A list of order objects, each containing details like: - **id** (string) - The unique identifier for the order. - **state** (string) - The current state of the order (e.g., "filled", "queued"). - **quantity** (string) - The number of shares ordered. - **price** (string) - The price of the order. - **side** (string) - The side of the order (e.g., "buy", "sell"). - **type** (string) - The type of order (e.g., "market", "limit"). - **created_at** (string) - The timestamp when the order was created. #### Response Example ```json [ { "id": "order-id-123", "state": "filled", "quantity": "5", "price": "175.50", "side": "buy", "type": "market", "created_at": "2024-01-15T10:00:00Z" } ] ``` ``` -------------------------------- ### Get Option Market Data Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves comprehensive market data for a specific option contract, including greeks, open interest, and profit probabilities. ```python import robin_stocks.robinhood as rh # Get market data for a specific option market_data = rh.get_option_market_data( inputSymbols="AAPL", expirationDate="2024-01-19", strikePrice="175.00", optionType="call" ) ``` -------------------------------- ### Get Option Chains Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Returns chain information for options on a stock, including available expiration dates and strike prices. ```APIDOC ## GET /api/options/chains ### Description Returns chain information for options on a stock, including available expiration dates and strike prices. ### Method GET ### Endpoint /api/options/chains ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock symbol for which to retrieve option chain information. - **info** (string) - Optional - Specifies the type of information to retrieve (e.g., "expiration_dates"). ### Request Example (Get chain info) ``` GET /api/options/chains?symbol=AAPL ``` ### Request Example (Get expiration dates only) ``` GET /api/options/chains?symbol=AAPL&info=expiration_dates ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the option chain. - **symbol** (string) - The stock symbol. - **can_open_position** (boolean) - Indicates if new positions can be opened for this chain. - **expiration_dates** (array) - A list of available expiration dates for the options. - **min_ticks** (object) - Minimum tick sizes for options pricing. - **above_tick** (string) - Minimum tick size above a certain price threshold. - **below_tick** (string) - Minimum tick size below a certain price threshold. #### Response Example ```json { "id": "chain-id", "symbol": "AAPL", "can_open_position": true, "expiration_dates": [ "2024-01-19", "2024-01-26" ], "min_ticks": { "above_tick": "0.05", "below_tick": "0.01" } } ``` ``` -------------------------------- ### Get Ratings Summary for a Stock Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Fetches analyst ratings for a stock, including a summary of buy, hold, and sell recommendations. Can also retrieve just the summary. ```python import robin_stocks.robinhood as rh # Get ratings summary for a stock ratings = rh.get_ratings("AAPL") ``` ```python # Get just the summary summary = rh.get_ratings("AAPL", info="summary") ``` -------------------------------- ### Get Stock Fundamentals Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves fundamental information about stocks, including financial metrics and company details. Can fetch specific data points for multiple stocks. ```python import robin_stocks.robinhood as rh # Get fundamentals for a single stock fundamentals = rh.get_fundamentals("AAPL") # Returns: [{'open': '174.50', 'high': '176.00', 'low': '174.00', 'volume': '52000000', # 'market_cap': '2800000000000', 'pe_ratio': '28.5', 'dividend_yield': '0.55', # 'sector': 'Technology', 'industry': 'Consumer Electronics', 'ceo': 'Tim Cook', # 'description': 'Apple Inc. designs, manufactures...', 'symbol': 'AAPL', ...}] # Get specific fundamental data pe_ratios = rh.get_fundamentals(["AAPL", "MSFT"], info="pe_ratio") # Returns: ['28.5', '35.2'] ``` -------------------------------- ### TD Ameritrade Get Accounts Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves account information and transactions. This example shows how to get all accounts associated with the authenticated user. ```python import robin_stocks.tda as tda # Get all accounts accounts, error = tda.get_accounts() # Returns: ([{'securitiesAccount': {'accountId': '123456789', 'type': 'MARGIN', ``` -------------------------------- ### Subsequent TD Ameritrade API Login Source: https://github.com/jmfernandes/robin_stocks/blob/master/tda.rst Execute this function at the start of your TD Ameritrade scripts after the initial `login_first_time` setup. It uses your encryption passcode to decrypt stored tokens and ensures you have a valid authorization token. ```python import robin_stocks.tda as tda tda.login("my-encryption-passcode") # make sure you have called login_first_time as some point. ``` -------------------------------- ### Prepare and Execute Sell Limit Order for Stock Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/quickstart.md This example demonstrates how to retrieve current stock positions, identify a specific stock (TSLA), calculate half the quantity to sell, and then place a limit sell order. It includes a note about the performance impact of fetching symbols individually. ```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) ``` -------------------------------- ### Place a Sell Limit Order for Stock Source: https://github.com/jmfernandes/robin_stocks/blob/master/Robinhood.rst Example of setting a limit order to sell a portion of your stock if the price reaches a specified target. This involves retrieving current positions and then creating the sell order. ```python positions_data = r.get_open_stock_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'] = r.get_symbol_by_url(item['instrument']) TSLAData = [item for item in positions_data if item['symbol'] == 'TSLA'] sellQuantity = float(TSLAData['quantity'])//2.0 r.order_sell_limit('TSLA',sellQuantity,200.00) ``` -------------------------------- ### Get Earnings Data Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves earnings data for a specified stock ticker. You can get all earnings information or specific details like EPS. ```APIDOC ## GET /earnings ### Description Retrieves earnings data for a stock. ### Method GET ### Endpoint /earnings ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock ticker symbol (e.g., "AAPL"). - **info** (string) - Optional - Specifies the type of information to retrieve (e.g., "eps"). ### Response #### Success Response (200) - Returns a list of dictionaries, where each dictionary contains earnings information for a specific period. ### Response Example ```json [ { "symbol": "AAPL", "year": 2024, "quarter": 1, "eps": { "estimate": "1.50", "actual": "1.53" }, "report": { "date": "2024-01-25", "timing": "pm" } } ] ``` ``` -------------------------------- ### Import All Robin Stocks Functions Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/quickstart.md Alternatively, import all functions directly. This method is not recommended as it can obscure the origin of functions. ```python >>> from robin_stocks import * ``` -------------------------------- ### Get Stock Quotes Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves real-time quote information for one or more stock tickers. Can filter results to get specific values like 'last_trade_price'. ```python import robin_stocks.robinhood as rh # Get quote for a single stock quotes = rh.get_quotes("AAPL") # Returns: [{'ask_price': '175.50', 'bid_price': '175.45', 'last_trade_price': '175.48', # 'symbol': 'AAPL', 'trading_halted': False, ...}] # Get quotes for multiple stocks quotes = rh.get_quotes(["AAPL", "MSFT", "GOOGL"]) # Filter results to get specific values last_prices = rh.get_quotes(["AAPL", "MSFT"], info="last_trade_price") # Returns: ['175.48', '378.92'] ``` -------------------------------- ### Custom GET Request with Payload Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/advanced.md Use `robin_stocks.request_get` to make a custom GET request to an API endpoint with a specified URL and payload. This is useful for filtering results, such as retrieving only call options. ```python >>> url = 'https://api.robinhood.com/options/instruments/' >>> payload = { 'type' : 'call'} >>> robin_stocks.request_get(url,'regular',payload) ``` -------------------------------- ### Order Buy Crypto by Price Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Submits a buy order for cryptocurrency by a specified dollar amount. Use 'gtc' for good 'til canceled time in force. ```python import robin_stocks.robinhood as rh # Buy crypto by dollar amount order = rh.order_buy_crypto_by_price( symbol="BTC", amountInDollars=100.00, # Buy $100 worth of Bitcoin timeInForce="gtc" ) # Returns: {'id': 'crypto-order-123', 'state': 'confirmed', 'quantity': '0.00235', ...} ``` -------------------------------- ### Get Stock Fundamentals Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves fundamental information about stocks. ```APIDOC ## GET /robinhood/fundamentals ### Description Retrieves fundamental information about stocks including sector, description, dividend yield, market cap, P/E ratio, and company details. ### Method GET ### Endpoint /robinhood/fundamentals ### Parameters #### Query Parameters - **symbols** (string or list of strings) - Required - One or more stock tickers (e.g., "AAPL" or ["AAPL", "MSFT"]). - **info** (string) - Optional - Specific fundamental data to retrieve (e.g., "pe_ratio"). If not provided, returns full fundamental objects. ### Response #### Success Response (200) - If 'info' is specified: A list of strings with the requested fundamental data for each symbol. - If 'info' is not specified: A list of objects, where each object contains detailed fundamental information for a symbol. #### Response Example (with info='pe_ratio') ```json [ "28.5", "35.2" ] ``` #### Response Example (without info) ```json [ { "open": "174.50", "high": "176.00", "low": "174.00", "volume": "52000000", "market_cap": "2800000000000", "pe_ratio": "28.5", "dividend_yield": "0.55", "sector": "Technology", "industry": "Consumer Electronics", "ceo": "Tim Cook", "description": "Apple Inc. designs, manufactures...", "symbol": "AAPL", ... } ] ``` ``` -------------------------------- ### Execute Crypto Buy by Price Order Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/quickstart.md Place an order to buy a specified amount of cryptocurrency by price. ```python #Buy $500 worth of Bitcoin >>> robin_stocks.order_buy_crypto_by_price('BTC',500) ``` -------------------------------- ### Login with MFA Code Programmatically Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/quickstart.md Log in to your Robinhood account using your credentials and a programmatically generated MFA code. ```python >>> import pyotp >>> import robin_stocks.robinhood as r >>> totp = pyotp.TOTP("My2factorAppHere").now() >>> login = r.login('joshsmith@email.com','password', mfa_code=totp) ``` -------------------------------- ### Get All Crypto Orders Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves all cryptocurrency orders and allows for cancellation. ```APIDOC ## GET /api/crypto/orders ### Description Retrieves all cryptocurrency orders. This endpoint can also be used to cancel orders. ### Method GET ### Endpoint /api/crypto/orders ### Response #### Success Response (200) - **orders** (array) - A list of cryptocurrency orders. - Each order object contains details such as: - **id** (string) - The unique identifier for the order. - **state** (string) - The current state of the order (e.g., 'filled', 'cancelled', 'pending'). - **side** (string) - The side of the order ('buy' or 'sell'). - **type** (string) - The type of order (e.g., 'market', 'limit'). - **symbol** (string) - The cryptocurrency symbol. - **quantity** (string) - The quantity of cryptocurrency. - **price** (string) - The price of the order (if applicable). - **created_at** (string) - The timestamp when the order was created. #### Response Example ```json { "orders": [ { "id": "crypto-order-123", "state": "filled", "side": "buy", "type": "market", "symbol": "BTC", "quantity": "0.00235", "price": null, "created_at": "2024-01-15T10:00:00Z" }, { "id": "crypto-order-104", "state": "pending_limit", "side": "sell", "type": "limit", "symbol": "BTC", "quantity": "0.01", "price": "45000.00", "created_at": "2024-01-15T11:00:00Z" } ] } ``` ``` -------------------------------- ### Get Crypto Positions Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves all cryptocurrency positions held in the account. ```APIDOC ## GET /api/crypto/positions ### Description Retrieves all cryptocurrency positions currently held in the account. ### Method GET ### Endpoint /api/crypto/positions ### Response #### Success Response (200) - **currency** (object) - Information about the cryptocurrency. - **code** (string) - The cryptocurrency code (e.g., 'BTC'). - **name** (string) - The full name of the cryptocurrency (e.g., 'Bitcoin'). - **quantity_available** (string) - The available quantity of the cryptocurrency. - **cost_bases** (array) - An array of cost basis information for the position. #### Response Example ```json [ { "currency": { "code": "BTC", "name": "Bitcoin" }, "quantity_available": "0.5", "cost_bases": [ { "lot_crerequisite": "12345", "purchase_price": "40000.00", "quantity": "0.25" } ] } ] ``` ``` -------------------------------- ### Buy Fractional Shares Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Submits an order to buy fractional shares of a stock. You can specify either the quantity of shares or the dollar amount to spend. Fractional orders typically use `gfd` (good for day) time in force. ```python import robin_stocks.robinhood as rh # Buy fractional shares by quantity order = rh.order_buy_fractional_by_quantity( symbol="AAPL", quantity=0.5, # Buy 0.5 shares timeInForce="gfd" # Good for day only for fractional ) # Buy fractional shares by dollar amount order = rh.order_buy_fractional_by_price( symbol="AAPL", amountInDollars=100.00, # Buy $100 worth of shares (minimum $1) timeInForce="gfd" ) ``` -------------------------------- ### Get Crypto Quote Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves quote information for a given cryptocurrency. ```APIDOC ## GET /api/crypto/quotes/{symbol} ### Description Retrieves quote information for a specific cryptocurrency. ### Method GET ### Endpoint /api/crypto/quotes/{symbol} ### Parameters #### Path Parameters - **symbol** (string) - Required - The cryptocurrency symbol (e.g., 'BTC'). #### Query Parameters - **info** (string) - Optional - Specific field to retrieve (e.g., 'mark_price'). If not provided, returns all quote information. ### Response #### Success Response (200) - **ask_price** (string) - The current ask price. - **bid_price** (string) - The current bid price. - **mark_price** (string) - The current mark price. - **high_price** (string) - The highest price in the current trading period. - **low_price** (string) - The lowest price in the current trading period. - **open_price** (string) - The opening price for the current trading period. #### Response Example (All Info) ```json { "ask_price": "42500.00", "bid_price": "42480.00", "mark_price": "42490.00", "high_price": "43000.00", "low_price": "42000.00", "open_price": "42200.00" } ``` #### Response Example (Specific Field) ```json { "mark_price": "42490.00" } ``` ``` -------------------------------- ### Order Buy Crypto by Quantity Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Submits a buy order for cryptocurrency by a specified quantity. Use 'gtc' for good 'til canceled time in force. ```python import robin_stocks.robinhood as rh # Buy crypto by quantity order = rh.order_buy_crypto_by_quantity( symbol="BTC", quantity=0.01, # Buy 0.01 BTC timeInForce="gtc" ) ``` -------------------------------- ### Execute Option Buy Limit Order Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/quickstart.md Place a limit order to buy an option contract. This example specifies a debit put option with a specific expiration date and strike price. ```python #Buy 5 $150 May 1st, 2020 SPY puts if the price per contract is $1.00. Good until cancelled. >>> robin_stocks.order_buy_option_limit('open','debit',1.00,'SPY',5,'2020-05-01',150,'put','gtc') ``` -------------------------------- ### Login and Authenticate with Robinhood Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Handles authentication to Robinhood, including multi-factor authentication and session persistence. Use `store_session=True` to save session details for reuse. The session expires after `expiresIn` seconds. ```python import robin_stocks.robinhood as rh # Basic login with username and password login_response = rh.login( username="your_username", password="your_password", expiresIn=86400, # Session expires in 24 hours (seconds) scope='internal', store_session=True, # Store session in pickle file for reuse mfa_code=None, # Optional MFA code pickle_path="", # Custom path for pickle file pickle_name="" ) # Returns: {'access_token': '...', 'token_type': 'Bearer', 'expires_in': 86400, ...} # Logout when done rh.logout() ``` -------------------------------- ### TD Ameritrade Get Accounts Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves account information and transaction history. ```APIDOC ## TD Ameritrade API - Get Accounts ### Description Retrieves account information and transactions. ### Method GET ### Endpoint /tda/accounts ### Parameters #### Query Parameters None ### Request Example ```python import robin_stocks.tda as tda # Get all accounts accounts, error = tda.get_accounts() ``` ### Response #### Success Response (200) - **accounts** (list) - A list of account objects, each containing details like account ID, type, and potentially transaction information. #### Response Example ```json [ { "securitiesAccount": { "accountId": "123456789", "type": "MARGIN", "..." } } ] ``` ``` -------------------------------- ### Order Buy Crypto Limit by Price Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Submits a buy order for cryptocurrency by dollar amount with a limit price. The order only executes if the market price is at or below the limit price. Use 'gtc' for time in force. ```python import robin_stocks.robinhood as rh # Buy crypto limit by dollar amount order = rh.order_buy_crypto_limit_by_price( symbol="BTC", amountInDollars=100.00, limitPrice=40000.00, timeInForce="gtc" ) ``` -------------------------------- ### Get Open Option Positions Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Returns all currently held option positions. ```APIDOC ## Get Open Option Positions ### Description Returns all currently held option positions. ### Method GET ### Endpoint /positions/options/ ### Parameters #### Query Parameters - **info** (string) - Optional - Specifies the type of information to retrieve. If not provided, returns full position details. Example: 'quantity'. ### Response #### Success Response (200) - **chain_symbol** (string) - The underlying stock symbol. - **average_price** (string) - The average price paid for the position. - **quantity** (string) - The number of contracts held. - **type** (string) - The type of option ('call' or 'put'). - **pending_buy_quantity** (string) - The quantity of buy orders pending. - **pending_sell_quantity** (string) - The quantity of sell orders pending. - **created_at** (string) - The timestamp when the position was created. #### Response Example ```json [ { "chain_symbol": "AAPL", "average_price": "650.00", "quantity": "2", "type": "call", "pending_buy_quantity": "0", "pending_sell_quantity": "0", "created_at": "2024-01-10T10:00:00Z" } ] ``` ``` -------------------------------- ### Get Latest Price Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Returns the most recent price for one or more stock tickers. ```APIDOC ## GET /robinhood/latest_price ### Description Returns the most recent price for one or more stock tickers as a simple list of price strings. ### Method GET ### Endpoint /robinhood/latest_price ### Parameters #### Query Parameters - **symbols** (string or list of strings) - Required - One or more stock tickers (e.g., "AAPL" or ["AAPL", "MSFT"]). - **priceType** (string) - Optional - The type of price to retrieve ('ask_price' or 'bid_price'). Defaults to 'last_trade_price'. - **includeExtendedHours** (boolean) - Optional - Whether to include extended hours pricing (default true). ### Response #### Success Response (200) - A list of strings, where each string is the latest price for the corresponding symbol. #### Response Example ```json [ "175.48" ] ``` ``` -------------------------------- ### Execute Market Buy Order Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/quickstart.md Place a market order to buy a specified quantity of a stock. ```python #Buy 10 shares of Apple at market price >>> robin_stocks.order_buy_market('AAPL',10) ``` -------------------------------- ### Get Orders and Cancel Order Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves order history and allows for order cancellation. ```APIDOC ## GET /api/accounts/{account_id}/orders ### Description Retrieves a list of orders for a specific account, with filtering options for time range and status. ### Method GET ### Endpoint /api/accounts/{account_id}/orders ### Parameters #### Path Parameters - **account_id** (string) - Required - The unique identifier for the account. #### Query Parameters - **max_results** (string) - Optional - Maximum number of results to return. - **from_time** (string) - Optional - Start date for filtering orders (YYYY-MM-DD). - **to_time** (string) - Optional - End date for filtering orders (YYYY-MM-DD). - **status** (string) - Optional - Filter orders by status (e.g., 'WORKING', 'FILLED', 'CANCELLED'). ### Response #### Success Response (200) - **orders** (list) - A list of order objects. #### Response Example ```json [ { "orderId": 12345, "status": "WORKING", "symbol": "AAPL", "quantity": 10, "price": 175.00 } ] ``` ## GET /api/accounts/{account_id}/orders/{order_id} ### Description Retrieves details for a specific order within an account. ### Method GET ### Endpoint /api/accounts/{account_id}/orders/{order_id} ### Parameters #### Path Parameters - **account_id** (string) - Required - The unique identifier for the account. - **order_id** (string) - Required - The unique identifier for the order. ### Response #### Success Response (200) - **order** (object) - An object containing the details of the specified order. #### Response Example ```json { "orderId": 12345, "status": "WORKING", "symbol": "AAPL", "quantity": 10, "price": 175.00 } ``` ## DELETE /api/accounts/{account_id}/orders/{order_id} ### Description Cancels a specific order for an account. ### Method DELETE ### Endpoint /api/accounts/{account_id}/orders/{order_id} ### Parameters #### Path Parameters - **account_id** (string) - Required - The unique identifier for the account. - **order_id** (string) - Required - The unique identifier for the order to be cancelled. ### Response #### Success Response (200) - **result** (object) - An object confirming the cancellation status. #### Response Example ```json { "status": "Cancelled" } ``` ``` -------------------------------- ### Order Buy Option Limit Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Submits a limit order to buy an option contract. Use 'open' for buy to open and 'debit' for buying options. ```python import robin_stocks.robinhood as rh # Buy to open a call option order = rh.order_buy_option_limit( positionEffect="open", # 'open' for buy to open, 'close' for buy to close creditOrDebit="debit", # 'debit' for buying options price=6.50, # Limit price per contract symbol="AAPL", quantity=1, # Number of contracts expirationDate="2024-01-19", strike=175.00, optionType="call", # 'call' or 'put' timeInForce="gtc" # 'gtc', 'gfd', 'ioc', 'opg' ) ``` -------------------------------- ### Get Transactions Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves transaction history for a specified account within a date range. ```APIDOC ## GET /api/accounts/{account_id}/transactions ### Description Retrieves transaction history for a specific account, with options to filter by transaction type and date range. ### Method GET ### Endpoint /api/accounts/{account_id}/transactions ### Parameters #### Path Parameters - **account_id** (string) - Required - The unique identifier for the account. #### Query Parameters - **transaction_type** (string) - Optional - Filters transactions by type (e.g., 'ALL', 'TRADE', 'DIVIDEND'). - **start_date** (string) - Optional - The start date for the transaction history (YYYY-MM-DD). - **end_date** (string) - Optional - The end date for the transaction history (YYYY-MM-DD). ### Response #### Success Response (200) - **transactions** (list) - A list of transaction objects. #### Response Example ```json [ { "transaction_id": "txn123", "type": "TRADE", "date": "2024-01-10", "symbol": "AAPL", "quantity": 10, "price": 175.00 } ] ``` ``` -------------------------------- ### Place Stop Limit Buy Order Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Use this to place a buy order that triggers a limit order once a specified stop price is reached. The order will only execute at or below the limit price. ```python import robin_stocks.robinhood as rh order = rh.order_buy_stop_limit( symbol="AAPL", quantity=5, limitPrice=182.00, # Limit price after stop is triggered stopPrice=180.00, # Triggers limit order when reached timeInForce="gtc" ) ``` -------------------------------- ### Place Order Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Submits buy or sell orders for a given account. ```APIDOC ## POST /api/accounts/{account_id}/orders ### Description Submits a new order for a specified account. Supports various order types like MARKET and LIMIT. ### Method POST ### Endpoint /api/accounts/{account_id}/orders ### Parameters #### Path Parameters - **account_id** (string) - Required - The unique identifier for the account where the order will be placed. #### Request Body - **order_payload** (object) - Required - The payload containing order details. - **orderType** (string) - Required - Type of order (e.g., 'MARKET', 'LIMIT'). - **session** (string) - Required - Session type (e.g., 'NORMAL'). - **duration** (string) - Required - Order duration (e.g., 'DAY', 'GOOD_TILL_CANCEL'). - **orderStrategyType** (string) - Required - Type of order strategy (e.g., 'SINGLE'). - **orderLegCollection** (array) - Required - Collection of order legs. - **instruction** (string) - Required - Action to perform (e.g., 'BUY', 'SELL'). - **quantity** (integer) - Required - Number of shares or contracts. - **instrument** (object) - Required - Details of the financial instrument. - **symbol** (string) - Required - The ticker symbol of the asset. - **assetType** (string) - Required - The type of asset (e.g., 'EQUITY', 'OPTION'). - **price** (string) - Optional - The limit price for LIMIT orders. ### Request Example ```json { "orderType": "MARKET", "session": "NORMAL", "duration": "DAY", "orderStrategyType": "SINGLE", "orderLegCollection": [ { "instruction": "BUY", "quantity": 10, "instrument": { "symbol": "AAPL", "assetType": "EQUITY" } } ] } ``` ### Response #### Success Response (200) - **result** (object) - An object confirming the order placement, potentially including order ID and status. #### Response Example ```json { "order_id": "98765", "status": "Submitted" } ``` ``` -------------------------------- ### TD Ameritrade Get Quote Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves real-time quote information for specified stocks. ```APIDOC ## TD Ameritrade API - Get Quote ### Description Retrieves quote information for stocks. ### Method GET ### Endpoint /tda/quote ### Parameters #### Query Parameters - **symbols** (string) - Required - Comma-separated string of stock ticker symbols (e.g., "AAPL,MSFT,GOOGL"). ### Request Example ```python import robin_stocks.tda as tda # Get quote for a single stock quote, error = tda.get_quote("AAPL") # Get quotes for multiple stocks quotes, error = tda.get_quotes("AAPL,MSFT,GOOGL") ``` ### Response #### Success Response (200) - **quotes** (dict) - A dictionary where keys are ticker symbols and values are quote objects containing bid price, ask price, last price, open price, high price, low price, and total volume. #### Response Example ```json { "AAPL": { "symbol": "AAPL", "bidPrice": 175.45, "askPrice": 175.50, "lastPrice": 175.48, "openPrice": 174.00, "highPrice": 176.00, "lowPrice": 173.50, "totalVolume": 52000000 }, "MSFT": { ... }, "GOOGL": { ... } } ``` ``` -------------------------------- ### Import Robin Stocks Library Source: https://github.com/jmfernandes/robin_stocks/blob/master/docs/source/quickstart.md Import the Robin Stocks library for use in your scripts. It's recommended to import it with the alias 'robin_stocks'. ```python >>> import robin_stocks ``` -------------------------------- ### Get Earnings Source: https://context7.com/jmfernandes/robin_stocks/llms.txt Retrieves earnings information for a stock across different financial quarters. ```APIDOC ## GET /robinhood/earnings ### Description Retrieves earnings information for a stock across different financial quarters. ### Method GET ### Endpoint /robinhood/earnings ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock ticker symbol (e.g., "AAPL"). - **year** (integer) - Optional - The year for which to retrieve earnings. Defaults to the current year. - **quarter** (integer) - Optional - The quarter for which to retrieve earnings (1, 2, 3, or 4). Defaults to all quarters if not specified. ### Response #### Success Response (200) - A list of objects, where each object contains earnings information for a specific quarter. #### Response Example ```json [ { "quarter": 1, "year": 2023, "revenue": "110000000000", "earnings": "30000000000", "eps": "1.80", "report_date": "2023-04-28" }, ... ] ``` ```