Skip to main content
Glama
drasticstatic

robinhood-mcp

robinhood_get_position

Retrieve a single current stock position from your Robinhood portfolio by providing the ticker symbol. Useful for quick portfolio checks and analysis.

Instructions

Get one current stock position with a faster single-symbol lookup.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesStock ticker symbol (e.g., "HIMS", "AAPL")

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function `get_position()` that executes the single-symbol position lookup logic. It normalizes the symbol, checks cache first, validates the instrument via Robinhood API, fetches open stock positions, matches by instrument URL, computes P&L from the quote, and returns a payload with held/price/quantity/equity/change fields.
    def get_position(symbol: str) -> dict[str, Any]:
        """Get a single position by symbol without rebuilding all holdings.
    
        Returns:
            Dict with held=False if absent, otherwise position details including
            price, quantity, average_buy_price, equity, percent_change, and equity_change.
        """
        symbol = _normalize_symbol(symbol)
        cached_positions = _get_positions_cached(time.monotonic())
        if cached_positions is not None:
            cached_position = cached_positions.get(symbol)
            if isinstance(cached_position, dict):
                return _position_payload(symbol, cached_position)
            _validate_symbol_instrument(symbol)
            return {"symbol": symbol, "held": False}
    
        instrument_url = _validate_symbol_instrument(symbol)
    
        positions = _safe_call(rh.account.get_open_stock_positions)
        if not isinstance(positions, list):
            raise RobinhoodError("Unexpected positions response type")
    
        match = next(
            (
                item
                for item in positions
                if isinstance(item, dict) and item.get("instrument") == instrument_url
            ),
            None,
        )
        if not match:
            return {"symbol": symbol, "held": False}
    
        quote = get_quote(symbol)
        price = quote.get("last_trade_price") or quote.get("mark_price")
        quantity = match.get("quantity")
        average_buy_price = match.get("average_buy_price")
        if price in (None, "") or quantity in (None, "") or average_buy_price in (None, ""):
            raise RobinhoodError(f"Incomplete position data for symbol: {symbol}")
    
        try:
            quantity_f = float(quantity)
            price_f = float(price)
            average_buy_price_f = float(average_buy_price)
        except (TypeError, ValueError) as e:
            raise RobinhoodError(f"Invalid numeric position data for symbol: {symbol}") from e
    
        equity = quantity_f * price_f
        equity_change = equity - (quantity_f * average_buy_price_f)
        percent_change = (
            0.0
            if average_buy_price_f == 0.0
            else ((price_f - average_buy_price_f) * 100 / average_buy_price_f)
        )
        return _position_payload(
            symbol,
            {
                "price": f"{price_f:.2f}",
                "quantity": quantity,
                "average_buy_price": average_buy_price,
                "equity": f"{equity:.2f}",
                "percent_change": f"{percent_change:.2f}",
                "equity_change": f"{equity_change:.2f}",
            },
        )
  • The MCP-tool-annotated function `robinhood_get_position` registered as an MCP tool. It calls `_ensure_logged_in()` then delegates to the `get_position(symbol)` from tools.py.
    @mcp.tool()
    def robinhood_get_position(symbol: str) -> dict:
        """Get one current stock position with a faster single-symbol lookup.
    
        Args:
            symbol: Stock ticker symbol (e.g., "HIMS", "AAPL")
    
        Returns a dict with held=False if absent, otherwise the position details
        for that symbol including quantity, price, average buy price, and P&L.
        """
        _ensure_logged_in()
        return get_position(symbol)
  • The @mcp.tool() decorator on line 99 registers `robinhood_get_position` as a tool named 'robinhood_get_position' in the FastMCP server.
    @mcp.tool()
    def robinhood_get_position(symbol: str) -> dict:
        """Get one current stock position with a faster single-symbol lookup.
    
        Args:
            symbol: Stock ticker symbol (e.g., "HIMS", "AAPL")
    
        Returns a dict with held=False if absent, otherwise the position details
        for that symbol including quantity, price, average buy price, and P&L.
        """
        _ensure_logged_in()
        return get_position(symbol)
  • The tool schema includes a single parameter `symbol: str` (line 122) as defined in the function signature. The docstring describes input (stock ticker) and output (dict with held flag and position details).
    @mcp.tool()
    def robinhood_get_position(symbol: str) -> dict:
        """Get one current stock position with a faster single-symbol lookup.
    
        Args:
            symbol: Stock ticker symbol (e.g., "HIMS", "AAPL")
    
        Returns a dict with held=False if absent, otherwise the position details
        for that symbol including quantity, price, average buy price, and P&L.
        """
        _ensure_logged_in()
        return get_position(symbol)
  • Helper function `_normalize_symbol` used by `get_position` to validate and normalize the ticker symbol (uppercase, strip whitespace, non-empty check).
    def _normalize_symbol(symbol: str) -> str:
        """Normalize and validate ticker symbols."""
        if not symbol or not isinstance(symbol, str):
            raise RobinhoodError("Symbol must be a non-empty string")
        symbol = symbol.upper().strip()
        if not symbol:
            raise RobinhoodError("Symbol must be a non-empty string")
        return symbol
  • Helper function `_validate_symbol_instrument` used by `get_position` to resolve a symbol to its instrument URL via Robinhood API. Used to match positions and detect unknown tickers.
    def _validate_symbol_instrument(symbol: str) -> str:
        """Resolve a symbol to its instrument URL, raising on unknown tickers."""
        instruments = _safe_call(rh.stocks.get_instruments_by_symbols, symbol)
        if (
            not isinstance(instruments, list)
            or not instruments
            or not isinstance(instruments[0], dict)
            or not instruments[0].get("url")
        ):
            raise RobinhoodError(f"No instrument found for symbol: {symbol}")
        return instruments[0]["url"]
  • Helper function `_position_payload` used by `get_position` to build a stable position response dict with a fixed set of fields (price, quantity, average_buy_price, equity, percent_change, equity_change).
    def _position_payload(symbol: str, data: dict[str, Any]) -> dict[str, Any]:
        """Build a stable position response with a fixed set of fields."""
        fields = {k: data.get(k) for k in _POSITION_FIELDS}
        held = all(v not in (None, "") for v in fields.values())
        return {"symbol": symbol, "held": held, **fields}
  • Helper constant `_POSITION_FIELDS` tuple defining the set of fields extracted for a position response.
    _POSITION_FIELDS = (
        "price",
        "quantity",
        "average_buy_price",
        "equity",
        "percent_change",
        "equity_change",
    )
  • Helper function `_get_positions_cached` used by `get_position` to retrieve cached holdings snapshot when fresh (within 30s TTL).
    def _get_positions_cached(now: float) -> dict[str, dict[str, Any]] | None:
        """Return cached holdings when still fresh."""
        global _positions_cache, _positions_cache_ts
    
        with _positions_cache_lock:
            if _positions_cache is None:
                return None
            if (now - _positions_cache_ts) >= _POSITIONS_CACHE_TTL_SECONDS:
                _positions_cache = None
                _positions_cache_ts = 0.0
                return None
            return deepcopy(_positions_cache)
    
    
    def _set_positions_cache(positions: dict[str, dict[str, Any]], now: float) -> None:
        """Store a fresh holdings snapshot for subsequent reads."""
        global _positions_cache, _positions_cache_ts
    
        with _positions_cache_lock:
            _positions_cache = deepcopy(positions)
            _positions_cache_ts = now
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description does not disclose behavioral traits such as idempotency, error handling, authentication needs, or what 'current' means. The output schema may cover return format, but safety and side effects are unaddressed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single concise sentence, but it could benefit from minor restructuring (e.g., front-loading the purpose and adding a brief usage note). It is efficient but slightly under-specified.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the presence of an output schema and one simple parameter, the description is minimally adequate. However, it omits context on when the 'faster' lookup applies and how it differs from the plural variant, leaving some gaps for an AI agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage for the 'symbol' parameter with examples. The description adds no extra meaning beyond the schema, earning a baseline score of 3.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'Get', the resource 'one current stock position', and highlights 'faster single-symbol lookup', effectively distinguishing it from the sibling tool 'robinhood_get_positions' which retrieves multiple positions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies use for a single symbol lookup with speed advantage but lacks explicit guidance on when not to use or direct comparison to alternatives like 'robinhood_get_positions'.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/drasticstatic/robinhood-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server