Skip to main content

RobinhoodClient

Struct RobinhoodClient 

Source
pub struct RobinhoodClient { /* private fields */ }
Expand description

Authenticated client for the Robinhood REST API.

Holds HTTP transport, authentication state, device token, and configuration. Domain-specific methods (stocks, options, orders, account) are defined in crate::endpoints as impl blocks on this type.

§Authentication

Construct with new or with_config, then call login before any endpoint method. login follows a cascade: cached token → live validation → refresh → headless OAuth. If the server requires a verification code, login returns RhoodError::ChallengeRequired so collect the code from the user and complete the flow with submit_challenge_response.

§Cloning

RobinhoodClient is cheap to clone: the HTTP transport, authentication state, device token, and configuration are all reference-counted internally. Cloning the client shares the same underlying auth state, so a refresh performed on one clone is visible on all others. The intended pattern for concurrent use is to construct a single client and clone it into each task.

§Timeouts

Every outbound call is bounded by two knobs on HttpConfig: request_timeout_secs is the total-call ceiling (headers + body) and connect_timeout_secs is the TCP connect ceiling. Defaults are 30s and 10s. A hung upstream is aborted with a timeout error rather than blocking the caller indefinitely. Override via RHOOD_HTTP_REQUEST_TIMEOUT_SECS / RHOOD_HTTP_CONNECT_TIMEOUT_SECS env vars or the corresponding CLI flags on rhood-mcp serve.

§Example

use rhood_core::RobinhoodClient;

let client = RobinhoodClient::new()?;
client.login_from_cache().await?;
let portfolio = client.get_portfolio().await?;
println!("equity: {:?}", portfolio.equity);

Implementations§

Source§

impl RobinhoodClient

Source

pub async fn login( &self, username: &str, password: &str, mfa_secret: Option<&str>, ) -> Result<()>

Unified login that cascades through all available authentication strategies.

The cascade order is:

  1. Cache - load token from disk
  2. Validate - confirm the cached token is accepted by the server
  3. Refresh - if validation fails, try refreshing the access token
  4. Headless - if refresh fails, perform a full OAuth password grant

If the headless login encounters a challenge (SMS/email), the error RhoodError::ChallengeRequired is returned with the challenge details. The caller should collect the code from the user and call submit_challenge_response() to complete authentication.

§Arguments
  • username - Robinhood account email/username
  • password - Robinhood account password
  • mfa_secret - Optional base32-encoded TOTP secret for automated MFA
§Errors

Returns RhoodError::ChallengeRequired if SMS/email verification is needed. Returns RhoodError::DeviceVerificationRequired if push verification is needed (for push challenges, the library polls automatically during login_headless). Returns cache, transport, or API errors.

In particular, an insecure token-cache file permission mode is returned so the caller can correct it before logging in again.

Source

pub async fn login_from_cache(&self) -> Result<bool>

Attempts to restore an authenticated session from the on-disk token cache.

Loads the cached token, validates it with a live API call via validate_token(), and on failure attempts to refresh it. Returns true if the client is now authenticated, false if all recovery strategies failed.

§Errors

Returns an error on I/O failures or HTTP transport errors.

Source

pub async fn validate_token(&self) -> Result<bool>

Validates the current access token by making a lightweight API call.

Returns Ok(true) if the token is accepted by the server, Ok(false) if the server returns 401 or 403 (token revoked or invalid), and Err on network/transport errors.

Uses GET /positions/?nonzero=true as the validation endpoint because it returns a small payload and is always available for authenticated users.

Source

pub async fn login_headless( &self, username: &str, password: &str, mfa_secret: Option<&str>, ) -> Result<()>

Submit the initial OAuth2 password grant. Sets auth_state based on the response (Authenticated, MfaRequired, DeviceVerification, or Challenged).

Source

pub async fn respond_to_challenge(&self, code: &str) -> Result<()>

Respond to an SMS/email challenge with the user-provided code. On success, transitions to Authenticated.

Source

pub async fn submit_challenge_response( &self, challenge_id: &str, code: &str, username: &str, password: &str, mfa_secret: Option<&str>, ) -> Result<()>

Respond to an SMS/email challenge and re-attempt login.

This is the full challenge-response flow:

  1. POSTs the user-provided code to the challenge endpoint
  2. If validated, re-attempts login with the provided credentials
  3. On success, transitions to Authenticated and caches tokens

The caller must provide the original login credentials because the challenge response only validates the device. A fresh OAuth password grant is still required to obtain tokens.

§Errors

Returns RhoodError::InvalidParameter if no challenge is pending. Returns RhoodError::Api if the challenge response is rejected. Returns any login error from the re-attempted login_headless() call.

Source§

impl RobinhoodClient

Source

pub async fn get<T: DeserializeOwned>(&self, url: &str) -> Result<T>

Sends an authenticated GET request and deserializes the JSON response.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source

pub async fn get_with_params<T: DeserializeOwned>( &self, url: &str, params: &[(&str, &str)], ) -> Result<T>

Sends an authenticated GET request with query parameters and deserializes the JSON response.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source

pub async fn get_paginated<T: DeserializeOwned>( &self, url: &str, params: &[(&str, &str)], ) -> Result<Vec<T>>

Sends an authenticated GET request and follows pagination links to collect all results into a single Vec.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source

pub async fn post_form<T: DeserializeOwned, P: Serialize + ?Sized>( &self, url: &str, payload: &P, ) -> Result<T>

Sends an authenticated POST request with a form-encoded body and deserializes the JSON response.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source

pub async fn post_json<T: DeserializeOwned, P: Serialize + ?Sized>( &self, url: &str, payload: &P, ) -> Result<T>

Sends an authenticated POST request with a JSON body and deserializes the JSON response.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source

pub async fn post_empty(&self, url: &str) -> Result<()>

Sends an authenticated POST request with an empty body.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source

pub async fn delete(&self, url: &str) -> Result<()>

Sends an authenticated DELETE request.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source

pub async fn patch_json<T: DeserializeOwned, P: Serialize + ?Sized>( &self, url: &str, payload: &P, ) -> Result<T>

Sends an authenticated PATCH request with a JSON body and deserializes the JSON response.

§Errors

Returns RhoodError::NotAuthenticated if the client is not logged in, or a transport/API error on failure.

Source§

impl RobinhoodClient

Source

pub fn new() -> Result<Self>

Creates a new client using the default configuration loaded from disk and environment variables.

§Errors

Returns an error if configuration loading or HTTP client construction fails.

Source

pub fn with_config(config: RhoodConfig) -> Result<Self>

Creates a new client with the given configuration.

Construction is a pure operation: no filesystem writes occur here. The token-cache directory is created lazily on first TokenCache::save.

§Errors

Returns an error if the HTTP client fails to build.

Source

pub fn api_url(&self, path: &str) -> String

Constructs a full URL by appending path to the configured API base URL.

Source

pub fn phoenix_url(&self, path: &str) -> String

Constructs a full URL by appending path to the configured Phoenix base URL.

Source

pub fn bonfire_url(&self, path: &str) -> String

Constructs a full URL by appending path to the configured Bonfire base URL.

Source

pub fn config(&self) -> &RhoodConfig

Returns a reference to the client’s configuration.

Source

pub async fn auth_state(&self) -> AuthState

Returns a snapshot of the current authentication state.

The state is cloned out from behind an internal read lock so the returned value is an owned snapshot; later mutations on the client will not be reflected in it.

Source

pub async fn is_authenticated(&self) -> bool

Returns true if the client holds valid authentication tokens.

Source

pub async fn logout(&self) -> Result<()>

Clears the authentication state and deletes the on-disk token cache.

§Errors

Returns an error if the token cache file cannot be deleted.

Source§

impl RobinhoodClient

Source

pub async fn get_account_summary(&self) -> Result<AccountSummary>

Fetches the unified account summary.

Returns a comprehensive snapshot including buying power, equity, cash, and margin health from the bonfire API.

§Errors

Returns RhoodError::NotAuthenticated if the account number cannot be determined. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_account_profile(&self) -> Result<AccountProfile>

Fetches the basic account profile information.

Returns details such as account number, type, and status.

§Errors

Returns RhoodError::NotAuthenticated if no account is found. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_portfolio(&self) -> Result<PortfolioProfile>

Fetches the portfolio profile containing equity, market value, and related financial summaries.

§Errors

