A production-ready, fully autonomous quantitative trading system for Gold/USD (XAU/USD) with Python and Rust implementations. Features news sentiment analysis, real-time notifications, database logging, and professional broker integrations.
- π Real-Time Web Dashboard - Professional monitoring with WebSocket live updates
- π 7 Advanced Strategies - ATR Volatility, Multi-Timeframe, Ensemble, and more
- π Strategy Comparison Tool - Backtest all strategies side-by-side
- π Interactive Charts - Equity curve, drawdown, and strategy performance visualization
- β OANDA Broker Integration - Professional forex trading with demo & live modes
- β News Sentiment Analysis - Yahoo Finance news with Gold-specific AI sentiment
- β Telegram & Email Alerts - Real-time notifications for all trading events
- β PostgreSQL Logging - Complete trade history and performance analytics
- β Health Monitoring - Auto-recovery and system health checks
- β Rust Performance - 10-100x faster than Python with async execution
- π€ Fully Autonomous - Runs 24/7 with no manual intervention
- π Multi-Indicator Strategy - MA, RSI, Bollinger Bands + News Sentiment
- π± OANDA Integration - Professional REST API v20 broker (demo & live)
- π‘οΈ Risk Management - Position sizing, stop-loss, take-profit, drawdown limits
- π Backtesting - Historical validation with slippage and commission
- π° News Sentiment - Fetches & analyzes Gold/USD news from Yahoo Finance
- π§ 60+ Keywords - Financial sentiment lexicon with Gold-specific terms
- βοΈ Signal Blending - Combines technical indicators with news sentiment
- π Real-time Analytics - Live performance tracking and equity curves
- π Real-Time Dashboard - Web UI with live charts and WebSocket updates
- π Interactive Visualizations - Equity curve, drawdown, strategy comparison
- π± Telegram Bot - Instant alerts with emoji status indicators
- π§ HTML Emails - Beautiful formatted trade notifications
- πΎ PostgreSQL - Persistent storage for trades and equity curve
- β€οΈ Health Checks - Automatic error recovery and heartbeat monitoring
- β‘ Rust Speed - 10-100x faster with zero-cost abstractions
- π§ Easy Setup - One-command installation script
- π Complete Docs - Step-by-step setup guide
- π§ͺ Well Tested - Unit tests and integration tests
This directory contains the Python implementation. For the high-performance Rust version, see rust/ directory.
- Autonomous Trading: Continuously monitors markets and executes trades automatically
- Advanced Strategy: Momentum-based strategy using multiple technical indicators:
- Moving Average Crossover (Fast/Slow MA)
- Relative Strength Index (RSI)
- Bollinger Bands
- Volume confirmation
- Trend strength analysis
- Comprehensive Risk Management:
- Position sizing based on risk parameters
- Stop loss and take profit levels
- Trailing stops
- Maximum drawdown limits
- Daily loss limits
- Backtesting Framework: Test strategies on historical data with detailed performance metrics
- Paper Trading: Test the system in simulation mode before going live
- Configurable: YAML-based configuration for easy customization
- Logging: Comprehensive logging with daily rotation and error tracking
- Python 3.8+
- See
requirements.txtfor all dependencies
# Clone the repository
git clone <repository-url>
cd quant-trading
# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtCopy the example environment file and configure your API keys:
cp .env.example .env
# Edit .env with your API keysCustomize the trading parameters in config/config.yaml:
- Adjust strategy parameters (MA periods, RSI thresholds, etc.)
- Set risk management limits
- Configure capital and position sizing
- Set data source and intervals
Test the strategy on historical data:
python run_backtest.pyThis will:
- Fetch historical Gold/USD data
- Run the strategy on past data
- Generate performance metrics
- Save results to
results/directory - Display equity curve and trading signals
python run_autonomous_trader.py --mode paperpython run_autonomous_trader.py --mode livepython run_autonomous_trader.py --oncequant-trading/
βββ src/
β βββ data/ # Data fetching and caching
β β βββ data_fetcher.py # Market data acquisition
β β βββ data_cache.py # Data caching utilities
β βββ strategies/ # Trading strategies
β β βββ base_strategy.py # Base strategy class
β β βββ gold_momentum_strategy.py # Gold momentum strategy
β βββ backtesting/ # Backtesting framework
β β βββ backtest_engine.py # Backtesting engine
β β βββ performance_metrics.py # Performance calculations
β βββ execution/ # Order execution
β β βββ autonomous_trader.py # Autonomous trading engine
β β βββ order_executor.py # Order execution logic
β βββ risk_management/ # Risk management
β β βββ risk_manager.py # Risk control system
β β βββ position_sizer.py # Position sizing utilities
β βββ utils/ # Utilities
β βββ config_loader.py # Configuration management
β βββ logger.py # Logging setup
βββ config/
β βββ config.yaml # Main configuration file
βββ data/ # Data storage
β βββ raw/ # Raw market data
β βββ processed/ # Processed data
βββ logs/ # Log files
βββ results/ # Backtest results
βββ notebooks/ # Jupyter notebooks for analysis
βββ tests/ # Unit tests
βββ run_backtest.py # Backtest runner
βββ run_autonomous_trader.py # Autonomous trader runner
βββ requirements.txt # Python dependencies
βββ .env.example # Example environment variables
βββ README.md # This file
The strategy uses multiple technical indicators to identify momentum in Gold/USD prices:
-
Moving Average Crossover:
- Fast MA (20-period) crosses Slow MA (50-period)
- Generates primary trend signals
-
RSI (Relative Strength Index):
- Identifies overbought (>70) and oversold (<30) conditions
- Confirms momentum and potential reversals
-
Bollinger Bands:
- Measures volatility
- Identifies breakout and mean reversion opportunities
-
Volume Confirmation:
- Confirms signals with volume analysis
- Filters false breakouts
-
Trend Strength:
- Measures the strength of the current trend
- Helps determine position sizing
Signals are generated based on a scoring system:
- Multiple indicators must align for a trade signal
- Buy signal requires 3+ bullish indicators
- Sell signal requires 3+ bearish indicators
- Otherwise, hold position
The system implements comprehensive risk controls:
- Position Sizing: Based on risk per trade (default 1% of capital)
- Stop Loss: Automatic stop loss at 2% per trade
- Take Profit: Automatic take profit at 5% per trade
- Trailing Stop: Dynamic trailing stop at 1.5%
- Maximum Drawdown: System halts at 15% drawdown
- Daily Loss Limit: Maximum 5% loss per day
- Position Limits: Maximum 3 concurrent positions
The backtesting framework calculates:
- Return Metrics: Total return, annualized return, daily returns
- Risk Metrics: Sharpe ratio, Sortino ratio, Calmar ratio, max drawdown
- Win/Loss Metrics: Win rate, profit factor, average win/loss
- Trade Statistics: Number of trades, consecutive wins/losses, trade duration
from src.utils.config_loader import load_config
from src.data.data_fetcher import DataFetcher
from src.strategies.gold_momentum_strategy import GoldMomentumStrategy
from src.backtesting.backtest_engine import BacktestEngine
# Load configuration
config = load_config()
# Initialize components
data_fetcher = DataFetcher(config)
strategy = GoldMomentumStrategy(config)
backtest = BacktestEngine(strategy, config)
# Fetch data and run backtest
data = data_fetcher.fetch_historical_data(start_date='2020-01-01', end_date='2024-12-31')
results = backtest.run(data)
# View results
print(results['metrics'])
backtest.plot_results()from src.utils.config_loader import load_config
from src.strategies.gold_momentum_strategy import GoldMomentumStrategy
from src.execution.autonomous_trader import AutonomousTrader
# Load configuration
config = load_config()
config['trading']['trading_mode'] = 'paper' # Use 'live' for real trading
# Initialize and start
strategy = GoldMomentumStrategy(config)
trader = AutonomousTrader(strategy, config)
trader.start()Key configuration parameters in config/config.yaml:
trading:
symbol: "GC=F" # Gold Futures
initial_capital: 100000 # Starting capital
position_size: 0.1 # 10% per trade
trading_mode: "paper" # paper or live
strategy:
fast_ma: 20 # Fast moving average
slow_ma: 50 # Slow moving average
rsi_period: 14 # RSI period
rsi_oversold: 30 # RSI oversold threshold
rsi_overbought: 70 # RSI overbought threshold
risk:
max_drawdown_pct: 15 # Maximum drawdown
stop_loss_pct: 2 # Stop loss per trade
take_profit_pct: 5 # Take profit per trade
risk_per_trade_pct: 1 # Risk per trade- Store API keys in
.envfile (never commit this file) - Use paper trading mode for testing
- Start with small capital in live mode
- Monitor the system regularly
- Set appropriate risk limits
Logs are stored in the logs/ directory:
trading_YYYY-MM-DD.log: Daily trading logstrading_errors_YYYY-MM-DD.log: Error logs- Automatic rotation and compression
- 30-day retention for regular logs, 90 days for errors
Run tests:
pytest tests/Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
IMPORTANT: This software is for educational purposes only. Trading involves substantial risk of loss. Past performance is not indicative of future results. The authors are not responsible for any financial losses incurred through the use of this software.
- Always test thoroughly in paper trading mode first
- Start with small amounts in live trading
- Never trade with money you cannot afford to lose
- Consult with a financial advisor before trading
This project is licensed under the MIT License - see the LICENSE file for details.
For questions, issues, or contributions, please open an issue on GitHub.
- Market data provided by Yahoo Finance
- Built with Python and various open-source libraries
- Inspired by quantitative trading research and best practices
Happy Trading! ππ°