Skip to content

Repository files navigation

◈ Autonomous AI Forex Trading Bot

A fully autonomous forex trading bot powered by a 3-layer AI consensus engine — Claude (LLM), RandomForest (ML), and PPO Reinforcement Learning — trading 10 forex pairs on OANDA with real-time risk management, session filtering, and a futuristic live dashboard.


Architecture

┌─────────────────────────────────────────────────────────┐
│                     bot.py (Main Loop)                  │
│   fast_loop (30s) ◄──────────────► slow_loop (5min)     │
└──────────────┬──────────────────────────────┬───────────┘
               │                              │
     ┌─────────▼──────────┐       ┌──────────▼──────────┐
     │   Scalp Trades     │       │    Swing Trades      │
     │   London/NY only   │       │  All sessions        │
     └─────────┬──────────┘       └──────────┬───────────┘
               └──────────────┬──────────────┘
                              │
           ┌──────────────────▼──────────────────┐
           │         Decision Pipeline            │
           │                                     │
           │  1. Session Filter                  │
           │  2. Correlation Filter              │
           │  3. News Blackout Check             │
           │  4. Profitability Gate (8 checks)   │
           │  5. RandomForest Score (35%)        │
           │  6. RL Agent Signal (25%)           │
           │  7. Claude Analysis (40%)           │
           │  8. Consensus + Lot Sizing          │
           │  9. Risk Validation                 │
           │ 10. Execute / Skip                  │
           └─────────────────────────────────────┘

Features

  • 3-Layer AI Consensus — Claude 40% + RandomForest 35% + PPO RL 25%
  • Variable Lot Sizing — 6 tiers (ELITE 3% → B 1%) based on consensus score
  • Session Awareness — scalp only during London/NY overlap, swing all sessions
  • Correlation Filter — never hold two correlated pairs simultaneously
  • News Blackout — pauses trading ±30 min around high-impact events
  • Profitability Gate — 8 pre-checks before calling Claude (saves API cost)
  • Weekend Protection — auto-closes all positions Friday 20:45 UTC
  • Weekly Drawdown Guard — reduces size at -10%, stops trading at -15%
  • Adaptive Streak Sizing — increases size on winning streaks, cuts on losing
  • Sunday Retraining — auto-retrains both ML models at Sunday midnight
  • Mobile Alerts — Pushover notifications for every trade event
  • Live Dashboard — futuristic real-time web UI at http://localhost:5000

Pairs Traded

EUR_USD GBP_USD USD_JPY USD_CHF AUD_USD NZD_USD USD_CAD EUR_GBP EUR_JPY GBP_JPY


Prerequisites


Setup

# 1. Clone
git clone https://github.com/Alanperry1/forex-bot.git
cd forex-bot

# 2. Create virtual environment
python3 -m venv venv
source venv/bin/activate      # Windows: venv\Scripts\activate

# 3. Install dependencies
pip install -r requirements.txt

# 4. Configure environment
cp .env.example .env          # then fill in your keys

.env Configuration

# Required
ANTHROPIC_API_KEY=sk-ant-...
OANDA_API_KEY=...
OANDA_ACCOUNT_ID=101-001-...
OANDA_PRACTICE=true           # set false for live trading

# Optional
NEWS_API_KEY=...
PUSHOVER_TOKEN=...
PUSHOVER_USER=...

Running

Test connections first

python test_connections.py

All checks should pass before running the bot. Claude and OANDA are required. NewsAPI, ForexFactory, and Pushover are optional.

Start the bot

# Practice mode (dry-run — no real orders)
python bot.py --dry-run

# Practice mode (real orders, practice account)
python bot.py

# Live trading (set OANDA_PRACTICE=false in .env first)
python bot.py

Open the dashboard

python dashboard.py
# Open http://localhost:5000

ML / RL Models

The bot ships without pre-trained models (they train on your own trade data).

RandomForest — trains after 50+ trades

python -m ml.trainer
# Saves: model.pkl

RL Agent (PPO) — bootstrap on simulated data

python -m rl.trainer
# Saves: rl_agent.zip

Until models are trained, the bot defaults to neutral scores (RF=0.5, RL=HOLD) and relies on Claude + risk rules only. Models auto-retrain every Sunday midnight.


Project Structure

forex-bot/
├── bot.py                 # Main entry point (fast + slow loops)
├── dashboard.py           # Live web dashboard (Flask)
├── ai_brain.py            # Claude integration (pair selection + trade analysis)
├── data_layer.py          # OANDA REST API client
├── executor.py            # Order placement + weekend protection
├── risk_manager.py        # Position sizing + trade validation
├── position_manager.py    # Open position tracking
├── session_filter.py      # Trading session detection
├── correlation_filter.py  # Correlated pair blocking
├── lot_sizing_engine.py   # Variable lot sizing (6 tiers)
├── profitability_gate.py  # Pre-trade 8-check gate
├── news.py                # NewsAPI + ForexFactory calendar
├── logger.py              # Trade logging + CSV + terminal output
├── alerts.py              # Pushover mobile notifications
├── test_connections.py    # API connection health checks
├── ml/
│   ├── features.py        # Feature engineering (17 features)
│   ├── predictor.py       # RF inference (score 0–1)
│   └── trainer.py         # RF training (RandomForestClassifier)
├── rl/
│   ├── environment.py     # Gymnasium trading environment
│   ├── agent.py           # PPO inference (action + size modifier)
│   ├── trainer.py         # PPO training (stable-baselines3)
│   └── reward.py          # Reward function
├── requirements.txt
├── .env                   # Your API keys (gitignored)
└── .gitignore

Lot Sizing Tiers

Tier Min Consensus Risk %
ELITE ≥ 0.90 3.0%
A+ ≥ 0.80 2.5%
A ≥ 0.70 2.0%
B+ ≥ 0.60 1.5%
B ≥ 0.50 1.0%
SKIP < 0.50 skip

Risk Controls

Control Threshold
Max open positions 3
Daily loss limit 5%
Weekly loss (reduce size) 10%
Weekly loss (stop trading) 15%
Min R:R ratio 1.5
Min Claude confidence 7/10
Min RF score 45%
Max spread 3 pips (scalp) / 5 pips (swing)

Dashboard

python dashboard.py   # http://localhost:5000
  • Live balance, daily/weekly P&L, win rate, profit factor
  • Open positions with live P&L and pip count
  • Equity curve chart
  • Current session + live spreads for top pairs
  • Recent trade history with tier badges and ML scores
  • AI system status (Claude / RandomForest / RL Agent)

Deploy (Production)

For 24/7 operation, run on a VPS. Recommended: Hetzner CX22 (~€4/mo) or Oracle Cloud Free Tier.

# Install as systemd service
sudo nano /etc/systemd/system/forex-bot.service
[Unit]
Description=Forex Bot
After=network.target

[Service]
WorkingDirectory=/home/ubuntu/forex-bot
ExecStart=/home/ubuntu/forex-bot/venv/bin/python bot.py
Restart=always
RestartSec=10
EnvironmentFile=/home/ubuntu/forex-bot/.env

[Install]
WantedBy=multi-user.target
sudo systemctl enable --now forex-bot
sudo journalctl -fu forex-bot    # live logs

⚠️ Disclaimer

This software is for educational purposes only. Forex trading carries significant risk of loss. Past performance does not guarantee future results. Always test on a practice account before using real funds. The authors are not responsible for any financial losses.

About

A fully autonomous forex trading bot powered by a 3-layer AI consensus engine — Claude (LLM), RandomForest (ML), and PPO Reinforcement Learning

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages