Building an MCP Agentic Stock Trading System - Part 3: The Agentic Loop

This is Part 3 of a series on building an MCP trading system. Read Part 1 for the architecture overview and Part 2 for the MCP servers and tools.

The agentic loop is where LLMs become active problem-solvers instead of passive responders. The LLM doesn't just answer once—it iteratively calls tools, analyzes results, and decides what to check next. My trading agent uses this to analyze stocks: fetch data, calculate indicators, check trends, then make a decision.

Here's how the agentic loop works in my system (llm-trading-agent.js:280-353):

  1. Send initial request: "Analyze AAPL for trading opportunities"
  2. LLM responds: stop_reason: 'tool_use' - "I need historical data"
  3. Execute tool locally: Call get_historical_prices('AAPL') via MCP
  4. Send results back: Add tool response to conversation
  5. LLM responds again: stop_reason: 'tool_use' - "Let me check RSI"
  6. Execute tool: Call calculate_rsi(prices) via MCP
  7. Send results back: Add RSI result to conversation
  8. LLM continues: Maybe checks trend, MACD, moving averages...
  9. LLM finishes: stop_reason: 'end_turn' - "BUY 10 shares, confidence 0.75, reasoning..."

The Agentic Loop

The loop runs until the LLM has enough information to decide. It's not scripted—the model chooses which tools to use and in what order.

while (continueLoop) {
  const response = await anthropic.messages.create({
    model: 'claude-3-haiku',
    tools: this.getMCPTools(),
    messages: messages,
  });

  if (response.stop_reason === 'tool_use') {
    // Execute tools, add results to messages
    // Loop continues
  } else if (response.stop_reason === 'end_turn') {
    // LLM is done, parse decision
    continueLoop = false;
  }
}

This is fundamentally different from rules-based systems. The rules-based agent always checks the same indicators in the same order. LLMs adapt—if RSI looks neutral, maybe check something else. If volume is unusual, investigate further.

Both Claude (via API) and the local LLM (via LM Studio) use this same loop pattern. Same architecture, different models, different intelligence.

Next: comparing what the three agents actually decide when analyzing the same stock.

agentic-stock-trader - View on GitHub

This post is part of my daily AI journey blog at Mosaic Mesh AI. Building in public, learning in public, sharing the messy middle of AI development.

Previous
Previous

Building an MCP Agentic Stock Trading System - Part 4: When Agents Disagree

Next
Next

Building an MCP Agentic Stock Trading System - Part 2: The MCP Servers and Tools