DEV Community

Phi Thành
Phi Thành

Posted on

Build an AI Trading Agent with a Market Data MCP Server

Writing custom tool definitions for every financial endpoint burns engineering hours and breaks whenever an upstream payload structure shifts. Connecting an LLM directly to a dedicated market data MCP server lets your autonomous agents pull real-time quotes, multi-timeframe candles, and technical indicators without custom wrapper scripts. In this guide, you will configure an MCP client to stream live market data for EURUSD, XAUUSD, and AAPL directly into agent execution loops.

TL;DR: The hosted endpoint at https://ai.realmarketapi.com/mcp provides 33 pre-built tools covering live prices, indicators, and market intelligence over the Model Context Protocol. MCP support is available on Pro ($34.99/mo) and Business ($74.99/mo) tiers on RealMarketAPI. If you are building on the Free or Starter tiers, use the REST endpoints directly instead of the MCP interface.

Why AI Agents Need Direct MCP Market Data Access

Large language models cannot observe live financial markets on their own. Their internal weights freeze at their training cutoff, while spot forex, equity order books, and crypto tokens fluctuate every second. When engineers build autonomous market research agents, trading bots, or execution assistants, they traditionally write bespoke tool plumbing:

  1. Define custom JSON Schema tool definitions for each financial endpoint.
  2. Parse incoming tool calls from model completions.
  3. Make network calls to upstream market data APIs.
  4. Clean and format the raw response into text strings.
  5. Append the formatted results back into the model's message history.

Maintaining this glue code across dozens of endpoints becomes tedious. Any change in parameter typing or response formatting breaks the agent loop. The Model Context Protocol (MCP) solves this problem by standardizing how client runtimes discover and call tools on external servers. Instead of maintaining boilerplate schemas in your application code, an MCP-compatible client queries the remote server, receives registered tool definitions, and routes execution calls over standard transports like Server-Sent Events (SSE).

Connecting an AI agent to a specialized market data MCP server exposes structured financial primitives immediately. If an agent needs to evaluate whether gold (XAUUSD) is oversold on a 1-hour chart or retrieve the latest bid/ask spread for EURUSD, it invokes the remote server's pre-built tools. The server handles validation, queries upstream institutional sources such as Binance, OKX, Coinbase, Exness, IG Group, OANDA, and Vantage, and returns clean, uniform payloads back to the model.

Adding the MCP Server to Claude Desktop or Your Agent

The hosted MCP server endpoint runs at https://ai.realmarketapi.com/mcp. It communicates using Server-Sent Events (SSE) over HTTP. Authentication requires an active API key passed as the apiKey query parameter directly in the connection URL.

MCP features are reserved for Pro ($34.99/mo, 200,000 requests/month) and Business ($74.99/mo, 1,000,000 requests/month) subscribers. If you pass an API key from a Free or Starter tier, the server rejects the handshake because those tiers do not include MCP access.

Configuring Claude Desktop

Claude Desktop can act as an MCP host application. To connect Claude Desktop to the remote financial server, update your local configuration file. On macOS, open ~/Library/Application Support/Claude/claude_desktop_config.json. On Windows, open %APPDATA%\Claude\claude_desktop_config.json.

Add the remote server using mcp-remote to establish the SSE bridge, replacing YOUR_API_KEY with your actual token:

