GETTING STARTED
1. Quickstart & Zero-DLL Setup
Cortex AI connects to MetaTrader 4 and MetaTrader 5 over a native Windows Named Pipe (\\.\pipe\Cortex.AI.v2) using MQL's built-in FileOpen sandbox—meaning Allow DLL imports stays OFF.
Step-by-Step Installation
- Launch the Cortex AI desktop app (
npm start or portable release executable).
- Open the Settings tab → Install EA to MetaTrader → click Scan & install.
- In MetaTrader, right-click Navigator → Expert Advisors → Refresh.
- Drag CortexEA onto any chart and check Allow Algo Trading (leave Allow DLL imports unchecked).
- Within 1 second, the chart comment displays
Cortex AI: connected and the terminal appears in the top selector bar.
ARCHITECTURE
2. System Architecture & Protocol v2.1
All communication between the desktop app and attached MT4/MT5 charts uses newline-delimited JSON (NDJSON) over \\.\pipe\Cortex.AI.v2 defined in app/src/shared/protocol.ts.
| Direction | Message Type | Cadence / Trigger | Purpose |
| EA → App | hello | On attach / reconnect | Handshakes protocol 2.0, account login, broker, chart symbol & timeframe. |
| EA → App | sync | Every 250ms | Streams live Bid/Ask, contract specs, balance/equity, open positions, pending orders & rules. |
| EA → App | bars | Every 5s / new bar | Streams up to 120 closed OHLCV bars for the on-device PhD Quant Regime Engine. |
| App → EA | command | On user/agent action | Dispatches place_order, modify_position, close_position, set_protection, etc. |
| EA → App | ack | On command completion | Returns accepted, done (with broker ticket/fill price), or failed. |
EXECUTION
3. Order Ticket & Top Execution Bar
Designed for narrow side-by-side placement (`480×820`) next to MetaTrader, the Trade tab places the 2-click SELL / BUY execution buttons at the very top of the viewport, followed immediately by the AI Quant Regime & Alpha Radar.
- Two-Click Arming: Clicking
BUY or SELL arms the button (Confirm BUY / Confirm SELL) for 2.5 seconds; clicking a second time dispatches the order.
- Fill-Anchored Market Stops: Market orders send
slPips and tpPips to the EA so the EA anchors stop-loss and take-profit to the actual broker fill price.
- Three Sizing Modes: Size by
% of Equity, $ Cash Risk, or fixed Lots.
TRADE MANAGEMENT
4. Autonomous EA Protection Rules
Protection rules execute inside the MetaTrader EA on every tick and persist across terminal or desktop restarts in MQL5/Files/CortexEA/rules-<login>-<symbol>.tsv:
- Break-Even: Moves SL to Entry + Offset pips once floating profit reaches Trigger pips.
- Trailing Stop: Trails SL behind the highest favorable price excursion by Trail pips.
- Partial Close (50%): Closes half the position volume once profit reaches Partial Trigger pips and records a
partialDone bitmask so it never double-fires.
FUND MANAGER
5. Multi-Terminal Fund Manager (1 → N)
The Fund tab turns Cortex AI into a multi-account execution desk:
- Pro-Rata Equity %: Risks the same percentage of equity on each selected terminal, automatically converting to each terminal's lot size using its own broker tick value.
- Equal Cash Risk ($): Risks the exact same dollar amount on each selected terminal.
- Quant Kelly Optimal: Sizes each terminal using its active chart's Quarter-Kelly regime recommendation.
- Emergency Flatten All Terminals: Two-click confirmation dispatches
close_all across every connected MT4/MT5 terminal simultaneously.
QUANT ENGINE
6. PhD Quant Regime & Portfolio Risk Engine
Implemented in app/src/shared/quant.ts, the engine computes deterministic statistical telemetry from the EA's 120-bar OHLCV stream:
Hurst Exponent (R/S): H > 0.55 (Trend) | H < 0.45 (Mean-Revert) | ~0.50 (Random Walk)
Yang-Zhang Volatility: Minimum-variance OHLC estimator (annualized %)
Quarter-Kelly Fraction: f* = clamp(0.25 * ((p * b - q) / b), 0.25%, 2.00%)
95% 1-Day Parametric VaR: 1.64485 * DailySigma * TotalNotionalExposure
SAFETY
7. Risk Guard & Daily Loss Circuit Breaker
Every order path—UI ticket, Fund Manager, AI Assistant, and MCP/REST Agent—passes through TradingHub and checkRisk() before queuing a command:
- Max Risk % Per Trade: Blocks any order whose stop-loss risk exceeds your configured percentage.
- Max Daily Loss %: Tracks your daily equity high-water mark and blocks new entries if daily drawdown reaches your limit.
- Max Lots & Max Open Positions: Hard caps on position size and concurrent open trades.
DEVELOPERS & AGENTS
8. Local HTTP MCP Server & Ready-Made Harness Prompts
Cortex AI runs a local HTTP Streamable MCP server on http://127.0.0.1:17845/mcp and REST API at http://127.0.0.1:17845/v1. Every connected agent receives 11+ quantitative tools subject to human-in-the-loop approvals and Risk Guard limits.
Quick Harness Connection (No npm Required)
# Claude Code CLI:
claude mcp add --transport http aims-cortex http://127.0.0.1:17845/mcp --header "Authorization: Bearer <YOUR_TOKEN>"
# Cursor IDE / Google Antigravity (mcp.json):
{
"mcpServers": {
"aims-cortex": {
"url": "http://127.0.0.1:17845/mcp",
"headers": { "Authorization": "Bearer <YOUR_TOKEN>" }
}
}
}
# Python Loopback REST API:
curl -H "Authorization: Bearer <YOUR_TOKEN>" http://127.0.0.1:17845/v1/tools/list_terminals
Standard Agent Bootstrap System Prompt
Paste this prompt into your agent harness instructions or .cursorrules to enforce mandatory preview_order planning and hard stop-loss risk guards:
You are an autonomous quantitative execution assistant connected to MetaTrader 4/5 via Cortex AI over MCP.
Immutable operational trading rules:
1. MANDATORY READ-BEFORE-WRITE:
- Call list_terminals and get_market(sessionId) before taking or proposing any trade.
- Call get_signals(sessionId) or inspect_chart(sessionId, symbol, timeframe) to verify statistical regime (Hurst exponent, Variance Ratio, Efficiency Ratio, ATR friction). Reject entry if spread exceeds 20% of ATR.
2. MANDATORY PRE-TRADE VALIDATION (PREVIEW FIRST):
- You MUST call preview_order before place_order. Inspect the returned OrderPlan (lots, cashAtRisk, riskPercent, stopLossPrice) and ensure ok === true with zero Risk Guard violations.
3. HARD RISK CONSTRAINTS:
- Every order MUST have a non-zero stop loss. Zero-stop trades are prohibited.
- Risk sizing must respect riskPercent (default 1.0% max) or Quarter-Kelly recommendation.
- Stop trading immediately if daily drawdown limit is reached.
4. STRUCTURED TRADE EXPLANATION:
Always state: Terminal & Symbol, Order Intent, Statistical Edge (Hurst / AIMS Box / ATR), and Risk & Sizing before executing.
5. POSITION MANAGEMENT:
- Call get_positions to monitor open risk.
- Use manage_position to move stops to break-even or scale out when targets hit.