Institutional-grade automated trading system implementing Ray Dalio's All-Weather Portfolio allocation
Automated trading system for MetaTrader 5 with:
- 📊 Ray Dalio Portfolio Allocation - Economic scenario-based position sizing across 8 assets (18% XAUUSD, 15% USDCHF/AUDUSD, 13% GBPUSD, 12% EURUSD/XAGUSD, 8% USDJPY, 7% EURJPY)
- 🛡️ 6-Layer Entry Filters - Validates ATR, Angle, Price, Candle Direction, EMA Ordering, and Time before every trade
- 🎨 Real-Time GUI - Live charts, EMA overlays, strategy states, and comprehensive monitoring
- 📈 4-Phase State Machine - SCANNING → ARMED → WINDOW_OPEN → ENTRY with pullback confirmation
- 💰 MT5 Broker Integration - Dynamic position sizing using broker-specific tick values (not hardcoded pip values)
Trading Assets: EURUSD, GBPUSD, XAUUSD, AUDUSD, XAGUSD, USDCHF, EURJPY, USDJPY (M5 timeframe)
# Clone repository
git clone https://github.com/yourusername/mt5_live_trading_bot.git
cd mt5_live_trading_bot
# Automated setup (Windows PowerShell - Recommended)
.\setup.ps1
# OR Manual setup
python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt# Copy MT5 credentials template
copy config\mt5_credentials_template.json config\mt5_credentials.json
# Edit with your MT5 account details
# (account number, password, server)# Start the trading bot
python advanced_mt5_monitor_gui.py
# OR run executable (Windows)
dist\MT5_Trading_Bot.exeEconomic scenario-based position sizing protecting against inflation, deflation, growth, and recession:
| Asset | Allocation | Economic Role | Example Risk* |
|---|---|---|---|
| XAUUSD | 18% | Inflation hedge (gold) | $90.14 |
| USDCHF | 15% | Deflation hedge (safe haven) | $75.12 |
| GBPUSD | 13% | Balanced growth | $65.10 |
| EURUSD | 12% | Balanced growth | $60.09 |
| XAGUSD | 12% | Commodity exposure | $60.09 |
| AUDUSD | 15% | Commodity currency | $75.12 |
| USDJPY | 8% | JPY carry trade | $40.06 |
| EURJPY | 7% | JPY cross exposure | $35.05 |
*Based on $50,078 portfolio with 1% risk per allocation
Key Benefit: Maximum 1% total portfolio risk even if all 8 assets signal simultaneously (vs 8% with equal weighting)
📖 Full Documentation: DALIO_ALLOCATION_SYSTEM.md
Every signal must pass ALL filters to prevent false entries. Filters are applied in two stages:
Stage 1: Crossover Validation (Scanning)
EMA Crossover Detected
↓
✅ [1] ATR Filter → Volatility in valid range?
✅ [2] Angle Filter → EMA slope meets requirements?
✅ [3] Price Filter → Price aligned with trend?
✅ [4] Candle Filter → Previous candle confirms momentum?
✅ [5] EMA Ordering → Multi-EMA sequence correct?
↓
ALL PASSED → ARMED State → Pullback → Window
ANY FAILED → REJECTED (stay in SCANNING)
Stage 2: Entry Validation (Window Breakout)
Window Breakout Detected
↓
✅ [6] Time Filter → Within trading hours?
↓
PASSED → ENTRY
FAILED → SKIP (Return to SCANNING)
Impact: Reduces entries from ~240/month to ~2-3/month per asset (matches backtesting)
📊 Filter Configuration: FILTER_CONFIGURATION.md
┌─────────────────────────────────────────────────────────────┐
│ SCANNING → Monitoring for valid crossovers (6-layer check) │
└─────────────────────────────────────────────────────────────┘
↓ All filters pass
┌─────────────────────────────────────────────────────────────┐
│ ARMED → Waiting for pullback confirmation (1-3 candles) │
│ ⚠️ Global invalidation: Counter-crossover resets state │
└─────────────────────────────────────────────────────────────┘
↓ Pullback complete
┌─────────────────────────────────────────────────────────────┐
│ WINDOW_OPEN → 2-sided breakout window active (1-20 bars) │
│ Success boundary → Execute trade │
│ Failure boundary → Reset to SCANNING │
└─────────────────────────────────────────────────────────────┘
↓ Breakout detected
┌─────────────────────────────────────────────────────────────┐
│ ENTRY → Trade executed with ATR-based SL/TP │
└─────────────────────────────────────────────────────────────┘
📚 Case Studies: COMPREHENSIVE_STRATEGY_VERIFICATION.md
NEW FEATURE: Expanded portfolio to 8 assets with JPY pair support
New Assets:
- 🇯🇵 EURJPY - 7% allocation, JPY cross exposure
- 🇯🇵 USDJPY - 8% allocation, JPY carry trade
Technical Details:
- JPY pairs use 3 decimal places (vs 5 for standard forex)
- Pip value = 0.01 (vs 0.0001 for standard pairs)
- Scale factor = 100 for proper pip calculations
- Rebalanced all allocations to maintain 100% total
Strategy Files:
sunrise_ogle_eurjpy.py- EURJPY LONG-only strategysunrise_ogle_usdjpy.py- USDJPY LONG-only strategy
CRITICAL UPDATE: Added UTC offset selector to handle Broker Time vs UTC mismatches (Daylight Savings Time)
New Features:
- 🕒 UTC Offset Selector: GUI dropdown to select Broker Time (UTC+1 / UTC+2)
- 🌍 Internal Conversion: All strategy time filters now convert broker time to UTC automatically
- 🔧 EURUSD Config: Updated to match backtest settings (Pullback + ATR)
Why this matters: Ensures trading hours (e.g., 08:00-16:00 UTC) are respected regardless of broker server time or DST changes.
CRITICAL BUG FIXED: Bot was ignoring LONG_USE_PULLBACK_ENTRY configuration flag
Impact:
- EURUSD: Should enter immediately on crossover (flag = False) but was forced into pullback mode ❌
- XAUUSD: Showing 2 pullback candles when config requires 3 ❌
Solution:
- Added flag check with branching logic (STANDARD vs PULLBACK mode)
- Created
_execute_entry()method for immediate entries - Enhanced configuration logging at startup
📖 Full Analysis: PULLBACK_SYSTEM_FIX.md
CRITICAL BUG FIXED: Now uses MT5 broker-specific tick values instead of hardcoded pip values
Before (BROKEN):
# Hardcoded standard lot assumptions
GBPUSD: Risk $22.70 instead of $80.13 (3.53x too small) ❌
XAGUSD: Risk $0.46 instead of $75.12 (163x too small!) ❌After (FIXED):
# Dynamic broker-specific calculation
tick_value = mt5.symbol_info(symbol).trade_tick_value # Real broker specs
value_per_point = tick_value × (point / tick_size)
lot_size = risk_amount / (sl_distance × value_per_point) ✅Enhanced Logging: Every trade now shows 5 sections:
- 📋 Broker specifications (contract size, tick value, digits)
- 💰 Dalio allocation (balance, asset %, risk amount)
- 🎯 Stop loss (SL distance in points, ATR multiplier)
- 🧮 Lot size calculation (step-by-step formula)
- ✅ Risk verification (confirms calculated risk matches expected)
📖 Technical Details: POSITION_SIZING_FIX_V2.md
CRITICAL BUG FIXED: ATR filter was not validating entries due to missing dataframe integration
Impact: Reduced entries from ~240/month to ~2-3/month per asset (matches backtesting)
📖 Details: ATR_BUG_FIX_COMPLETE.md
mt5_live_trading_bot/
├── advanced_mt5_monitor_gui.py # Main bot (3,500+ lines)
├── requirements.txt # Python dependencies
├── setup.ps1 # Automated setup
├── build_exe.bat # Build Windows executable
│
├── config/ # Configuration
│ ├── mt5_credentials_template.json
│ └── mt5_credentials.json # (your credentials - gitignored)
│
├── strategies/ # Asset-specific parameters
│ ├── sunrise_ogle_eurusd.py # EURUSD strategy (READ-ONLY)
│ ├── sunrise_ogle_gbpusd.py # GBPUSD strategy (READ-ONLY)
│ ├── sunrise_ogle_xauusd.py # XAUUSD strategy (READ-ONLY)
│ ├── sunrise_ogle_audusd.py # AUDUSD strategy (READ-ONLY)
│ ├── sunrise_ogle_xagusd.py # XAGUSD strategy (READ-ONLY)
│ ├── sunrise_ogle_usdchf.py # USDCHF strategy (READ-ONLY)
│ ├── sunrise_ogle_eurjpy.py # EURJPY strategy (READ-ONLY)
│ └── sunrise_ogle_usdjpy.py # USDJPY strategy (READ-ONLY)
│
├── testing/ # Test suite
│ ├── test_setup.py # Verify installation
│ ├── test_monitor_components.py # GUI tests
│ ├── test_mt5_order.py # Order execution test
│ ├── check_broker_specs.py # Broker verification
│ ├── test_position_sizing.py # Position sizing tests
│ ├── test_jpy_entries.py # JPY pairs validation tests
│ └── verify_all_symbols.py # Symbol configuration check
│
├── docs/ # Documentation
│ ├── README.md # Documentation index
│ ├── START_TESTING_HERE.md # Quick start guide
│ └── archive/ # Historical docs
│
└── logs/ # Application logs (gitignored)
- DALIO_QUICK_REFERENCE.md - Position sizing quick reference
- FILTER_CONFIGURATION.md - Entry filter matrix
- START_TESTING_HERE.md - Testing guide
- DALIO_ALLOCATION_SYSTEM.md - Complete Ray Dalio implementation
- COMPREHENSIVE_STRATEGY_VERIFICATION.md - 1,500+ line verification (MT5 vs Backtrader)
- STRATEGY_FILES_POLICY.md - READ-ONLY policy for strategy files
- strategy_comparison.md - Source of Truth for strategy parameters and logic
- POSITION_SIZING_FIX_V2.md - Position sizing fix (MT5 tick value integration)
- PULLBACK_SYSTEM_FIX.md - Pullback flag check implementation
- DEEP_STRATEGY_ANALYSIS_NOV14.md - 25-page session analysis
- docs/ - Additional guides (EMA setup, pullback fixes, etc.)
# 1. Installation check
cd testing
python test_setup.py
# 2. Broker specifications
python check_broker_specs.py
# 3. Position sizing validation
python test_position_sizing.py
# 4. Symbol configuration check
python verify_all_symbols.pycd testing
python test_mt5_order.py # Basic order testAlways use demo accounts for testing!
{
"account": 12345678,
"password": "YourPassword",
"server": "YourBroker-Demo"
}Each strategy file in strategies/ contains:
- EMA periods (Fast, Medium, Slow, Filter)
- ATR multipliers (SL: 4.5x, TP: 6.5x default)
- Pullback requirements (1-3 candles)
- Window duration (1-20 bars)
- Trading hours (UTC)
- Filter thresholds (ATR, Angle, etc.)
- ✅ Ray Dalio Allocation - Maximum 1% portfolio risk across all assets
- ✅ 6-Layer Filters - Validates every signal before entry
- ✅ ATR-Based SL/TP - Dynamic stop loss (4.5x ATR) and take profit (6.5x ATR)
- ✅ MT5 Broker Integration - Uses actual tick values (not hardcoded)
- ✅ Global Invalidation - Counter-trend crossovers reset armed states
- ✅ Duplicate Prevention - Checks existing positions before entry
- ✅ Time Filters - Trading hour restrictions per asset
- Asset Dashboard - Price, state, pullback count, window status
- Live Charts - Candlesticks with EMA overlays (Fast, Medium, Slow, Filter)
- Strategy States - Color-coded phase indicators (SCANNING, ARMED, WINDOW_OPEN)
- Configuration Viewer - Complete strategy parameters and filter details
- Terminal Logging - Real-time event log with timestamps
- Symbol Selection - Switch between 8 monitored assets
- Timeframe - M5 (5-minute candles)
- Indicators - EMA overlays, volume bars
- Window Markers - Shows breakout boundaries when window active
✓ Ensure MT5 terminal is running and logged in
✓ Verify credentials in config/mt5_credentials.json
✓ Check MetaTrader5 Python package installed
✓ Restart MT5 terminal
✓ Confirm market is open for selected assets
✓ Check if price data streaming (see logs/)
✓ Review filter thresholds (may be too strict)
✓ Verify strategy files loaded (check terminal)
✓ Run testing/check_broker_specs.py
✓ Verify MT5 account balance fetched correctly
✓ Check logs for broker specifications section
✓ Confirm tick_value matches broker's contract specs
Contributions welcome! Please:
- Fork the repository
- Create feature branch (
git checkout -b feature/AmazingFeature) - Read STRATEGY_FILES_POLICY.md - Strategy files are READ-ONLY
- Test on demo account thoroughly
- Document changes and include test results
- Submit Pull Request
MIT License - see LICENSE file for details.
This software is for educational purposes only.
Trading financial instruments carries high risk and may not be suitable for all investors. No representation is made that any account will achieve profits or losses similar to those shown. Past performance is not indicative of future results.
The developers assume no responsibility for your trading results. Use at your own risk.
- MetaTrader 5 Python API
- Ray Dalio's All-Weather Portfolio principles
- mplfinance for financial charts
- Backtrader for strategy development
⚡ Happy Trading! Trade with institutional-grade risk management!
