Skip to content

Repository files navigation

NEXUS AUTO SYSTEM

Event-driven, autonomous forex/gold trading system with multi-strategy signal generation, AI-assisted research, browser-based market intelligence, and comprehensive risk management.


Architecture Overview

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.

Core Principles

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.

Trading Flow

┌──────────────┐     ┌───────────────┐     ┌──────────────┐
│  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      │
                              └──────────┘ └──────────┘ └──────────┘

Directory Structure

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 Scope

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_trading defaults to false

Quick Start

1. Install Dependencies

pip install -r requirements.txt

Note: MetaTrader5 requires Windows with MT5 terminal installed. On Linux/macOS, the system runs in simulation/paper mode.

2. Configure

Edit the YAML files in config/:

# Set your MT5 credentials
vim config/system.yaml

Or 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=DEBUG

3. Run

python launcher.py

The system will:

  1. Load configuration from YAML files
  2. Initialize the database (SQLite)
  3. Connect to MT5 (if enabled and available)
  4. Start all agents in priority order
  5. Begin the main trading loop
  6. Serve the dashboard at http://127.0.0.1:8900

4. Dashboard

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

Configuration Guide

YAML Files

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

Environment Variables

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.


Key Architectural Rules

  1. No direct agent imports — Agents communicate exclusively through the EventBus. Never import one agent from another.

  2. Risk is the gatekeeper — No trade is ever executed without RISK_APPROVED. The ExecutionEngine only acts on approved signals.

  3. Singleton access — Always use get_config(), get_event_bus(), get_state_manager(), etc. Never instantiate core services directly.

  4. State changes emit events — SystemStateManager publishes events for every significant state transition (phase change, agent start/stop, position open/close).

  5. Graceful degradation — The system must remain functional when optional dependencies (MT5, browser, dashboard) are unavailable.

  6. Thread safety — The event bus and state manager use locks for thread-safe operation across the async main loop.


Development Roadmap

Phase 1 — Foundation

  • 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

Phase 2 — Enhancement

  • 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

Phase 3 — Intelligence

  • 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

Phase 4 — Resilience

  • NOT_STARTED: Multi-broker support
  • NOT_STARTED: Cloud deployment (Docker, AWS)
  • NOT_STARTED: System monitoring & alerting
  • NOT_STARTED: Failsafe mechanisms & circuit breakers

Phase 5 — Scale

  • NOT_STARTED: Multi-account management
  • NOT_STARTED: Strategy marketplace
  • NOT_STARTED: Advanced backtesting with walk-forward
  • NOT_STARTED: API for external integrations

License

Private project. All rights reserved.

About

NEXUS AUTO SYSTEM is an autonomous forex and gold trading platform built on an event-driven agent architecture. It combines multi-strategy signal generation, AI-assisted research, browser-based market intelligence,

Topics

Resources

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages