Skip to main content
Glama
code-rabi

Interactive Brokers MCP Server

by code-rabi

get_market_data

Retrieve real-time market data for specified symbols from Interactive Brokers to inform trading decisions and monitor financial instruments.

Instructions

Get real-time market data. Usage: { "symbol": "AAPL" } or { "symbol": "AAPL", "exchange": "NASDAQ" }.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYes
exchangeNo

Implementation Reference

  • The main tool handler function that ensures prerequisites and delegates to IBClient.getMarketData, then formats the response as MCP ToolHandlerResult.
    async getMarketData(input: GetMarketDataInput): Promise<ToolHandlerResult> {
      try {
        // Ensure Gateway is ready
        await this.ensureGatewayReady();
        
        // Ensure authentication in headless mode
        if (this.context.config.IB_HEADLESS_MODE) {
          await this.ensureAuth();
        }
        
        const result = await this.context.ibClient.getMarketData(input.symbol, input.exchange);
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: this.formatError(error),
            },
          ],
        };
      }
    }
  • Zod shape definition for get_market_data input validation used in tool registration.
    export const GetMarketDataZodShape = {
      symbol: z.string(),
      exchange: z.string().optional()
    };
  • src/tools.ts:66-71 (registration)
    MCP tool registration calling server.tool with name, description, schema, and handler.
    server.tool(
      "get_market_data",
      "Get real-time market data. Usage: `{ \"symbol\": \"AAPL\" }` or `{ \"symbol\": \"AAPL\", \"exchange\": \"NASDAQ\" }`.",
      GetMarketDataZodShape,
      async (args) => await handlers.getMarketData(args)
    );
  • Core implementation that resolves symbol to contract ID and fetches market data snapshot from IB Gateway API.
    async getMarketData(symbol: string, exchange?: string): Promise<any> {
      try {
        // First, get the contract ID for the symbol
        const searchResponse = await this.client.get(
          `/iserver/secdef/search?symbol=${symbol}`
        );
        
        if (!searchResponse.data || searchResponse.data.length === 0) {
          throw new Error(`Symbol ${symbol} not found`);
        }
    
        const contract = searchResponse.data[0];
        const conid = contract.conid;
    
        // Get market data snapshot
        // Using corrected field IDs based on IB Client Portal API documentation:
        // 31=Last Price, 70=Day High, 71=Day Low, 82=Change, 83=Change%, 
        // 84=Bid, 85=Ask Size, 86=Ask, 87=Volume, 88=Bid Size
        const response = await this.client.get(
          `/iserver/marketdata/snapshot?conids=${conid}&fields=31,70,71,82,83,84,85,86,87,88`
        );
    
        return {
          symbol: symbol,
          contract: contract,
          marketData: response.data
        };
      } catch (error) {
        Logger.error("Failed to get market data:", error);
        
        // Check if this is likely an authentication error
        if (this.isAuthenticationError(error)) {
          const authError = new Error(`Authentication required to retrieve market data for ${symbol}. Please authenticate with Interactive Brokers first.`);
          (authError as any).isAuthError = true;
          throw authError;
        }
        
        throw new Error(`Failed to retrieve market data for ${symbol}`);
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'real-time' data, which implies freshness, but doesn't cover critical aspects like rate limits, authentication requirements, error handling, or data format. For a tool with no annotations, this leaves significant gaps in understanding its operational behavior.

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

Conciseness5/5

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

The description is highly concise and front-loaded, with a clear purpose statement followed by specific usage examples. Every sentence earns its place by providing essential information without redundancy, making it easy to scan and understand quickly.

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 tool's moderate complexity (2 parameters, no output schema, no annotations), the description is adequate but incomplete. It covers basic usage and parameters but lacks details on return values, error conditions, or integration with sibling tools. This makes it minimally viable but with clear gaps for effective agent use.

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

Parameters4/5

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

The description adds meaningful context beyond the input schema, which has 0% description coverage. It clarifies that 'symbol' is required and 'exchange' is optional, and provides example usage with 'AAPL' and 'NASDAQ'. This compensates well for the schema's lack of descriptions, though it doesn't detail allowed values or constraints for the parameters.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Get real-time market data.' It specifies the verb ('Get') and resource ('real-time market data'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'get_account_info' or 'get_positions', which prevents a score of 5.

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 provides implied usage guidance through the example JSON structures, showing how to use the tool with required and optional parameters. However, it lacks explicit guidance on when to use this tool versus alternatives (e.g., when real-time data is needed vs. other market-related tools), and no exclusions or prerequisites are mentioned.

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/code-rabi/interactive-brokers-mcp'

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