XAU/USD Scalping AI - Hybrid MA Crossover Strategy
A professional XAU/USD scalping system that combines rule-based moving average crossover signals with advanced backtesting and live trading capabilities. Achieves consistent monthly profits through trend-following scalping with robust risk management.
π― Key Features
- Hybrid Strategy: Rule-based MA crossover with AI-optimized parameters
- Advanced Backtesting: Realistic trading conditions with slippage, commissions, and position sizing
- Live Trading: MetaTrader 5 integration with automated order execution
- Risk Management: Dynamic position sizing, trailing stops, and capital protection
- Multi-Timeframe: Optimized for 1-hour data with intraday scalping
- Performance Tracking: Comprehensive metrics and trade logging
- Model Sharing: Pre-trained models available on Hugging Face Hub
π Performance Results
Optimal Configuration (2022-2025 Forward Test):
- Total Return: 4,163.14% (10,000 β 416,314)
- Annualized Return: ~416%
- Trades: 1,392 total (mix of long/short positions)
- Win Rate: 70%+ (short scalps), 60%+ (long positions)
- Risk Parameters:
- Long TP: 1,000 points, SL: 400 points
- Short TP: 10 points, SL: 20 points
- Position Size: 2% long, 0.02% short
- Monthly Target: 35,000 THB (~$1,000 USD) achievable
Risk Metrics:
- Maximum Drawdown: <15% (optimal risk threshold)
- Sharpe Ratio: >2.0
- Profit Factor: >1.5
π Quick Start
Prerequisites
- Python 3.8+
- MetaTrader 5 account (for live trading)
- Hugging Face account (for model access)
Installation
- Clone the repository:
git clone https://github.com/yourusername/xauusd-scalping-ai.git
cd xauusd-scalping-ai
- Create virtual environment:
python -m venv .venv
.\.venv\Scripts\Activate.ps1
- Install dependencies:
pip install -r requirements.txt
- Configure environment:
cp .env.example .env
# Edit .env with your API keys and trading credentials
Download Models from Hugging Face
from huggingface_hub import hf_hub_download
import joblib
# Download models
models = ['entry_clf.joblib', 'lstm.pt', 'transformer.pt', 'xgb.model', 'meta.joblib']
for model in models:
hf_hub_download(repo_id="JonusNattapong/xauusd-scalping-models",
filename=model,
local_dir="./models")
π Usage
Backtesting
Run comprehensive backtests with different parameter combinations:
# Grid search optimization
python scripts/forward_hybrid_2024_2025.py
# Small capital testing ($100-$1,000)
python scripts/backtest_small_capital.py
# Custom backtest
python scripts/run_backtests.py
Training (Optional)
Train new models on updated data:
# Advanced training with hyperparameter tuning
python scripts/advanced_train.py
# Basic training
python src/train.py
Live Trading
β οΈ WARNING: Live trading involves real financial risk. Start with small positions.
Setup MT5:
- Install MetaTrader 5 platform
- Configure your trading account in
.env - Ensure MT5 is running before starting live trading
Start live trading:
python scripts/live_trading.py
Features:
- Automated signal generation
- Order execution with slippage protection
- Real-time position monitoring
- Telegram notifications
- Emergency stop functionality
Data Analysis
# Generate performance plots
python scripts/generate_plots.py
# Compute detailed metrics
python scripts/compute_metrics.py
# Test data integrity
python scripts/test_data.py
ποΈ Project Structure
βββ data/ # Historical price data
β βββ XAU_1h_data.jsonl # Primary 1-hour data
β βββ *.jsonl # Multi-timeframe data
βββ models/ # Pre-trained models
β βββ entry_clf.joblib # Entry signal classifier
β βββ lstm.pt # LSTM model
β βββ transformer.pt # Transformer model
β βββ xgb.model # XGBoost model
β βββ meta.joblib # Meta-model
βββ output/ # Backtest results & analysis
β βββ forward_hybrid_summary_*.csv
β βββ best_trades.csv
β βββ *.npy # Forward test arrays
βββ scripts/ # Executable scripts
β βββ live_trading.py # MT5 live trading
β βββ forward_hybrid_*.py # Backtesting
β βββ generate_plots.py # Visualization
β βββ *.py # Analysis tools
βββ src/ # Core source code
β βββ backtest.py # Advanced backtest engine
β βββ data_loader.py # Data loading utilities
β βββ features.py # Feature engineering
β βββ models.py # Model definitions
β βββ utils.py # Helper functions
βββ tests/ # Unit tests
βββ white_paper.pdf # Comprehensive documentation
βββ requirements.txt # Python dependencies
βββ .env # Environment variables
βββ README.md # This file
π Strategy Overview
Core Logic
- Primary Signal: MA(5) vs MA(20) crossover on 1-hour charts
- Long Positions: One large position per day (1000-3000 point targets)
- Short Scalps: Multiple intraday positions (10-50 point targets)
- Session Focus: London/NYC trading sessions for optimal liquidity
Risk Management
- Position Sizing: Percentage-based allocation (0.02%-2% per trade)
- Stop Loss: Fixed points with trailing stop options
- Maximum Holding: Long positions β€24 hours, shorts β€3 hours
- Capital Protection: 15% maximum drawdown threshold
- Diversification: Mix of long-term and short-term positions
Technical Indicators
- Moving Averages (5, 20 periods)
- RSI for overbought/oversold confirmation
- MACD for trend strength validation
- ATR for volatility adjustment
π§ Configuration
Environment Variables (.env)
# Hugging Face
HF_TOKEN=your_hf_token
# Trading APIs
EXNESS_API_KEY=your_api_key
EXNESS_SERVER_API=Exness-MT5Trial
EXNESS_PASSWORD_API=your_password
# Data APIs
FINNHUB_API_KEY=your_key
GOLDAPI_KEY=your_key
ALPHA_VANTAGE_KEY=your_key
TWELVE_DATA_KEY=your_key
# Notifications
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_ID=your_chat_id
# Paths
DATA_PATH=data/
MODEL_PATH=models/
Backtest Parameters
Key parameters in src/backtest.py:
ENTRY_THRESH: Signal confidence thresholdSTOP_LOSS: Stop loss in pointsTAKE_PROFIT: Take profit in pointsPOSITION_SIZE: Capital allocation percentage
π€ Models & AI Components
Available Models
- Entry Classifier: XGBoost-based signal confirmation
- LSTM Model: Sequential pattern recognition
- Transformer Model: Attention-based feature extraction
- Ensemble Meta-Model: Combined predictions
Model Performance
- Accuracy: 65-75% signal prediction
- Precision: 70%+ for profitable signals
- Recall: 60%+ for trade opportunities
Download from: https://huggingface.co/JonusNattapong/xauusd-scalping-models
π Documentation
- White Paper: Comprehensive strategy documentation
- API Reference: Code documentation
- Backtest Results: Detailed performance analysis
π§ͺ Testing
Run the test suite:
python -m pytest tests/
Or run smoke tests:
python scripts/smoke_test.py
π€ Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Follow PEP 8 style guidelines
- Add tests for new features
- Update documentation
- Ensure backward compatibility
βοΈ License
This project is licensed under the MIT License - see the LICENSE file for details.
β οΈ Disclaimer
This software is for educational and research purposes only. Trading cryptocurrencies and forex involves substantial risk of loss and is not suitable for every investor. Past performance does not guarantee future results. Please trade responsibly and never risk more than you can afford to lose.
π Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Models: Hugging Face Hub
π Acknowledgments
- Data sourced from reliable financial providers
- Built with MetaTrader 5 API
- Models hosted on Hugging Face Hub
- Inspired by quantitative trading research
Happy Trading! ππ