Skip to main content
Glama
Trading MCP Server

Trading MCP Server

by VaishnaviK23

Trading-MCP-Server

An intelligent trading assistant that integrates with the Claude AI MCP (Model Context Protocol) platform. This tool fetches live stock prices using Yahoo Finance and enables seamless command-based interaction with the market via Claude's agent interface.

πŸš€ Features

  • πŸ”„ Fetches real-time (or near real-time) stock prices using Yahoo Finance

  • πŸ€– Connects to Claude MCP as a server with custom trading commands

  • πŸ›  Built using Python with support for virtual environments and uv for dependency management

  • βš™οΈ Supports modular expansion to include trading signals, historical analysis, and more

Related MCP server: Yahoo Finance MCP Server

🧠 Architecture

  • Claude AI MCP Integration: Uses mcp[cli] to expose a server interface to Claude.

  • Yahoo Finance API: For retrieving stock data (via yfinance).

  • Virtual Environment: Managed using uv for fast and deterministic builds.

πŸ“¦ Setup

# Install uv if not already installed
brew install uv

# Navigate to the project directory
cd MCPtrading

# Install dependencies
uv pip install -r requirements.txt

# (Optional) Add packages
uv add yfinance

πŸƒβ€β™€οΈ Running the Server

Make sure to use the correct Python environment:

uv run --python .venv/bin/python --with "mcp[cli]" mcp run trader_tools.py

Or update your Claude config:

{
  "mcpServers": {
    "Trading": {
      "command": "/Users/yourname/.local/bin/uv",
      "args": [
        "run",
        "--python",
        "/full/path/to/.venv/bin/python",
        "--with",
        "mcp[cli]",
        "mcp",
        "run",
        "trader_tools.py"
      ]
    }
  }
}

πŸ§ͺ Example Usage

Ask Claude:

"What's the latest price of AAPL?"

Claude will call the MCP server and respond with the current stock price.

Available Tools

8 tools
current_priceA

Fetch the live price of a stock symbol.

Args: symbol: Stock ticker symbol (e.g. AAPL, TSLA) - This should be a valid symbol supported by Yahoo Finance.

Returns: The current market price as a float, or -1.0 if the price could not be fetched.

Example: get_live_price("AAPL") -> 193.45

Inputs: symbol (required). Returns: result

pnlA

Generate a Profit & Loss (P&L) summary.

Combines realized and unrealized gains into a single financial overview.

Returns: A dictionary with keys 'realized' and 'unrealized' representing the total gains.

Example: pnl() -> {"realized": 320.75, "unrealized": 145.60}

Inputs: no named parameters. Returns: object

portfolioA

Show current portfolio holdings.

This tool calculates the net number of shares held for each stock symbol by summing all buy and sell trades in the trade history CSV.

Returns: A dictionary mapping stock symbols to their current number of held shares. Only symbols with a positive balance are included.

Example: portfolio() -> {"AAPL": 120, "GOOG": 60}

Inputs: no named parameters. Returns: object

realized_gainsA

Calculate total realized gains using FIFO method.

This tool goes through the trade history and tracks all buy transactions in a FIFO queue. For each sell, it matches shares with the earliest buys and calculates the realized profit or loss accordingly.

Returns: A float representing the total realized gain or loss (in dollars), rounded to two decimal places.

Example: realized_gains() -> 352.75

Inputs: no named parameters. Returns: result

simulate_sellA

Simulate selling a number of shares of a stock and estimate the profit or loss.

Args: symbol: The stock ticker symbol to simulate the sale for (e.g., TSLA) shares: The number of shares to simulate selling.

Returns: The estimated profit/loss from the simulated sale using FIFO matching, in dollars.

Example: simulate_sell("AAPL", 50) -> 123.45

Inputs: symbol (required), shares (required). Returns: result

trade_historyA

Return the trade history for a specific stock symbol.

Args: symbol: The stock ticker symbol (e.g., AMZN, MSFT)

Returns: A list of dictionaries containing all trade records for that symbol.

Example: trade_history("GOOG") -> [{"date": "2024-01-01", "type": "Buy", ...}, ...]

Inputs: symbol (required). Returns: result

unrealized_gainsA

Calculate unrealized gains for current holdings.

This tool calculates unrealized profit or loss by comparing the average buy price for currently held shares against the current market price fetched live using yfinance.

Returns: A dictionary mapping each stock symbol to its unrealized gain or loss in dollars.

Example: unrealized_gains() -> {"AAPL": 125.50, "GOOG": -22.15}

Inputs: no named parameters. Returns: object

validate_tradesA

Validate that no trades sell more shares than have been bought.

Parses the trade history sequentially to ensure all sell transactions occur only after a corresponding quantity of shares has been bought.

Returns: A list of error messages for invalid trades, if any.

Example: validate_trades() -> ["Invalid sell on 2024-02-10: 20 shares of AAPL (owned: 10)"]

Inputs: no named parameters. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 8 tools

    Disambiguation4/5

    Most tools have distinct purposes, but there is some overlap between 'pnl', 'realized_gains', and 'unrealized_gains' that could cause confusion. 'pnl' combines both realized and unrealized gains, while the other two provide separate calculations, which might lead an agent to misselect when seeking specific details.

    Naming Consistency3/5

    The naming is mixed with snake_case used throughout, but the verb patterns vary: some are nouns (e.g., 'portfolio', 'pnl'), some are verbs (e.g., 'simulate_sell', 'validate_trades'), and some are descriptive phrases (e.g., 'trade_history', 'unrealized_gains'). This inconsistency reduces predictability, though it remains readable.

    Tool Count5/5

    With 8 tools, the count is well-scoped for a trading server, covering key operations like price fetching, portfolio management, gain calculations, and trade validation. Each tool serves a clear purpose without being overwhelming or insufficient for the domain.

    Completeness4/5

    The tool set covers core trading functions such as price lookup, portfolio tracking, and gain analysis, but lacks tools for executing trades or managing orders, which are typical in trading systems. This minor gap might require agents to work around, but the existing tools support essential workflows.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables LLMs to retrieve stock market data and financial information from Yahoo Finance using the yfinance Python library. Supports querying stock prices, historical data, and other financial metrics through natural language.
      MIT
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Integrates Yahoo Finance data with Claude to provide real-time and historical financial information, including stock prices, financial statements, and options data. It enables comprehensive market research and investment analysis through natural language interactions.
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Provides real-time stock quotes, market indices, historical data, and financial visualizations from Yahoo Finance without API keys, enabling users to analyze and visualize market data through Claude.
      3
      1
      MIT