For educational purposes only. Trading involves substantial risk of loss. Not financial advice.

Architecture

How the system works under the hood.

System Overview

┌─────────────────────────────────────────────────────────────────┐
│                         AGENT (agent-v1.mjs)                    │
├─────────────────────────────────────────────────────────────────┤
│  ┌─────────────────┐     ┌─────────────────────────────────┐    │
│  │   StockTwits    │     │       LLM Analysis (OpenAI)     │    │
│  │   Sentiment     │────▶│  • Signal research              │    │
│  │                 │     │  • Position management          │    │
│  └─────────────────┘     │  • Buy/sell decisions           │    │
│                          └──────────────┬──────────────────┘    │
└─────────────────────────────────────────┼───────────────────────┘
                                          │
                                          ▼
┌─────────────────────────────────────────────────────────────────┐
│                    MCP SERVER (Cloudflare Workers)              │
├─────────────────────────────────────────────────────────────────┤
│  Policy Engine → Approval Tokens → Order Execution              │
└──────────────────────────┬──────────────────────────────────────┘
                           │
                           ▼
                    ┌─────────────┐
                    │   Alpaca    │
                    │   Broker    │
                    └─────────────┘
    

Agent Loop

The agent runs continuously with two main phases:

Data Gathering (24/7)

  1. Fetch trending stocks from StockTwits API
  2. Calculate sentiment scores (bullish vs bearish messages)
  3. Filter by minimum sentiment and volume thresholds
  4. Send top signals to LLM for research

Trading (Market Hours Only)

  1. Check existing positions for stop-loss/take-profit
  2. Ask LLM to analyze each position (HOLD/SELL)
  3. Look for buy opportunities from researched signals
  4. Execute trades via MCP server

LLM Decision Making

Signal Research

For each trending stock, the LLM receives:

It returns:

{
  "verdict": "BUY" | "SKIP" | "WAIT",
  "confidence": 0.0-1.0,
  "reasoning": "explanation",
  "red_flags": ["concerns"],
  "catalysts": ["positive factors"]
}

Position Analysis

For each held position, the LLM receives:

It returns:

{
  "action": "HOLD" | "SELL",
  "confidence": 0.0-1.0,
  "reasoning": "explanation"
}

Order Flow

All orders go through a two-step process for safety:

1. Preview

Call orders-preview with order details. The policy engine validates:

Returns an approval token (valid 5 minutes).

2. Submit

Call orders-submit with the approval token. The order is executed through Alpaca.

MCP Tools

The MCP server exposes these tools:

Tool Description
accounts-get Get account balance and status
positions-list List current positions
positions-close Close a position
orders-preview Preview order, get approval token
orders-submit Submit approved order
orders-list List recent orders
market-clock Check if market is open
market-quote Get stock quote
technicals-get Get RSI, MACD, etc.

Project Structure

mahoraga/
├── agent-v1.mjs              # Trading agent
├── .dev.vars                 # API keys (gitignored)
│
├── src/                      # MCP Server
│   ├── index.ts              # Entry point
│   ├── durable-objects/
│   │   └── trading-agent.ts  # DO version (optional)
│   ├── mcp/
│   │   └── agent.ts          # Tool definitions
│   ├── policy/
│   │   ├── engine.ts         # Trade validation
│   │   └── approval.ts       # Token handling
│   └── providers/
│       ├── alpaca/           # Broker client
│       └── llm/              # OpenAI client
│
├── dashboard/                # React dashboard
│   └── src/App.tsx
│
└── migrations/               # D1 database