Skip to main content
Glama

OpenTrading

An open-source AI trading agent for MetaTrader 5 with MCP (Model Context Protocol) support.

Connect any AI client (Claude, GPT, OpenCode, Cursor, Copilot) directly to your MT5 terminal through a standardized MCP interface. The agent handles signal generation, risk management, backtesting, and paper/live execution — while the AI acts as analyst, not executor.

⚠️ Risk Disclaimer: This software is provided for educational and research purposes only. It is NOT financial advice. Trading financial instruments (forex, crypto, commodities, indices) carries substantial risk of loss and may not be suitable for all investors. Past performance and backtest results do not guarantee future results. The authors and contributors are not responsible for any financial losses incurred through the use of this software. Use at your own risk. Never trade with money you cannot afford to lose. Always consult with a licensed financial advisor before making trading decisions.

Architecture

User / AI Client
      │
      ▼
MCP Server (port 8020) ── HTTP ──► FastAPI Backend (port 8010)
                                        │
                          ┌─────────────┼─────────────┐
                          ▼             ▼              ▼
                    Signal Engine   Risk Engine    Execution Gate
                    (quant/rule)   (deterministic) (paper/live)
                          │             │              │
                          └─────────────┼──────────────┘
                                        ▼
                              MT5 / Tavily (optional)

The LLM acts as an analyst/operator, not an order executor. Every live order must pass through:

  1. Signal Engine — quant/rule-based trade signals

  2. Risk Engine — deterministic risk validation (final gate)

  3. Human Approval — explicit operator confirmation

  4. Kill Switch — emergency stop mechanism

If data is unavailable, the system reports source=unavailable — it never fabricates market data.

What Makes This Different

  • MCP-Native — Exposes 80+ MCP tools so any AI client can query market data, analyze charts, run backtests, and manage positions through a standardized protocol. No custom API integration needed.

  • MetaTrader 5 First — Deep MT5 integration: real-time bars, ticks, spread data, account status, position management, and order execution. Works with any MT5 broker (demo or live).

  • Risk-Gated — The AI analyzes; the risk engine decides. No order reaches MT5 without passing deterministic risk validation.

  • Works Remotely — Run the MCP server on Windows (MT5 host) and connect from macOS/Linux AI clients over SSE. Your AI tools stay on your dev machine while MT5 runs on the trading PC.

  • FastAPI backend with 80+ endpoints covering the full quant pipeline

  • Signal engine — baseline strategies (SMA, RSI, ATR, volatility breakout) + ensemble voting

  • Risk engine — deterministic gate (max risk, daily loss, spread caps, edge floor, kill switch)

  • Backtest engine — realistic cost model (spread, slippage, commission, swap, execution delay)

  • Model registry — LightGBM/XGBoost training, walk-forward validation, champion/challenger

  • Opportunity scanner — multi-symbol, multi-timeframe confluence scoring

  • Paper trading — simulated execution with position management and edge tracking

  • Live trading — gated behind approval queue, operator session, kill switch (disabled by default)

  • Audit trail — immutable event log in data/audit/audit.jsonl

  • Tavily research — optional web/news sentiment and macro context

How It Works — MCP + MT5

┌──────────────────────┐     SSE / stdio      ┌──────────────────────────┐
│   AI Client           │ ◄──────────────────► │   OpenTrading MCP Server │
│  (Claude / GPT /      │                      │   (port 8020)            │
│   OpenCode / Cursor)  │    80+ MCP tools     │                          │
│                       │                      │   Read-only by default:  │
│   macOS / Linux /     │   analysis_packet    │   • market data          │
│   Windows             │   get_market_bars    │   • features & indicators│
│                       │   market_research    │   • backtest & overfit   │
│                       │   htf_context        │   • confluence scores    │
│                       │   propose_trade      │   • position management  │
│                       │   request_live_order │                          │
└──────────────────────┘                      └───────────┬──────────────┘
                                                          │ HTTP
                                                          ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                        OpenTrading Backend (port 8010)                    │