Returns RhoodError::NotAuthenticated if no portfolio is found. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_positions(&self) -> Result<Vec<Position>>

Fetches all stock positions with a non-zero quantity.

Excludes positions that have been fully closed (quantity of zero).

Instrument URLs are resolved to ticker symbols on a best-effort basis via [enrich_position_symbols]; any failure, including a failure of the batched symbol-resolution request, is silently ignored so that the caller always receives the raw positions.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_all_positions(&self) -> Result<Vec<Position>>

Fetches all stock positions, including those with a zero quantity.

Instrument URLs are resolved to ticker symbols on a best-effort basis via [enrich_position_symbols]; any failure, including a failure of the batched symbol-resolution request, is silently ignored so that the caller always receives the raw positions.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn enrich_position_symbols( &self, positions: &mut [Position], ) -> Result<()>

Backfills symbol on each position by resolving its instrument URL to a ticker via a single batched /instruments/?ids= request. Best-effort: positions whose URL can’t be parsed or resolved are left with symbol = None.

Source§

impl RobinhoodClient

Source

pub async fn get_dividends(&self, since: Option<&str>) -> Result<Vec<Dividend>>

Fetches all dividend payments, optionally filtered by date.

When since is provided, only dividends updated on or after that date (ISO 8601 format, e.g. “2025-01-01”) are returned.

Instrument URLs are resolved to ticker symbols on a best-effort basis via enrich_dividend_symbols; any failure is silently ignored so that the caller always receives the raw dividends even when the symbol-resolution request fails.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn enrich_dividend_symbols( &self, dividends: &mut [Dividend], ) -> Result<()>

Backfills symbol on each dividend by resolving its instrument URL to a ticker via a single batched /instruments/?ids= request. Best-effort: dividends whose URL can’t be parsed or resolved are left with symbol = None.

Source

pub async fn get_total_dividends(&self) -> Result<String>

Computes the total dividend income received (paid + reinvested) as a decimal string that preserves the source amounts’ precision. Excludes voided/pending dividends.

§Errors

Returns an error if the dividend fetch fails.

Source

pub async fn get_interest_payments(&self) -> Result<Vec<InterestPayment>>

Fetches all interest/sweep payments.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source§

impl RobinhoodClient

Source

pub async fn get_documents( &self, doc_type: Option<DocumentType>, ) -> Result<Vec<Document>>

Fetches account documents, optionally filtered by type.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source§

impl RobinhoodClient

Source

pub async fn get_futures_contract( &self, symbol: &str, ) -> Result<FuturesContract>

Fetches a futures contract by its symbol (e.g., “/ESH26” or “ESH26”).

§Errors

Returns an error if the contract is not found or on HTTP failures.

Source

pub async fn cached_futures_contract( &self, symbol: &str, ) -> Result<Arc<FuturesContract>>

Cached wrapper around get_futures_contract.

Returns an Arc<FuturesContract> shared with other callers for the configured TTL. When caching is disabled (CacheConfig::enabled = false) the upstream endpoint is hit on every call.

Source

pub async fn get_futures_quote(&self, symbol: &str) -> Result<FuturesQuote>

Fetches a real-time futures quote by resolving a symbol to its instrument ID.

§Errors

Returns RhoodError::InvalidSymbol if the contract cannot be found or has no instrument ID. Also returns an error on HTTP failures.

Source

pub async fn get_futures_quotes( &self, symbols: &[&str], ) -> Result<Vec<FuturesQuote>>

Fetches real-time futures quotes for multiple symbols in a single request.

Resolves each symbol to its instrument ID concurrently via the resolver cache, then batches the quote request. Cache hits return immediately; misses fan out via futures::future::try_join_all so N upstream contract lookups run in parallel rather than sequentially.

§Errors

Returns an error if any symbol cannot be resolved or on HTTP failures.

Source

pub async fn get_futures_account_id(&self) -> Result<Option<String>>

Discovers the Robinhood futures account ID.

Queries the Ceres accounts endpoint and filters for accountType == "FUTURES". Returns None if the user has no futures account.

§Errors

Returns an error on HTTP or deserialization failures.

Source

pub async fn cached_futures_account_id(&self) -> Result<String>

Cached wrapper around get_futures_account_id.

The futures account id never changes for a given session, so it lives in a tokio::sync::OnceCell. When caching is disabled, every call hits upstream.

Unlike get_futures_account_id, this wrapper returns RhoodError::InvalidParameter rather than Ok(None) when the user has no futures account, matching the error shape existing call sites already expect.

Source

pub async fn get_all_futures_orders( &self, since: Option<&str>, ) -> Result<Vec<FuturesOrder>>

Fetches all futures orders with optional date filtering.

Discovers the futures account ID automatically. Uses cursor-based pagination to fetch all pages.

§Errors

Returns RhoodError::InvalidParameter if no futures account exists. Also returns an error on HTTP or deserialization failures.

Source§

impl RobinhoodClient

Source

pub async fn get_markets(&self) -> Result<Vec<Market>>

Fetches a list of all available markets (e.g., NYSE, NASDAQ).

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_market_hours( &self, mic: &str, date: &str, ) -> Result<MarketHours>

Fetches market hours for a specific market and date.

The mic parameter is a Market Identifier Code (e.g., "XNYS") and date is in YYYY-MM-DD format.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_market_today_hours(&self, mic: &str) -> Result<MarketHours>

Fetches today’s market hours for a market identified by its MIC code.

Resolves the market from the full market list and follows its todays_hours URL.

§Errors

Returns RhoodError::InvalidParameter if the MIC code is unknown or the market has no today’s-hours URL. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_daily_movers(&self) -> Result<Vec<WatchlistItem>>

Fetches the top 20 daily movers from Robinhood’s curated list.

Uses the /discovery/lists/items/ endpoint with Robinhood’s daily movers list ID. Returns enriched items with live price and change data.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source§

impl RobinhoodClient

Source

pub async fn get_option_chain(&self, symbol: &str) -> Result<OptionChain>

Fetches the option chain for a given stock symbol.

Resolves the symbol to its instrument and then retrieves the associated tradable chain.

§Errors

Returns RhoodError::InvalidSymbol if the symbol has no tradable option chain. Also returns an error on HTTP or deserialization failures.

Source

pub async fn find_options( &self, symbol: &str, expiration_date: &str, option_type: &str, strike_price: Option<&str>, ) -> Result<Vec<OptionInstrument>>

Searches for option contracts matching the specified criteria.

Filters by symbol, expiration date, option type ("call" or "put"), and optionally a specific strike price. Only active contracts are returned.

§Errors

Returns RhoodError::InvalidSymbol if the symbol has no tradable option chain. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_option_positions(&self) -> Result<Vec<OptionPosition>>

Fetches all option positions, including those with a zero quantity.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_open_option_positions(&self) -> Result<Vec<OptionPosition>>

Fetches only open option positions (quantity greater than zero).

§Errors

Returns an error if the underlying positions request fails.

Source

pub async fn get_option_market_data( &self, symbol: &str, contracts: &[OptionContractSpec<'_>], ) -> Result<Vec<OptionMarketData>>

Fetches live market data for specific option contracts.

Resolves each OptionContractSpec to its instrument URL via find_options, then fetches bid/ask, Greeks, volume, open interest, and probability data in a single batched request to /marketdata/options/.

§Errors

Returns RhoodError::InvalidParameter if any contract spec does not match an active option instrument. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_option_market_data_by_instrument_urls( &self, instrument_urls: &[String], ) -> Result<Vec<OptionMarketData>>

Fetches live market data for option instrument URLs.

Sends the supplied URLs directly to /marketdata/options/ without performing option-instrument discovery. Results are identified by their existing OptionMarketData::instrument field; their order is not guaranteed to match the input order.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_index_option_chain(&self, symbol: &str) -> Result<OptionChain>

Fetches the option chain for an index symbol (e.g., “SPX”).

Resolves the symbol to its index instrument, picks the first tradable_chain_ids entry, and retrieves the chain metadata.

§Errors

Returns RhoodError::InvalidSymbol if the index has no tradable option chain. Also returns an error on HTTP or deserialization failures.

Source

pub async fn find_index_options( &self, symbol: &str, expiration_date: &str, option_type: OptionType, strike_price: Option<&str>, ) -> Result<Vec<OptionInstrument>>

Searches for index option contracts matching the specified criteria.

Applies the weekly suffix mapping (e.g., SPX -> SPXW) and resolves the chain ID from the index instrument.

§Errors

Returns RhoodError::InvalidSymbol if the index has no tradable option chain. Also returns an error on HTTP or deserialization failures.

Source§

impl RobinhoodClient

Source

pub async fn get_all_stock_orders( &self, since: Option<&str>, ) -> Result<Vec<StockOrder>>

Fetches all stock orders, including completed, cancelled, and pending.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_open_stock_orders(&self) -> Result<Vec<StockOrder>>

Fetches only open (cancellable) stock orders.

Filters the full order list to those with a non-null cancel URL.

§Errors

Returns an error if the underlying orders request fails.

Source

pub async fn cancel_stock_order(&self, order_id: &str) -> Result<()>

Cancels a pending stock order by its order ID.

Requires writable mode (read_only = false).

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Also returns an error on HTTP failures.

Source

pub async fn place_stock_order( &self, req: &StockOrderRequest, ) -> Result<StockOrder>

Places a stock order (buy or sell) based on the given request parameters.

Resolves the symbol to its instrument URL and the authenticated account URL before submitting. Requires writable mode (read_only = false).

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Returns RhoodError::InvalidSymbol if the symbol cannot be resolved. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_all_option_orders( &self, since: Option<&str>, ) -> Result<Vec<OptionOrder>>

Fetches all option orders, including completed, cancelled, and pending.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_open_option_orders(&self) -> Result<Vec<OptionOrder>>

Fetches only open (cancellable) option orders.

Filters the full order list to those with a non-null cancel URL.

§Errors

Returns an error if the underlying orders request fails.

Source

pub async fn cancel_option_order(&self, order_id: &str) -> Result<()>

Cancels a pending option order by its order ID.

Requires writable mode (read_only = false).

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Also returns an error on HTTP failures.

Source

pub async fn place_option_order( &self, req: &OptionOrderRequest, ) -> Result<OptionOrder>

Places an option order based on the given request parameters.

Resolves the symbol, expiration date, strike price, and option type to a specific option contract before submitting. Requires writable mode (read_only = false).

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Returns RhoodError::InvalidSymbol if the option contract cannot be found. Also returns an error on HTTP or deserialization failures.

Source

pub async fn cancel_all_stock_orders(&self) -> Result<CancelAllOutcome>

Cancels all open (cancellable) stock orders.

Fetches open orders, then attempts to cancel each one. Requires writable mode. Returns the IDs cancelled successfully and every per-order failure. An open order without an ID is returned as a failure because it cannot be cancelled by ID.

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Returns an error if fetching the open orders fails.

Source

pub async fn cancel_all_option_orders(&self) -> Result<CancelAllOutcome>

Cancels all open (cancellable) option orders.

Fetches open orders, then attempts to cancel each one. Requires writable mode. Returns the IDs cancelled successfully and every per-order failure. An open order without an ID is returned as a failure because it cannot be cancelled by ID.

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Returns an error if fetching the open orders fails.

Source

pub async fn enrich_order_symbols( &self, orders: &mut [StockOrder], ) -> Result<()>

Fills in missing symbol fields on stock orders by resolving their instrument URLs. Caches instrument lookups so each unique URL is fetched at most once.

Orders that already have a symbol or lack an instrument URL are skipped.

Source§

impl RobinhoodClient

Source

pub async fn get_recurring_investments( &self, ) -> Result<Vec<RecurringInvestment>>

Fetches all recurring investment schedules.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn create_recurring_investment( &self, create_recurring_request: &CreateRecurringRequest, ) -> Result<RecurringInvestment>

Creates a new recurring investment schedule.

Resolves the symbol to its instrument ID and discovers the account number before submitting. Requires writable mode.

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Returns RhoodError::InvalidSymbol if the symbol cannot be resolved. Also returns an error on HTTP or deserialization failures.

Source

pub async fn update_recurring_investment( &self, schedule_id: &str, req: &UpdateRecurringRequest, ) -> Result<RecurringInvestment>

Updates an existing recurring investment schedule.

Can change amount, frequency, state (pause/resume), or start date. Requires writable mode.

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Also returns an error on HTTP or deserialization failures.

Source

pub async fn cancel_recurring_investment( &self, schedule_id: &str, ) -> Result<RecurringInvestment>

Cancels a recurring investment schedule by setting its state to “deleted”.

Requires writable mode.

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_next_investment_date( &self, frequency: RecurringFrequency, start_date: &str, ) -> Result<NextInvestmentDate>

Looks up the next scheduled investment date for a given frequency and start date.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source§

impl RobinhoodClient

Source

pub async fn resolve_instrument_id(&self, symbol: &str) -> Result<String>

Resolves a ticker symbol to its Robinhood instrument ID.

Routes through the resolver cache via cached_instrument so repeated resolutions for the same symbol within the TTL are served from memory.

§Errors

Returns RhoodError::InvalidSymbol if the symbol is not found.

Source

pub async fn get_earnings(&self, symbol: &str) -> Result<Vec<Earnings>>

Fetches earnings data for a ticker symbol.

Returns all available earnings records (historical and upcoming).

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_ratings(&self, symbol: &str) -> Result<Rating>

Fetches analyst ratings for a ticker symbol.

Requires instrument ID resolution (one extra API call).

§Errors

Returns RhoodError::InvalidSymbol if the symbol is not found. Returns an error on HTTP or deserialization failures.

Source

pub async fn get_news(&self, symbol: &str) -> Result<Vec<NewsArticle>>

Fetches recent news articles for a ticker symbol.

Returns paginated results collected into a single vector.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_splits(&self, symbol: &str) -> Result<Vec<StockSplit>>

Fetches stock split history for a ticker symbol.

Requires instrument ID resolution (one extra API call). Returns all splits collected from paginated results.

§Errors

Returns RhoodError::InvalidSymbol if the symbol is not found. Returns an error on HTTP or deserialization failures.

Source

pub async fn get_tags(&self, tag: &str) -> Result<TagResult>

Fetches instruments associated with a tag (e.g., “100-most-popular”).

Returns the tag metadata and a list of instrument URLs. Use get_instrument_by_symbol to resolve individual URLs to symbols if needed.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source§

impl RobinhoodClient

Source

pub async fn get_quotes(&self, symbols: &[&str]) -> Result<Vec<StockQuote>>

Fetches real-time stock quotes for one or more ticker symbols.

Symbols are uppercased before the request. Results are filtered to include only quotes that contain a valid symbol field.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_latest_prices( &self, symbols: &[&str], ) -> Result<Vec<(String, String)>>

Returns the latest trade price for each requested symbol.

Prefers the extended-hours trade price when available; otherwise falls back to the last regular-session trade price. Each entry in the returned vector is a (symbol, price) tuple.

§Errors

Returns an error if the underlying quote request fails.

Source

pub async fn get_fundamentals( &self, symbols: &[&str], ) -> Result<Vec<Fundamentals>>

Fetches fundamental data (market cap, P/E ratio, dividend yield, etc.) for one or more ticker symbols.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_stock_historicals( &self, symbols: &[&str], opts: &HistoricalOpts, ) -> Result<Vec<Candle>>

Fetches historical price data (OHLCV candles) for one or more symbols.

The opts parameter controls the candle interval, time span, and session bounds. Extended and trading bounds are only valid with a day span; other combinations return an error.

§Errors

Returns RhoodError::InvalidParameter if extended or trading bounds are used with a non-day span. Also returns an error on HTTP or deserialization failures.

Source

pub async fn get_instrument_by_symbol( &self, symbol: &str, ) -> Result<Option<Instrument>>

Looks up a Robinhood instrument by its ticker symbol.

Returns Ok(None) when the symbol does not match any known instrument.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn cached_instrument( &self, symbol: &str, ) -> Result<Option<Arc<Instrument>>>

Cached wrapper around get_instrument_by_symbol.

Returns an Arc<Instrument> shared with other callers requesting the same symbol during the TTL configured on the resolver cache. When caching is disabled (CacheConfig::enabled = false), every call hits upstream and nothing is inserted into the cache.

Errors are not cached: a failed lookup for one caller does not taint concurrent callers requesting the same symbol. Successful hits also populate the reverse uuid → symbol map used by resolve_symbols.

Source

pub async fn get_index_instrument( &self, symbol: &str, ) -> Result<Option<IndexInstrument>>

Looks up a Robinhood index instrument by its symbol (e.g., “SPX”).

Returns Ok(None) when the symbol does not match any known index.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn cached_index_instrument( &self, symbol: &str, ) -> Result<Option<Arc<IndexInstrument>>>

Cached wrapper around get_index_instrument.

Returns an Arc<IndexInstrument> shared with other callers during the configured TTL. Caching is skipped entirely when CacheConfig::enabled = false.

Source

pub async fn resolve_symbols( &self, ids: &[String], ) -> Result<HashMap<String, String>>

Resolves a batch of instrument UUIDs to ticker symbols.

Consults the resolver cache’s uuid → symbol map first; only uncached UUIDs are sent upstream. Misses are chunked into batches of CacheConfig::enrichment_batch_size to stay under Robinhood’s query-string limits, and each chunk is sent as a single ?ids=uuid1,uuid2,... request to /instruments/. Results are written back to the cache when enabled.

The returned map contains only UUIDs that resolve to an instrument with both an id and a symbol; any UUID whose instrument payload lacks either field is omitted from the map rather than producing an error.

§Errors

Returns an error if any chunked upstream request fails.

Source

pub async fn get_index_quote(&self, symbol: &str) -> Result<IndexQuote>

Fetches real-time market data for an index symbol.

Resolves the symbol to its index ID, then queries the index-specific market data endpoint.

§Errors

Returns RhoodError::InvalidSymbol if the index is not found. Also returns an error on HTTP or deserialization failures.

Source§

impl RobinhoodClient

Source

pub async fn get_transfers(&self) -> Result<Vec<Transfer>>

Fetches all unified transfers (ACH, wire, debit card).

Uses the Bonfire API to retrieve a consolidated view of all transfer types in a single request.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source§

impl RobinhoodClient

Source

pub async fn get_user_profile(&self) -> Result<UserProfile>

Fetches the authenticated user’s profile.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_day_trades(&self) -> Result<DayTradeCheck>

Fetches recent day trades for the user’s account.

Discovers the account number from the account endpoint, then fetches day trade data. The PDT flag is derived from the account’s margin balances.

§Errors

Returns RhoodError::NotAuthenticated if no account is found.

Source§

impl RobinhoodClient

Source

pub async fn get_watchlists(&self) -> Result<Vec<Watchlist>>

Fetches all user watchlists.

§Errors

Returns an error if the HTTP request fails or the response cannot be deserialized.

Source

pub async fn get_watchlist(&self, name_or_id: &str) -> Result<Watchlist>

Fetches a single watchlist by display name or ID.

Tries display name first (case-insensitive), then falls back to exact ID match. This allows users to look up watchlists with emoji names by ID.

§Errors

Returns RhoodError::InvalidParameter if no watchlist matches.

Source

pub async fn get_watchlist_items( &self, name_or_id: &str, ) -> Result<Vec<WatchlistItem>>

Fetches the items in a watchlist by name or ID.

Uses the /discovery/lists/items/ endpoint which returns enriched items with live market data (price, change, volume, etc.).

§Errors

Returns RhoodError::InvalidParameter if the watchlist contains only option strategies (the discovery API does not support them). Returns an error if the watchlist is not found or the items cannot be fetched.

Source

pub async fn add_to_watchlist(&self, name: &str, symbols: &[&str]) -> Result<()>

Adds symbols to a watchlist.

Resolves each symbol to its instrument ID, then adds them all in a single bulk write. Requires writable mode.

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Returns RhoodError::InvalidSymbol if any symbol cannot be resolved.

Source

pub async fn remove_from_watchlist( &self, name: &str, symbols: &[&str], ) -> Result<usize>

Removes symbols from a watchlist.

Fetches the enriched watchlist items, matches the requested symbols (case-insensitive), then removes the matches in a single bulk write. Requires writable mode.

Returns the number of symbols that were actually found and removed. Symbols not present in the watchlist are silently skipped and do not count toward the return value.

§Errors

Returns RhoodError::ReadOnlyMode if the client is in read-only mode. Returns RhoodError::InvalidParameter if the watchlist is not found or is missing an ID.

Trait Implementations§

Source§

impl Clone for RobinhoodClient

Source§

fn clone(&self) -> RobinhoodClient

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more