A complete AI-powered MetaTrader 5 trading copilot. Connect your MT5 terminal, chat with me (Z.ai — free for you) about the markets, get trade proposals backed by Smart Money Concepts + multi-timeframe confluence + market regime detection. Run, backtest (with walk-forward overfitting verdict), and auto-execute 4 trading strategies. Get morning briefs + performance dashboards + Telegram alerts. Schedule everything via cron. Wrap as a Windows .exe installer with Tauri.
- Morning brief automation — scheduled AI-written daily briefing at 07:00 (configurable). Covers all watchlist symbols with regime, bias, confluence, key levels, open positions review, top setups, risks, and a plan for the day. Auto-sent to Telegram if configured. New UI tab + AI tool
generate_morning_brief. - Performance dashboard — computes real trade metrics from the DB: Net P&L, Win rate, Profit factor, Expectancy, Max DD, Sharpe, Calmar, Avg R-multiple, equity curve (Recharts), drawdown chart, best/worst trades, longest streak, distribution by symbol/strategy/direction. Period selector (24h/7d/30d/all). New UI tab + AI tool
get_performance_metrics. - Telegram alerts — fires on: trade fills, trade closes, kill switch events, morning briefs, daily summaries, errors. Settings UI with Bot Token + Chat ID + Send Test Message button. All alerts persisted to DB regardless of delivery success.
- Cron-driven scan loop —
/api/cron/tickendpoint runs all due scheduled jobs. 4 default jobs: morning brief (07:00), auto-trade scan (every 5 min), performance snapshot (22:00), daily summary (21:00). Settings → Notify tab shows the cron table with toggle switches + "Run Tick Now" button. Includes Windows Task Scheduler + Linux crontab scripts. - Windows installer prep — full Tauri config in
desktop/for building a native.msiinstaller. README explains both Tauri and PyInstaller paths. - 2 new AI tools —
generate_morning_brief,get_performance_metrics. Total AI tools: 18. - Updated system prompt — extended with Phase 4 sections covering morning brief + performance + automation.
- 3 new Prisma models —
MorningBrief,PerformanceSnapshot,TelegramAlert,CronJob.
- Strategy library — 4 strategies with declarative manifests (regimes, sessions, suited markets, params):
- MACD-EMA Trend Follow — MACD(12,26,9) cross + EMA(100) filter + ATR SL/TP. For trending markets.
- BB-RSI Mean Reversion — RSI<30 + below lower BB + bounce. For ranging markets.
- SMC Order Block Retest — institutional OB detection + retest entry + SL beyond OB + TP at next liquidity. For trend/range/reversal markets.
- Opening Range Breakout (ORB) — first N minutes of London/NY session defines range; enter on breakout with expansion confirmation. Failure-trade logic included.
- Backtester engine (pure TypeScript, no external deps):
- Walk-forward validation (train/test windows)
- Overfitting verdict: ROBUST / MODERATE / WEAK / OVERFITTED based on test/train ratio + window consistency
- Full metrics: Net profit, Win rate, Profit factor, Expectancy, Max DD, Sharpe, Calmar, Avg R-multiple
- Spread + commission + slippage modeling
- Trade log with entry/exit/exit-reason per trade
- Market regime detector — ADX + ATR ratio classifies current regime:
- trend (ADX>25), range (ADX<20), expansion (ATR>1.3×avg), compression (ATR<0.7×avg), reversal (ADX>45)
- Returns ADX, +DI/-DI, bias, current session, confidence score, description
- Auto-trade engine:
- Scans every N minutes (default 5) across active strategies × watchlist symbols
- Each strategy gated by manifest: regime + session + market-type filters
- Every signal passes through Phase 2
evaluateTradeComprehensive(kill switch, DD, correlation, news, lot sizing) - Daily signal cap (default 10) to prevent runaway
- All scans + signals + vetoes logged to audit
- State persisted in DB (active strategies, last scan, signals today)
- Manual scan trigger via UI button or AI tool
- 3 new AI tools —
list_strategies,backtest_strategy(with walk-forward),run_strategy_scan,detect_regime. Total AI tools: 16. - Updated system prompt — I now follow an extended workflow: detect_regime → MTF → SMC → news → correlation → propose → execute. For strategies, I always recommend walk-forward backtesting before deployment.
- Strategies tab (new UI tab) with 3 sub-tabs:
- Strategy Library — cards showing all 4 strategies with manifests
- Backtester — configure + run + see metrics grid + walk-forward verdict + trade log
- Auto-Trade — engine status, active strategies toggle, run scan button, scan result table
- Smart Money Concepts analysis — runs the
smartmoneyconceptsPython library inside the sidecar. Detects: Fair Value Gaps, Order Blocks (with volume strength), BOS/CHoCH, Liquidity zones (equal highs/lows), Swing highs/lows, Retracements. Exposed as/smc/analyzeAPI andanalyze_smcAI tool. - Multi-Timeframe Confluence — analyzes W1/D1/H4/H1/M15 in parallel, computes bias per timeframe, returns an overall confluence score (0-100) + recommendation. Exposed as
/api/smc/mtfAPI andmulti_timeframe_analysisAI tool. - TradingView Chart tab — embedded free TradingView widget (M15 → W1), with the SMC panel and MTF panel side-by-side. Auto-refreshes every 60-120s.
- MTF Snapshot on Dashboard — at-a-glance bias + confluence score per watchlist symbol.
- Risk engine upgrades:
- Correlation matrix — every trade now checked against 30-day D1 Pearson correlation with open positions. Rejects if |corr| > 0.8 with any open position.
- News calendar filter — pulls high-impact events from MT5 Economic Calendar. Rejects trades within ±30min of high-impact news on the symbol's currencies.
- Real symbol-info-based lot sizing — uses actual
tickValue/tickSize/volumeMin/volumeMax/volumeStepfrom MT5 (no more heuristic defaults).
- Auto-journaling — when a position closes, the LLM is called with the trade context (entry, exit, P&L, hold time, AI reasoning at entry) and writes a structured journal entry automatically. Kill-switch events also generate a journal entry.
- 4 new AI tools —
analyze_smc,multi_timeframe_analysis,check_news,get_correlation. Total AI tools: 12. - Updated system prompt — I now follow a structured analysis workflow before proposing trades: MTF confluence → SMC on H4 → news check → correlation check → propose → execute.
- Web UI (Next.js 16, runs on your Windows PC, accessible from any device on your LAN)
- AI Copilot chat — I'm the default LLM (free for you via Z.ai). Switchable to OpenRouter, Ollama, LM Studio, Google AI, NVIDIA, OpenAI, Anthropic in Settings
- MT5 connection — via a Python FastAPI sidecar that wraps the MetaTrader5 SDK
- 8 Phase 1 AI tools — get account info, ticks, candles, positions, propose trades (with risk checks), place/close/modify trades
- Risk engine — vetoes any trade that breaks your rules (kill switch, DD limits, position caps, spread filter, Friday close, SL required on live)
- Live dashboard — account balance, equity, P&L, watchlist ticks, open positions, kill switch
- Manual trade ticket — with AI-suggested SL/TP and risk-engine pre-flight
- Audit log — every AI message, every tool call, every trade, every risk veto — fully traceable
- Demo/Live detection — auto-detected from your MT5 server string.
- Copilot + Auto-trade modes
FX pairs (configurable watchlist), XAUUSD (gold), BTCUSD, ETHUSD.
Browser (your phone/laptop) ──HTTP+WebSocket──► Next.js 16 app (port 3000)
│
│ HTTP localhost:8001
▼
Python FastAPI sidecar
(mt5-sidecar/main.py)
│
│ MetaTrader5 SDK
▼
MT5 Terminal (Windows)
The Next.js app and the Python sidecar both run on your Windows PC. The browser can be on any device on your LAN (phone, laptop, tablet).
- Python 3.10+ — https://python.org (check "Add to PATH" during install)
- MetaTrader 5 terminal — https://www.metatrader5.com/en/download
- Node.js 18+ and Bun — https://bun.sh
- Git — to clone this repo
Open MT5 terminal and log in to your broker (demo first!).
cd mt5-sidecar
copy .env.example .env
# Edit .env and fill in MT5_LOGIN, MT5_PASSWORD, MT5_SERVER
notepad .env
pip install -r requirements.txt
python main.pyYou should see:
[INFO] MT5 sidecar v0.1.0 starting on 0.0.0.0:8001
[INFO] ✓ Connected to MT5 — login=XXXXX, server=MetaQuotes-Demo
INFO: Uvicorn running on http://0.0.0.0:8001
Leave this terminal running.
In a new terminal:
cd <project root>
bun install
bun run db:push # creates the SQLite DB
bun run devThe app runs on http://localhost:3000 (Next.js direct) or http://localhost:81 (through the bundled Caddy gateway — recommended for full WebSocket support).
Open http://localhost:81 in your browser.
- Go to Settings → MT5 tab — verify your login/server are saved. The dashboard should show "Connected to MT5 sidecar" and a "LIVE" badge (not mock).
- Go to Settings → AI Provider — Z.ai is the default (free for you). Optionally add an API key for another provider (OpenRouter has free models too).
- Go to Settings → Risk — adjust risk %, DD limits, etc. to your comfort.
- Go to Settings → Watchlist — add or remove symbols. Defaults: EURUSD, GBPUSD, USDJPY, XAUUSD, BTCUSD, ETHUSD.
- Dashboard — see live account + watchlist + positions + kill switch
- AI Copilot — ask me anything: "What's EURUSD doing?", "Should I long gold?", "Audit my open positions"
- Trade — manual ticket with AI-suggested SL/TP, passes through risk engine
- Positions — close or modify SL/TP on any open position
- Journal — AI-written trade reviews (populated as trades close)
- Settings → Audit Log — full audit trail of every action
In the sandbox/preview environment, all MT5 calls return mock data so you can explore the UI. When you run the Python sidecar on your Windows PC with MT5 running, all data is real.
To check which mode you're in: look at the top-right of the dashboard — it shows either "Live" (real sidecar) or "Mock" (no sidecar).
- Kill switch — one button closes all positions + locks trading for 30 min
- Daily drawdown limit — auto-halts when hit (default 5%)
- Max concurrent positions (default 3)
- Max positions per symbol (default 2)
- Spread filter — rejects trades when spread > 2× normal
- Friday close — no new trades after 21:00 UTC Friday
- Saturday lock — market closed
- SL required on live accounts
- Demo-only by default — auto-detected from server string
- Full audit log — every AI decision, every trade, every veto — stored in SQLite
| Provider | Cost | Setup |
|---|---|---|
| Z.ai (default) | Free for you | None — works out of the box |
| OpenRouter | Free tier available | API key from openrouter.ai |
| Ollama | Free | Install Ollama locally, run ollama pull llama3.1:8b |
| LM Studio | Free | Install LM Studio, start the local server |
| Google AI | Free tier | API key from aistudio.google.com |
| NVIDIA NIM | Free tier | API key from build.nvidia.com |
| OpenAI | Paid | API key from platform.openai.com |
| Anthropic | Paid | API key from console.anthropic.com |
- Smart Money Concepts analysis (FVG, Order Blocks, BOS/CHoCH, Liquidity, Sessions) — from
smart-money-conceptsrepo - TradingView chart embed (free widget)
- Multi-timeframe confluence analysis (W→D→H4→H1→M15 alignment)
- Correlation matrix (reject trades too correlated with open positions)
- News calendar filter (MT5 Economic Calendar integration)
- AI-written trade journal entries (auto-generated on close)
- Pre-trade approval gate with structured reasoning
- Auto-trade mode with strategy library (MACD-EMA, BBRSI, SMC OB-retest)
- Backtester with walk-forward + overfitting verdict (from
tradingview-mcprepo) - Regime detection (trend/range/expansion)
- Strategy manifest system (from
Argusrepo)
- Morning brief automation (scheduled AI summary of the day)
- Performance dashboard (Sharpe, Calmar, expectancy, R-multiple)
- Telegram alerts
- Multi-account support
- Tauri/PyWebView wrap as Windows desktop .exe installer
- Frontend: Next.js 16, React 19, TypeScript, Tailwind CSS 4, shadcn/ui, Zustand, TanStack Query
- Backend (Next.js API routes): Node.js, Prisma ORM (SQLite), z-ai-web-dev-sdk
- Backend (MT5 sidecar): Python, FastAPI, MetaTrader5 SDK
- Realtime: Socket.IO (mini-service on port 3003, gateway-friendly)
- Database: SQLite (shared between Next.js and accessible from Python for journaling)
.
├── src/
│ ├── app/
│ │ ├── page.tsx # Main UI — tabbed single-page app
│ │ ├── layout.tsx
│ │ └── api/ # Next.js API routes
│ │ ├── chat/ # AI chat endpoint (LLM + tool dispatch)
│ │ ├── mt5/ # MT5 proxy → sidecar
│ │ ├── trade/ # Trade placement / close / modify
│ │ ├── settings/ # Settings CRUD
│ │ ├── journal/ # Journal entries
│ │ ├── audit/ # Audit log
│ │ ├── kill-switch/ # Kill switch activate/deactivate
│ │ └── conversations/ # Chat history
│ ├── components/
│ │ ├── ui/ # shadcn/ui components
│ │ └── trading/ # Trading-specific components
│ │ ├── dashboard.tsx
│ │ ├── chat.tsx
│ │ ├── trade.tsx
│ │ ├── positions.tsx
│ │ ├── journal.tsx
│ │ └── settings.tsx
│ ├── hooks/
│ │ ├── use-realtime.ts # Socket.IO hook for ticks/positions
│ │ ├── use-toast.ts
│ │ └── use-mobile.ts
│ └── lib/
│ ├── db.ts # Prisma client
│ ├── settings.ts # Settings helpers
│ ├── llm/
│ │ └── provider.ts # 8-provider LLM abstraction
│ ├── mt5/
│ │ └── client.ts # MT5 sidecar client + mock fallback
│ ├── risk/
│ │ └── engine.ts # Risk engine (DD, kill switch, lot sizing)
│ └── tools/
│ └── dispatcher.ts # AI tool dispatcher (8 tools)
├── prisma/
│ └── schema.prisma # Settings, Conversation, Message, Trade, JournalEntry, AuditLog
├── mt5-sidecar/ # Python FastAPI sidecar (runs on Windows PC)
│ ├── main.py
│ ├── requirements.txt
│ └── .env.example
├── mini-services/
│ └── realtime/ # Socket.IO service (port 3003)
│ ├── index.ts
│ └── package.json
├── research/ # 10 cloned trading repos for reference
└── package.json
Trading forex, gold, and crypto carries substantial risk. This software is provided for educational and informational purposes only. Always test on a DEMO account first. Never trade with money you can't afford to lose. The AI can and will make mistakes — that's why every trade passes through the risk engine and (in copilot mode) requires your explicit confirmation.
MIT for the original code in this repo. The research/ folder contains third-party repositories with their own licenses — see each repo's LICENSE file.