# AI-Quantitative-Trading **Repository Path**: discover304/AI-Quantitative-Trading ## Basic Information - **Project Name**: AI-Quantitative-Trading - **Description**: AI-powered multi-agent forex trading system. 8 GPT-4o agents collaborate via Redis pub/sub to analyze markets, detect signals, and execute leveraged trades on IG Markets. Full-screen Textual TUI dashboard with real-time monitoring. - **Primary Language**: Python - **License**: Apache-2.0 - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-31 - **Last Updated**: 2026-04-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # AI Quantitative Trading System An AI-powered multi-agent quantitative trading system that uses GPT-4o agents organized in a hierarchical team structure to analyze forex markets, detect trading signals, and execute leveraged trades on IG Markets. ## Architecture ### System Overview ```mermaid graph TB subgraph Terminal["Interactive Terminal"] User["User Input"] GPT["GPT-4o Interpreter"] UI["InquirerPy / Rich UI"] User <--> GPT <--> UI end subgraph Orchestrator["Agent Orchestrator (ThreadPoolExecutor)"] subgraph Interns["Intern Agents (Independent Threads)"] MI["Market Intern
IG API prices
GPT-4o trend"] SI["Social Intern
Telegram/X/CNN
GPT-4o sentiment"] TI["Technical Intern
EMA/WMA/LSTM
Momentum"] AI_intern["Asset Intern
Positions/P&L
Monitoring"] end SIG["Signal Agent
Detects trading opportunities"] DEC["Decision Agent
Creates trade decisions"] LDR["Leader Agent
Validates via simulation"] EXE["Execution Agent
Executes leveraged FX trades"] MI --> SIG SI --> SIG TI --> SIG AI_intern --> SIG SIG -->|signal detected| DEC DEC --> LDR LDR -->|approved| EXE EXE -->|position update| AI_intern end Terminal -->|commands| Orchestrator subgraph External["External Services"] Redis[("Redis
State & PubSub")] IG["IG Markets
Demo / Live"] OpenAI["OpenAI
GPT-4o API"] end Orchestrator <--> Redis Orchestrator <--> IG Orchestrator <--> OpenAI ``` ### Data Flow ```mermaid sequenceDiagram participant MI as Market Intern participant SI as Social Intern participant TI as Technical Intern participant AI as Asset Intern participant Redis as Redis PubSub participant SIG as Signal Agent participant DEC as Decision Agent participant LDR as Leader Agent participant EXE as Execution Agent participant IG as IG Markets par Every 15-60 seconds MI->>Redis: publish market report SI->>Redis: publish social sentiment TI->>Redis: publish technical indicators AI->>Redis: publish asset report end Redis->>SIG: intern reports SIG->>SIG: GPT-4o signal detection SIG->>Redis: publish signal alt Signal Detected (confidence >= 0.6) Redis->>DEC: signal notification DEC->>DEC: GPT-4o trade decision DEC->>Redis: publish decision Redis->>LDR: decision notification LDR->>LDR: Backtest simulation LDR->>LDR: GPT-4o validation alt Decision Approved LDR->>Redis: publish approved verdict Redis->>EXE: verdict notification EXE->>IG: open leveraged position IG-->>EXE: deal confirmation EXE->>Redis: update asset records else Decision Rejected LDR->>Redis: publish rejected verdict end end ``` ### Redis Key & Channel Architecture ```mermaid graph LR subgraph Keys["Key-Value State"] K1["trade:intern:{name}:latest"] K2["trade:intern:{name}:history"] K3["trade:signal:latest"] K4["trade:decision:latest"] K5["trade:assets:positions"] K6["trade:assets:summary"] K7["trade:agent:{name}:status"] end subgraph Channels["PubSub Channels"] C1["trade:ch:intern:market"] C2["trade:ch:intern:social"] C3["trade:ch:intern:technical"] C4["trade:ch:intern:asset"] C5["trade:ch:signal"] C6["trade:ch:decision"] C7["trade:ch:leader"] C8["trade:ch:execution"] C9["trade:ch:system"] end Keys --- |"dual write"| Channels ``` ### Agent Hierarchy | Agent | Role | GPT-4o Usage | Thread | |-------|------|-------------|--------| | **Market Intern** | Fetches live FX prices, volume, spreads from IG Markets | Trend classification (bullish/bearish/neutral) | Own thread | | **Social Intern** | Monitors Telegram channels, X/Twitter accounts, CNN/Reuters RSS | Sentiment analysis (-1.0 to 1.0) | Own thread | | **Technical Intern** | Computes EMA, WMA, momentum; runs LSTM price prediction | N/A (pure computation) | Own thread | | **Asset Intern** | Monitors open positions, unrealized P&L, exposure | Portfolio summary | Own thread | | **Signal Agent** | Reads all intern reports, detects trading opportunities | Signal detection reasoning | Own thread | | **Decision Agent** | Accumulates context, creates specific trade decisions when signaled | Trade sizing, stop-loss/TP calculation | Own thread | | **Leader Agent** | Validates decisions via backtesting simulation + GPT-4o review | Decision validation, risk assessment | Own thread | | **Execution Agent** | Executes approved trades on IG Markets with leverage | N/A (executes instructions) | Own thread | ### Technology Stack | Component | Technology | |-----------|-----------| | Language | Python 3.11+ | | Package Manager | uv | | Configuration | Hydra + OmegaConf | | LLM | OpenAI GPT-4o (function calling + JSON mode) | | Data Store | Redis (state + pub/sub messaging) | | Broker | IG Markets REST API (demo/live) | | Terminal UI | Rich (formatting) + InquirerPy (arrow-key menus) | | ML Model | PyTorch LSTM for price prediction | | Data Sources | IG Markets, Telegram Bot API, X/Twitter API v2, RSS feeds | | Concurrency | Python threading + ThreadPoolExecutor | ## Getting Started ### Prerequisites - Python 3.11+ - Redis server running locally - IG Markets account (demo account for testing) - OpenAI API key - (Optional) Telegram Bot token, X/Twitter Bearer token ### Installation ```bash # Clone the repository git clone cd AI-Quantitative-Trading # Install dependencies with uv uv sync # Copy environment template and fill in your credentials cp .env.example .env ``` ### Environment Variables Edit `.env` with your credentials: ```env # OpenAI OPENAI_API_KEY=sk-... # IG Markets (demo account) IG_USERNAME=your_username@ig.demo IG_PASSWORD=your_password IG_API_KEY=your_api_key IG_ACC_NUMBER=your_account_number # Telegram (optional) TELEGRAM_BOT_TOKEN=123456:ABC-DEF... # X/Twitter (optional) TWITTER_BEARER_TOKEN=AAAA... # Redis (optional, defaults to localhost:6379) REDIS_PASSWORD= ``` ### Setting Up Data Sources #### IG Markets Demo Account 1. Sign up at [IG Markets](https://www.ig.com/) for a demo account 2. Generate an API key from My Account → Settings → API 3. Add credentials to `.env` #### Telegram Bot (for social monitoring) 1. Message [@BotFather](https://t.me/BotFather) on Telegram 2. Send `/newbot` and follow the prompts 3. Copy the bot token to `.env` 4. Add the bot to channels you want to monitor 5. Configure channel list in `conf/data_sources/telegram.yaml` #### X/Twitter API (for social monitoring) 1. Apply for a developer account at [developer.x.com](https://developer.x.com) 2. Create a project and app 3. Generate a Bearer token 4. Copy to `.env` 5. Configure tracked users and hashtags in `conf/data_sources/twitter.yaml` #### News RSS Feeds Pre-configured in `conf/data_sources/news.yaml` — no setup needed. Default feeds: - CNN Markets - Reuters Business - Bloomberg Markets ### Starting Redis ```bash # Ubuntu/Debian sudo apt install redis-server sudo systemctl start redis # macOS brew install redis brew services start redis # Docker docker run -d --name redis -p 6379:6379 redis:latest # Verify redis-cli ping # Should return PONG ``` ### Running the System ```bash # Start the interactive terminal uv run python -m trade # Override config via command line (Hydra) uv run python -m trade broker=ig_live # Switch to live account uv run python -m trade agents.execution.dry_run=false # Enable real trading uv run python -m trade trading.risk.max_position_size_usd=500 # Adjust risk ``` ## Use Cases ### 1. Monitor FX Markets in Real-Time ``` > show me what's happening in the market AI: Here's the current market overview: EUR/USD: 1.0842 (+0.12%) — Bullish trend GBP/USD: 1.2651 (-0.05%) — Neutral USD/JPY: 149.23 (+0.31%) — Bullish trend Social Sentiment: Slightly positive (0.35) Key Topics: "ECB rate decision", "US jobs data" What would you like to do? > View detailed technical analysis Check open positions Start the trading agents Configure risk parameters ``` ### 2. Start Automated Trading (Dry Run) ``` > start trading EUR/USD AI: I'll start the agent pipeline for EUR/USD in dry-run mode. Starting agents... Market Intern — monitoring CS.D.EURUSD.MINI.IP Social Intern — monitoring 3 Telegram channels, 5 Twitter accounts Technical Intern — computing EMA(12/26), WMA(100), LSTM Asset Intern — monitoring positions Signal Agent — listening for signals Decision Agent — ready Leader Agent — simulator loaded (30-day lookback) Execution Agent — DRY RUN mode (no real trades) What would you like to do? > Watch agent activity live Switch to real trading Adjust risk parameters Stop all agents ``` ### 3. Review a Trading Signal ``` > what signals have we seen? AI: The Signal Agent detected a BUY signal 3 minutes ago: SIGNAL: BUY EUR/USD Confidence: 0.78 Reasoning: EMA crossover (12 > 26), bullish momentum (0.45), positive social sentiment (0.52) LSTM Prediction: +0.0023 (23 pips up) Decision Agent proposed: Action: OPEN LONG | Size: 0.5 mini lots | Leverage: 30:1 Stop-Loss: 20 pips | Take-Profit: 50 pips Leader Agent APPROVED after simulation: Simulated P&L: +$115 (median) | Max Drawdown: -$42 Win Probability: 63% ``` ### 4. Check Portfolio & Positions ``` > how are my positions doing? AI: Current portfolio status: | Epic | Direction | Size | Entry | Current | P&L | |---------|-----------|------|--------|---------|---------| | EUR/USD | LONG | 0.5 | 1.0835 | 1.0842 | +$10.50 | | GBP/USD | SHORT | 0.5 | 1.2670 | 1.2651 | +$14.25 | Total Exposure: $1,000 (leveraged at 30:1) Unrealized P&L: +$24.75 ``` ### 5. Enable Live Trading ``` > switch to real trading AI: WARNING: You are about to enable LIVE trading on your IG demo account. Current configuration: - Account: Demo - Market: FX (EUR/USD, GBP/USD, USD/JPY) - Leverage: 30:1 - Max position: $1,000 - Stop-loss: 2.0% > Confirm — enable live trading on DEMO account Cancel — stay in dry-run mode Review risk settings first ``` ## Configuration All configuration is managed via Hydra YAML files in `conf/`: ``` conf/ ├── config.yaml # Main config with defaults ├── broker/ │ ├── ig_demo.yaml # IG demo credentials (env vars) │ └── ig_live.yaml # IG live credentials (env vars) ├── agents/ │ └── default.yaml # Agent intervals, thresholds, dry_run ├── llm/ │ └── gpt4o.yaml # Model, temperature, max_tokens ├── redis/ │ └── default.yaml # Host, port, key prefix ├── data_sources/ │ ├── telegram.yaml # Bot token, channels to monitor │ ├── twitter.yaml # Bearer token, users/tags to track │ └── news.yaml # RSS feed URLs ├── trading/ │ └── forex.yaml # Epics, leverage, risk limits └── logging/ └── default.yaml # Log level, output dir ``` Override any config from the command line: ```bash uv run python -m trade broker=ig_live trading.risk.max_daily_loss_usd=100 ``` ## Project Structure ```mermaid graph TB subgraph src/trade main["__main__.py
Hydra entry point"] app["app.py
Interactive terminal loop"] subgraph cli["cli/"] renderer["renderer.py
Rich + InquirerPy"] interpreter["interpreter.py
GPT-4o options"] commands["commands.py
Command dispatch"] end subgraph config["config/"] schemas["schemas.py
Dataclass configs"] loader["loader.py
Hydra helpers"] end subgraph logging_mod["logging/"] logger["logger.py
File + Rich console"] end subgraph storage["storage/"] redis_client["redis_client.py
Singleton connection"] keys["keys.py
Key/channel constants"] state["state.py
Read/write helpers"] pubsub["pubsub.py
PubSub wrapper"] end subgraph agents["agents/"] base["base.py — BaseAgent ABC"] registry["registry.py — Orchestrator"] llm["llm.py — GPT-4o client"] agent_schemas["schemas.py — Pydantic I/O"] subgraph intern["intern/"] market["market_intern.py"] social["social_intern.py"] technical["technical_intern.py"] asset["asset_intern.py"] end signal["signal_agent.py"] decision["decision_agent.py"] leader["leader_agent.py"] execution["execution_agent.py"] end subgraph broker["broker/"] ig["ig_client.py
IG REST API"] models["models.py
Trade dataclasses"] simulator["simulator.py
Backtesting"] end subgraph ml_models["models/"] lstm["lstm.py — StockLSTM"] preprocessing["preprocessing.py"] end subgraph data["data/"] fetcher["fetcher.py
Unified fetcher"] indicators["indicators.py
EMA/WMA/RSI"] subgraph sources["sources/"] telegram["telegram.py"] twitter["twitter.py"] news["news.py"] end end main --> app app --> cli app --> agents agents --> storage agents --> broker agents --> data agents --> ml_models end ``` ## License Apache License 2.0