{
  "mcpServers": {
    "realmarketapi": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://ai.realmarketapi.com/mcp?apiKey=YOUR_API_KEY"
      ]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Restart Claude Desktop. The application initiates a connection to the server, runs the tools/list handshake, and exposes 33 financial tools inside the chat interface. You can verify the connection by asking Claude: "What tools do you have for checking gold prices and technical indicators?"

Connecting with Python Using the Official MCP SDK

If you are building an autonomous agent runtime in Python rather than using a desktop GUI, connect directly with the official mcp library. The script below initializes an SSE client session, performs the protocol handshake, and prints every tool registered on the server:

import asyncio
from mcp import ClientSession
from mcp.client.sse import sse_client

API_KEY = "YOUR_API_KEY"
MCP_URL = f"https://ai.realmarketapi.com/mcp?apiKey={API_KEY}"

async def inspect_mcp_tools():
    async with sse_client(MCP_URL) as (read_stream, write_stream):
        async with ClientSession(read_stream, write_stream) as session:
            # Complete protocol initialization
            await session.initialize()

            # Fetch all registered tools
            response = await session.list_tools()
            print(f"Connected successfully. Registered tools: {len(response.tools)}\n")

            for tool in response.tools:
                print(f"Tool: {tool.name}")
                print(f"Description: {tool.description}")
                print("---")

if __name__ == "__main__":
    asyncio.run(inspect_mcp_tools())
Enter fullscreen mode Exit fullscreen mode

This client establishes an SSE transport over HTTP, negotiates capabilities, and loads tool schemas directly into memory without requiring any local tool definitions.

Querying Live EURUSD Price Data via Tool Calls

Once the session is active, your agent can query real-time market data across 60+ supported symbols spanning forex, commodities, equities, crypto, and indices. The underlying price engine returns structured candle records containing nine standardized fields:

  • SymbolCode: The market ticker (e.g., EURUSD, XAUUSD, BTCUSD, AAPL).
  • OpenPrice: Opening price for the candle period.
  • ClosePrice: Most recent trade or closing price.
  • HighPrice: Highest recorded price during the period.
  • LowPrice: Lowest recorded price during the period.
  • Bid: Current best available buying quote.
  • Ask: Current best available selling quote.
  • Volume: Aggregate trading volume.
  • OpenTime: Timestamp representing the start of the current candle.

Under the hood, calling the price tool issues an operation equivalent to calling the REST endpoint GET https://api.realmarketapi.com/api/v1/price?apiKey=YOUR_API_KEY&symbolCode=EURUSD&timeFrame=M1. The platform provides 6 timeframes, including M1, M5, and H1.

Here is how an agent executes a live price tool call in Python:

import asyncio
from mcp import ClientSession
from mcp.client.sse import sse_client

API_KEY = "YOUR_API_KEY"
MCP_URL = f"https://ai.realmarketapi.com/mcp?apiKey={API_KEY}"

async def fetch_price_data(symbol: str, timeframe: str):
    async with sse_client(MCP_URL) as (read_stream, write_stream):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()

            # Execute tool call on the remote server
            result = await session.call_tool(
                "get_price",
                arguments={
                    "symbolCode": symbol,
                    "timeFrame": timeframe
                }
            )

            print(f"Output from get_price for {symbol}:")
            for content in result.content:
                print(content.text)

if __name__ == "__main__":
    asyncio.run(fetch_price_data("EURUSD", "M1"))
Enter fullscreen mode Exit fullscreen mode

The server returns structured data matching this format (values illustrative):

{
  "SymbolCode": "EURUSD",
  "OpenPrice": 1.08512,
  "ClosePrice": 1.08534,
  "HighPrice": 1.08540,
  "LowPrice": 1.08505,
  "Bid": 1.08533,
  "Ask": 1.08535,
  "Volume": 382,
  "OpenTime": "2025-02-15T15:00:00Z"
}
Enter fullscreen mode Exit fullscreen mode

Because the MCP protocol returns typed output, the agent can parse Bid and Ask to compute the spread, inspect whether ClosePrice is trading near HighPrice, or evaluate current volume before executing downstream decisions.

Fetching Technical Indicators Through MCP

Many automated agent workflows require technical indicators to gauge momentum or identify trend reversals. Without dedicated server-side indicator tools, your pipeline would need to fetch long arrays of historical OHLCV data, import math libraries like NumPy or TA-Lib into your environment, compute calculations locally, and format the numbers for the LLM.

The market data MCP server avoids this overhead by exposing server-side calculations directly. Under the hood, these map to endpoints such as GET https://api.realmarketapi.com/api/v1/indicator/rsi?apiKey=YOUR_API_KEY&symbolCode=AAPL&timeFrame=H1&period=14. The platform also calculates SMA, EMA, MACD, and support/resistance levels.

The following code demonstrates an agent querying the RSI tool for Apple stock (AAPL) over an H1 timeframe:

import asyncio
from mcp import ClientSession
from mcp.client.sse import sse_client

API_KEY = "YOUR_API_KEY"
MCP_URL = f"https://ai.realmarketapi.com/mcp?apiKey={API_KEY}"

async def check_momentum(symbol: str, period: int = 14):
    async with sse_client(MCP_URL) as (read_stream, write_stream):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()

            rsi_output = await session.call_tool(
                "get_rsi",
                arguments={
                    "symbolCode": symbol,
                    "timeFrame": "H1",
                    "period": period
                }
            )

            print(f"RSI calculation for {symbol} (H1, period {period}):")
            for item in rsi_output.content:
                print(item.text)

if __name__ == "__main__":
    asyncio.run(check_momentum("AAPL", 14))
Enter fullscreen mode Exit fullscreen mode

In addition to technical indicators, Pro and Business plan subscribers can use the Intelligence API tools through MCP. These tools allow agents to retrieve next-candle bias, trend signals, technical setups, confluence ratings, liquidity zones, order flow summaries, and market anomalies across supported symbols like BTCUSD, US500, or USOIL.

Handling Plan Limits and MCP Connection Gotchas

When deploying AI agents in production, you must account for rate limits, tier restrictions, and protocol overhead.

1. Plan Tier Capabilities

MCP server access depends strictly on your subscription level:

  • Free Plan ($0): 5,000 requests/month, REST only. Covers gold, silver, BTC, ETH, EURUSD, and Google on M1, M5, and H1 timeframes. No credit card required. MCP is not included.
  • Starter Plan ($4.99/mo): 20,000 requests/month, 60+ symbols, all timeframes, 30 days of history, Volatility API access. MCP is not included.
  • Plus Plan ($14.99/mo): 75,000 requests/month, 3 months history, WebSocket x10 connections. MCP is not included.
  • Pro Plan ($34.99/mo): 200,000 requests/month, 1 year history, WebSocket x100 connections, MCP server access (33 tools), and Intelligence API access.
  • Business Plan ($74.99/mo): 1,000,000 requests/month, up to 10 years history, WebSocket x300 connections, MCP server access, and Intelligence API access.
  • Yearly Billing: Saves up to 15% across paid tiers.

If you are on the Free or Starter plan, do not point an MCP client to the server endpoint. Instead, make standard HTTP requests using the REST base URL https://api.realmarketapi.com. You can test a direct REST call using curl:

curl "https://api.realmarketapi.com/api/v1/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1"
Enter fullscreen mode Exit fullscreen mode

This call returns the exact same candle fields (SymbolCode, OpenPrice, ClosePrice, HighPrice, LowPrice, Bid, Ask, Volume, OpenTime) without requiring MCP negotiation.

2. Prompt Context and Schema Overhead

The MCP server registers 33 individual tools. In standard MCP host setups like Claude Desktop, the full schema definition for all 33 tools is injected into the model's system prompt on every conversational turn. This schema overhead consumes context tokens before your agent processes user messages or market queries.

If you run custom autonomous agents where token usage and latency are critical, configure your client to filter tool definitions during session startup, exposing only the specific tools your workflow needs (such as get_price and get_rsi).

3. Request Budgets in Autonomous Loops

Every tool call initiated by an LLM counts toward your monthly request limit. An autonomous script that prompts a model to inspect EURUSD, XAUUSD, and BTCUSD every 60 seconds makes 3 tool calls per minute. Over a 30-day month, that adds up to 129,600 requests. This fits comfortably within the Pro plan quota of 200,000 requests per month, but would exhaust a Starter plan's 20,000 request limit in less than five days.

For continuous streaming or high-frequency polling where conversational reasoning is unnecessary, use the WebSocket interface at wss://api.realmarketapi.com instead of repeated MCP tool invocations.

To begin building your agent, check your plan tier on RealMarketAPI pricing, grab your API key, and test your first MCP handshake against https://ai.realmarketapi.com/mcp?apiKey=YOUR_API_KEY.

Top comments (0)