OpenTrading
An open-source AI trading agent for MetaTrader 5 with MCP support, connecting AI clients to MT5 for market data, analysis, and risk-gated trading.
README
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:
- Signal Engine — quant/rule-based trade signals
- Risk Engine — deterministic risk validation (final gate)
- Human Approval — explicit operator confirmation
- 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
- Data Never Fabricated — If MT5/Tavily is unavailable, the system returns
DATA_UNAVAILABLE, not fake data. - Risk Engine Is Final Gate — No order bypasses risk validation.
- Live Trading Off By Default —
ENABLE_LIVE_ORDER=falseunless explicitly enabled. - Human In The Loop — Live orders require operator approval.
- Kill Switch — Emergency stop survives restarts (file-backed state).
- 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.
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。