Event-driven, autonomous forex/gold trading system with multi-strategy signal generation, AI-assisted research, browser-based market intelligence, and comprehensive risk management.
NEXUS is built around a loosely coupled, event-driven agent architecture. Every module communicates exclusively through the EventBus — no agent ever imports or calls another agent directly. This makes the system modular, testable, and extensible.
| Principle | Description |
|---|---|
| Event Bus | All inter-agent communication goes through the central EventBus. Agents publish and subscribe; they never reference each other. |
| Risk First | Every signal must pass through the RiskEngine gatekeeper before execution. If risk rejects, the trade never happens. |
| Singleton Services | Core services (ConfigManager, EventBus, SystemStateManager, DatabaseManager, etc.) are singletons accessed via get_xxx() functions. |
| State Manager | A single source of truth for system state: phase, agent states, connections, positions, signals, risk status. |
| Graceful Degradation | Optional dependencies (FastAPI, MetaTrader5, Selenium) are handled gracefully — the system logs a warning and continues. |
┌──────────────┐ ┌───────────────┐ ┌──────────────┐
│ Market Data │────>│ Strategy │────>│ Risk Engine │
│ (MT5/API) │ │ Agents │ │ (GATEKEEPER) │
└──────────────┘ └───────┬───────┘ └──────┬───────┘
│ │
v v
┌─────────────┐ ┌──────────────┐
│ Signal │ │ APPROVED? │
│ Engine │ │ Yes ───────>│ Execution
└─────────────┘ │ No ────────>│ Rejected
└──────────────┘
│
v
┌──────────────┐
│ MT5 Broker │
│ Connector │
└──────┬───────┘
│
┌────────────┼────────────┐
v v v
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Position │ │Portfolio │ │Perform- │
│ Manager │ │ Manager │ │ance │
└──────────┘ └──────────┘ └──────────┘
NEXUS-AUTO-SYSTEM/
├── config/ # YAML configuration files
│ ├── system.yaml # MT5, trading, browser, dashboard, log, AI settings
│ ├── strategies.yaml # Strategy configs, timeframes, symbols, per-strategy params
│ └── risk.yaml # Risk limits, SL/TP defaults, warning thresholds
├── core/ # Framework layer (no trading logic)
│ ├── __init__.py
│ ├── config.py # ConfigManager singleton — loads YAML + env overrides
│ ├── event_bus.py # EventBus singleton — pub/sub inter-agent messaging
│ ├── event_types.py # Typed event definitions & enums
│ ├── event_schema.py # Event schema validation & serialization
│ ├── redis_bridge.py # Redis pub/sub bridge (Python → Redis)
│ ├── state_manager.py # SystemStateManager — centralized state & snapshot
│ └── system_manager.py # SystemManager — agent lifecycle & orchestration
├── database/
│ ├── __init__.py
│ ├── models.py # SQLAlchemy-style data models (SQLite)
│ └── repositories.py # DatabaseManager — all CRUD operations
├── agents/ # Autonomous agents (BaseAgent subclasses)
│ ├── __init__.py
│ ├── monitoring_agent.py # System health, heartbeat, error tracking
│ ├── market_intelligence_agent.py # Browser-based news & sentiment
│ ├── risk_agent.py # Risk monitoring & enforcement
│ ├── social_media_agent.py # Social sentiment analysis
│ ├── strategy_manager_agent.py # Strategy lifecycle management
│ └── trading_agent.py # Trade execution coordination
├── strategies/ # Trading strategy implementations
│ ├── __init__.py
│ ├── base_strategy.py # Abstract base for all strategies
│ ├── smc_strategy.py # Smart Money Concepts (order blocks, FVG, BOS)
│ ├── mean_reversion_strategy.py # Bollinger Band + RSI reversion
│ ├── breakout_strategy.py # Consolidation breakout detection
│ ├── harmonic_fib_strategy.py # Harmonic pattern + Fibonacci (Phase 2)
│ └── limited_grid_strategy.py # Controlled grid trading (Phase 2)
├── market/ # Market data & analysis
│ ├── __init__.py
│ ├── data_manager.py # OHLCV data fetching & caching
│ ├── indicators.py # Technical indicator calculations
│ ├── market_structure.py # Swing detection, structure analysis
│ └── mtf_engine.py # Multi-timeframe analysis engine
├── trading/ # Trade execution & risk
│ ├── __init__.py
│ ├── broker/
│ │ ├── __init__.py
│ │ └── mt5_connector.py # MetaTrader 5 bridge
│ ├── engine/
│ │ ├── __init__.py
│ │ ├── signal_engine.py # Signal lifecycle & validation
│ │ ├── execution_engine.py # Order execution (only after RISK_APPROVED)
│ │ ├── position_manager.py # Open position tracking & P&L
│ │ └── portfolio_manager.py # Balance, equity, margin, drawdown
│ ├── risk/
│ │ ├── __init__.py
│ │ ├── risk_engine.py # Central risk gatekeeper
│ │ ├── drawdown_guard.py # Max drawdown enforcement
│ │ ├── daily_loss_guard.py # Daily loss limit enforcement
│ │ └── correlation_checker.py # Correlated position checker
│ └── performance/
│ ├── __init__.py
│ └── performance_tracker.py # Win rate, profit factor, Sharpe, etc.
├── browser/ # Selenium-based web scrapers
│ ├── __init__.py
│ ├── chrome_manager.py # Chrome WebDriver lifecycle
│ ├── forexfactory.py # Economic calendar scraper
│ ├── investing.py # Investing.com market data
│ ├── tradingview.py # TradingView analysis scraping
│ ├── social_media.py # Social sentiment sources
│ └── whatsapp.py # WhatsApp alert integration
├── ai/ # AI/ML research module
│ ├── __init__.py
│ ├── feature_engine.py # Feature extraction for ML models
│ ├── meta_labeling.py # Meta-labeling for strategy signals
│ ├── signal_model.py # Signal quality prediction model
│ └── reinforcement/
│ ├── __init__.py
│ └── strategy_selector.py # RL-based strategy weight optimizer
├── dashboard/ # Web dashboard
│ ├── backend/
│ │ ├── __init__.py
│ │ ├── main.py # FastAPI app — REST + WebSocket
│ │ ├── api/
│ │ │ └── __init__.py
│ │ └── websocket/
│ │ └── __init__.py
│ ├── realtime/
│ │ └── node/ # Node.js + TypeScript real-time gateway
│ └── frontend/ # Next.js dashboard
├── launcher/ # System startup & watchdog
│ ├── __init__.py
│ ├── launcher.py # Main entry point
│ ├── startup_manager.py # Ordered service initialization
│ └── watchdog.py # Process monitoring & auto-restart
├── tests/ # Test suite
│ └── __init__.py
├── logs/ # Auto-generated log files
├── database/ # SQLite database files
├── requirements.txt # Python dependencies
├── launcher.py # System entry point (root level)
└── README.md # This file
Phase 1 focuses on a fully functional paper-trading system with:
- 3 strategies: Smart Money Concepts (SMC), Mean Reversion, Breakout
- 3 symbols: EURUSD, GBPUSD, XAUUSD
- Risk engine: Position sizing, daily loss limit, drawdown guard, correlation check
- Browser intelligence: ForexFactory calendar, Investing.com, TradingView
- Dashboard: Real-time WebSocket + REST API for monitoring
- Paper trading only:
live_tradingdefaults tofalse
pip install -r requirements.txtNote: MetaTrader5 requires Windows with MT5 terminal installed. On Linux/macOS, the system runs in simulation/paper mode.
Edit the YAML files in config/:
# Set your MT5 credentials
vim config/system.yamlOr use environment variables:
export NEXUS_MT5_LOGIN=12345678
export NEXUS_MT5_PASSWORD=your_password
export NEXUS_MT5_SERVER="BrokerName-Demo"
export NEXUS_MT5_PATH="/path/to/terminal64.exe"
export NEXUS_LOG_LEVEL=DEBUGpython launcher.pyThe system will:
- Load configuration from YAML files
- Initialize the database (SQLite)
- Connect to MT5 (if enabled and available)
- Start all agents in priority order
- Begin the main trading loop
- Serve the dashboard at
http://127.0.0.1:8900
Once running, the dashboard is available at:
- API:
http://127.0.0.1:8900/docs(Swagger UI) - WebSocket:
ws://127.0.0.1:8900/ws
Key endpoints:
| Endpoint | Method | Description |
|---|---|---|
/api/status |
GET | Full system status snapshot |
/api/portfolio |
GET | Balance, equity, margin, drawdown |
/api/positions |
GET | Open positions with P&L |
/api/signals |
GET | Active/pending signals |
/api/risk |
GET | Risk engine state & guard statuses |
/api/performance?days=30 |
GET | Performance report |
/api/agents |
GET | Agent states & connections |
/api/event-stats |
GET | Event bus statistics |
/api/trading/pause |
POST | Emergency pause all trading |
/api/trading/resume |
POST | Resume trading after pause |
/api/trading/close-all |
POST | Close all open positions |
/api/config |
GET | Current config (passwords masked) |
/ws |
WS | Real-time state updates |
All configuration lives in the config/ directory:
| File | Section | Description |
|---|---|---|
system.yaml |
mt5 |
MetaTrader 5 connection settings |
system.yaml |
trading |
Live/paper mode, slippage, magic number |
system.yaml |
browser |
Chrome automation settings |
system.yaml |
dashboard |
Host, port, WebSocket heartbeat |
system.yaml |
log |
Log level, format, rotation |
system.yaml |
ai |
AI mode, cache size, backtest window |
strategies.yaml |
strategies |
Timeframes, enabled strategies, symbols |
strategies.yaml |
strategies.smc |
SMC order block & FVG params |
strategies.yaml |
strategies.mean_reversion |
BB & RSI parameters |
strategies.yaml |
strategies.breakout |
Consolidation & volume params |
risk.yaml |
risk |
All risk limits & thresholds |
| Variable | Maps To | Example |
|---|---|---|
NEXUS_MT5_LOGIN |
mt5.login |
12345678 |
NEXUS_MT5_PASSWORD |
mt5.password |
secret |
NEXUS_MT5_SERVER |
mt5.server |
Broker-Demo |
NEXUS_MT5_PATH |
mt5.path |
C:/MT5/terminal64.exe |
NEXUS_LIVE_TRADING |
trading.live_trading |
true |
NEXUS_DEMO |
mt5.demo |
true |
NEXUS_LOG_LEVEL |
log.level |
DEBUG |
NEXUS_DASHBOARD_PORT |
dashboard.port |
8900 |
Environment variables override YAML values at runtime.
-
No direct agent imports — Agents communicate exclusively through the
EventBus. Never import one agent from another. -
Risk is the gatekeeper — No trade is ever executed without
RISK_APPROVED. TheExecutionEngineonly acts on approved signals. -
Singleton access — Always use
get_config(),get_event_bus(),get_state_manager(), etc. Never instantiate core services directly. -
State changes emit events —
SystemStateManagerpublishes events for every significant state transition (phase change, agent start/stop, position open/close). -
Graceful degradation — The system must remain functional when optional dependencies (MT5, browser, dashboard) are unavailable.
-
Thread safety — The event bus and state manager use locks for thread-safe operation across the async main loop.
- IMPLEMENTED: Core framework (config, event bus, state manager, system manager, event schema)
- IMPLEMENTED: Database layer (SQLite, repositories, models, singleton pattern)
- IMPLEMENTED: MT5 broker connector
- IMPLEMENTED: 3 trading strategies (SMC, Mean Reversion, Breakout)
- IMPLEMENTED: Risk engine with all guards (7 checks)
- IMPLEMENTED: Execution engine with 10 pre-execution safety checks
- IMPLEMENTED: Position & portfolio management
- IMPLEMENTED: Performance tracking
- IMPLEMENTED: Browser automation (DrissionPage: ForexFactory, Investing, TradingView)
- IMPLEMENTED: Dashboard backend REST API (FastAPI)
- IMPLEMENTED: YAML configuration system
- TESTED: 39 unit tests (core, trading, negative tests) - ALL PASS
- TESTED: 72 Python files, 0 syntax errors
- IMPLEMENTED: Limited Grid strategy (fixed signal flooding bug)
- IMPLEMENTED: Harmonic Fibonacci strategy (fixed pattern scan bugs)
- IMPLEMENTED: Redis bridge (Python → Redis pub/sub)
- IMPLEMENTED: Node.js + TypeScript real-time gateway
- IMPLEMENTED: Next.js dashboard frontend
- PARTIALLY_IMPLEMENTED: Dashboard real-time (Redis → Node → WS → Next.js flow created, integration pending live Redis)
- IMPLEMENTED: AI meta-labeling for signal quality
- SCAFFOLDED: Strategy weight optimization (rule-based, not RL yet)
- SCAFFOLDED: WhatsApp trade notifications
- SCAFFOLDED: Live RL strategy selection (rule-based Phase 1)
- SCAFFOLDED: Multi-timeframe signal confluence scoring
- NOT_STARTED: Automated strategy parameter optimization
- NOT_STARTED: News impact quantification model
- NOT_STARTED: Multi-broker support
- NOT_STARTED: Cloud deployment (Docker, AWS)
- NOT_STARTED: System monitoring & alerting
- NOT_STARTED: Failsafe mechanisms & circuit breakers
- NOT_STARTED: Multi-account management
- NOT_STARTED: Strategy marketplace
- NOT_STARTED: Advanced backtesting with walk-forward
- NOT_STARTED: API for external integrations
Private project. All rights reserved.