│                                                                          │
│   ┌──────────────┐   ┌──────────────┐   ┌──────────────┐                │
│   │ Signal Engine │   │  Risk Engine │   │Execution Gate│                │
│   │ (quant/rule)  │──►│(deterministic│──►│ (paper/live) │                │
│   └──────────────┘   └──────────────┘   └──────┬───────┘                │
│                                                  │                        │
└──────────────────────────────────────────────────┼────────────────────────┘
                                                   │
                                                   ▼
                                    ┌──────────────────────────┐
                                    │   MetaTrader 5 Terminal  │
                                    │   (Windows)              │
                                    │                          │
                                    │   • Real-time ticks      │
                                    │   • OHLC bars            │
                                    │   • Spread data          │
                                    │   • Account & positions  │
                                    │   • Order execution      │
                                    └──────────────────────────┘

The MCP server is a thin proxy — it never talks to MT5 directly. All market data flows: MT5 → Backend → MCP → AI Client. All orders flow: AI Client → MCP → Backend → MT5, with the risk engine as the final gate at every step.

MCP Connection — Use from Anywhere

Local (same machine):

// opencode.jsonc or .cursor/mcp.json
{ "mcp": { "opentrading": { "type": "local", "command": ["python", "-m", "mcp_servers.trading_agent_mcp"] } } }

Remote (macOS/Linux client → Windows MT5 host):

// On your AI client machine (macOS/Linux)
{ "mcp": { "opentrading": { "type": "remote", "url": "http://<windows-ip>:8020/mcp", "timeout": 120000 } } }

The MCP server runs in data-only mode by default (MCP_DATA_ONLY_MODE=true). The AI client gets raw market data, features, analytics, and research — it must form its own thesis. Live trading tools become available only when MCP_ENABLE_LIVE_TOOLS=true and MCP_DATA_ONLY_MODE=false. See MCP Tool Policy and Agent MCP Usage.

Quick Start

Prerequisites

  • Python 3.11+ (all platforms)

  • MetaTrader 5 terminal on Windows (for live market data & execution)

  • Tavily API key (optional, for news research)

Quick Setup (macOS / Linux / Windows)

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate      # macOS/Linux
# .venv\Scripts\activate       # Windows

pip install -r requirements.txt
python -m pytest               # verify setup

Start the Backend + MCP Server

The backend auto-starts an embedded MCP server on port 8020:

uvicorn app.main:app --host 127.0.0.1 --port 8010 --env-file .env --reload

You now have both:

  • Backend API: http://127.0.0.1:8010 (REST)

  • MCP Server: http://127.0.0.1:8020 (SSE + Streamable HTTP)

Or start them separately for remote access:

# Terminal 1 — Backend only
TRADING_AGENT_DISABLE_EMBEDDED_MCP=true uvicorn app.main:app --host 0.0.0.0 --port 8010 --env-file .env

# Terminal 2 — Standalone MCP server
TRADING_AGENT_BASE_URL=http://127.0.0.1:8010 MCP_TRANSPORT=sse MCP_SSE_HOST=0.0.0.0 MCP_SSE_PORT=8020 python -m mcp_servers.trading_agent_mcp

Fresh Start (Port Cleanup)

# macOS / Linux
lsof -ti:8010,8020 | xargs kill -9

# Windows
.venv\Scripts\python.exe scripts\kill_ports.py 8010 8020

Configuration

Copy .env.example to .env and adjust as needed:

# Safety defaults (live trading disabled)
ENABLE_LIVE_ORDER=false
REQUIRE_AUTH=false
KILL_SWITCH_ACTIVE=false

# Risk parameters (tuned for small demo accounts)
MAX_RISK_PER_TRADE=0.05        # 5% max risk per trade
MAX_DAILY_LOSS=0.10            # 10% max daily drawdown
MIN_SIGNAL_CONFIDENCE=0.42     # minimum signal confidence
MIN_REWARD_RISK=0.7            # minimum reward:risk ratio

# Optional integrations
MT5_ENABLED=false              # MT5 bridge (Windows only)
TAVILY_API_KEY=                # News research API key

Full configuration reference in .env.example.

Key Endpoints

Endpoint

Purpose

GET /health

Backend health check

POST /market/bars

Fetch OHLC bars

POST /features/build

Compute technical features

POST /signal/generate

Generate trade signal

POST /risk/check

Validate risk parameters

POST /backtest/run

Run strategy backtest

POST /opportunity/scan

Multi-symbol scan

POST /orders/paper

Submit paper (simulated) order

POST /orders/live/submit

Submit live order (requires approval)

POST /approval/create

Create approval record

POST /killswitch/trigger

Toggle kill switch

GET /audit/logs

Retrieve audit trail

GET /mcp-health

MCP server health status

Project Structure

opentrading/
├── app/                    # FastAPI application
│   ├── main.py             # Entrypoint (~2600 lines, all routes)
│   ├── config.py           # Environment config (Settings dataclass)
│   ├── auth.py             # Internal token guard
│   └── schemas.py          # Pydantic data models
├── services/               # Business logic (60+ services)
│   ├── signal_service.py   # Signal engine
│   ├── risk_service.py     # Risk engine
│   ├── backtest_service.py # Backtest simulator
│   └── ...
├── strategies/             # Trading strategy implementations
│   ├── rule_baseline.py    # SMA + RSI baseline
│   └── volatility_breakout.py
├── mcp_servers/            # MCP server (HTTP proxy to backend)
├── models/                 # Trained ML models
│   ├── registry.json       # Model registry
│   └── saved_models/
├── data/                   # File-backed runtime state
│   ├── state/              # kill_switch.json, operator_session.json
│   ├── journal/            # paper_trading_journal.jsonl
│   ├── alerts/             # price_alerts.json
│   ├── audit/              # audit.jsonl
│   └── model_registry/     # registry.json
├── docs/                   # Documentation
├── scripts/                # Utility scripts and runners
│   ├── run_paper_loop.py
│   ├── run_daily_paper_eval.py
│   ├── run_strategy_sweep.py
│   └── ...
└── tests/                  # Test suite (50+ test files)

Safety Philosophy

  1. Data Never Fabricated — If MT5/Tavily is unavailable, the system returns DATA_UNAVAILABLE, not fake data.

  2. Risk Engine Is Final Gate — No order bypasses risk validation.

  3. Live Trading Off By DefaultENABLE_LIVE_ORDER=false unless explicitly enabled.

  4. Human In The Loop — Live orders require operator approval.

  5. Kill Switch — Emergency stop survives restarts (file-backed state).

  6. MCP Data-Only Mode — AI clients receive raw data + context, not trade orders.

Docs

Document

Description

Trading SOP

Standard operating procedure

Risk Rules

Risk management parameters

No-Trade Conditions

When the system refuses to trade

Live Order Policy

Live trading requirements

Emergency Kill Switch

Emergency stop procedures

MCP Tools

Available MCP tools

Agent MCP Usage

AI client usage guide

Operator Prompt

Operator system prompt

AI Client Prompt

AI client system prompt

Research Checklist

Market research workflow

Daily Paper Eval

Daily evaluation procedure

Quant Pipeline

Research pipeline docs

Runbook

Operational runbook

Development

# Run all tests
python -m pytest

# Run a specific test group
python -m pytest tests/test_signal.py tests/test_risk.py -q

# Run a single test file
python -m pytest tests/test_api.py -v

# Start dev server with auto-reload
uvicorn app.main:app --reload --host 127.0.0.1 --port 8010 --env-file .env

No CI, linter, formatter, or typecheck config is committed. pytest is the only executable source of truth.

License

MIT License — see LICENSE file.


⚠️ Remember: This is experimental software. You are responsible for your own trading decisions and any resulting financial outcomes. The market does not guarantee returns. Always manage your risk.

A
license - permissive license
-
quality - not tested
C
maintenance

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

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/hyuwowo/opentrading'

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