An autonomous AI trading agent that makes all buy/sell decisions without human intervention. It scans markets every 2 minutes, applies 4 intraday strategies (Breakout, Day Trade, Opening Range Breakout, VWAP Bounce), and manages a $1,000 paper portfolio with a $50 daily gain target.
The AI decides everything: which instruments to trade, when to enter and exit, position sizing, stop-loss and take-profit levels, and when to stop trading for the day. You configure risk tolerance via a risk profile (conservative/moderate/aggressive) — the agent handles the rest.
Current mode: Day trading with focused watchlist (US500, US100, AAPL, NVDA, TSLA, BTCUSD, ETHUSD, GOLD). Stocks trade during US market hours; crypto runs 24/7.
Insights are delivered via Telegram and a Streamlit dashboard. Runs locally or on Google Cloud Run.
┌─────────────┐ webhook ┌──────────────────┐
│ Telegram │◄─────────────►│ Cloud Run │
│ (phone) │ │ Service (bot) │
└─────────────┘ └────────┬─────────┘
│ reads via GitHub API
┌─────────────┐ git pull ┌───────▼──────────┐
│ Laptop │◄─────────────│ GitHub Repo │
│ (optional) │──────────────►│ (code + data) │
└──────┬──────┘ git push └───────▲──────────┘
│ │ git push
│ localhost:7497 ┌──────┴───────────┐
┌──────▼──────┐ triggers │ Cloud Run │
│ IBKR TWS │ ┌──────────►│ Job (pipeline) │
│ (desktop) │ │ └──────────────────┘
└─────────────┘ │
┌─────────────┐ │
│ Cloud │──┘ also sends reminders 30 min before
│ Scheduler │
└─────────────┘
Joe AI is a fully autonomous trading agent — no manual trade decisions required. Here's what it does on its own:
- Market analysis — Detects the current market regime (trending, ranging, volatile) using SPY/VIX data
- Signal generation — Scans instruments with 100+ technical indicators, scores them, and identifies trade setups
- Strategy matching — Matches signals to the best strategy for the current regime (Day Trade, ORB, VWAP Bounce, Breakout)
- Risk assessment — Evaluates each signal across 5 risk dimensions (position, portfolio, market, behavioral, strategy) and blocks high-risk trades
- Trade execution — Opens paper positions with calculated position size, stop-loss, and take-profit levels
- Position management — Monitors open positions every 2 minutes, adjusts trailing stops, and closes at SL/TP/expiry
- Self-tuning — Weekly auto-tuner analyzes past trades and adjusts strategy parameters within safe bounds
- Risk controls — Enforces daily loss limits, gain targets, consecutive loss breakers, and correlation checks automatically
You control the risk level by choosing a risk profile (conservative, moderate, or aggressive) — the agent handles all trading decisions within those bounds.
- New traders who want to learn how markets work without risking real money
- Strategy learners who want to see how breakout, day trade, ORB, and VWAP bounce strategies perform in different market conditions
- Anyone curious about trading who wants an AI agent autonomously managing a simulated portfolio with daily updates to their phone
The agent runs a $1,000 paper portfolio targeting $50/day through 3 moderate-risk trades (3% risk each, 1:2.5 R:R). After 30 days of simulated results, the dashboard shows a "Go Live Readiness" checklist to help you decide if you're ready for real trading.
- Paper trading simulation — $1,000 virtual portfolio with daily P&L tracking, ROI, and strategy accuracy
- Go Live Readiness — 30-day evaluation checklist before committing real money
- Market regime detection — SPY/VIX-based regime classification (trending up, trending down, range-bound, high volatility)
- 100+ instrument scanning — stocks, ETFs, indices, forex, crypto, commodities
- 4 active intraday strategies — Day Trade, Opening Range Breakout (ORB), VWAP Bounce, Breakout
- Defensive mode — auto-suspends trading when VIX > 28 or drawdown exceeds -10%
- Multi-layer risk profiling — position, portfolio, market, behavioral, and strategy dimensions
- AI analysis — Gemini-powered daily summaries, trade analysis, and Q&A
- Crypto intelligence — fear & greed, BTC/ETH dominance, funding rates, open interest, whale activity, DeFi TVL, liquidation estimates
- Stock extras — earnings calendar, sector performance, market breadth, insider activity
- After-hours analysis — earnings gaps, pre-market movers, crypto overnight signals
- Signal summary alerts — after each scan, stock and crypto signals grouped by strategy with RSI, MACD, volume, and action taken (entered/watchlist/skipped)
- Daily P&L alert — realized + unrealized P&L, portfolio value, positions entered/exited today
- Weekly performance digest — Sunday report with week's P&L, win rate, best/worst trades, strategy breakdown, max drawdown, regime outlook
- Position alerts — notifications on position open, close, stop-out, and target-hit
- Earnings warnings — alert when any open position has earnings within 3 days
- System alerts — pipeline failures, API circuit breaker activations
/status— portfolio balance, open positions, today's P&L, regime, risk grade/positions— detailed open positions with entry price, current P&L, stop/target levels/performance— win rate, total trades, profit factor, Sharpe ratio, best/worst trades, strategy breakdown/pause— pause new entries (existing positions still monitored for SL/TP)/resume— resume trading after pause/blacklist TICKER— skip a ticker in scanning (run without args to see current blacklist)/whitelist TICKER— remove a ticker from blacklist- Interactive menu — Daily Briefing, Stocks, Crypto, Portfolio, Ask AI, System
- Intraday monitor — checks positions every 2 minutes during market hours, auto-closes at SL/TP, opens day trades
- Auto-parameter tuning — weekly backtest (Sunday) analyzes 2 weeks of trades and adjusts strategy parameters within ±20% of baseline
- Cloud deployment — runs 24/7 on Cloud Run with scheduled pipeline executions
- Pipeline reminders — Telegram notification 30 min before runs so you can optionally run locally with IBKR
- Configurable modules — enable/disable crypto, stocks extras, after-hours via preferences
- Python 3.12+ (tested with 3.13)
- Git for cloning and data sync
- A Capital.com demo account (free, no real money needed) — sign up here
- A Telegram bot — create one via @BotFather on Telegram
- Optional: Interactive Brokers TWS for enhanced US equity data
git clone <your-repo-url>
cd ai-trading-agent
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txtcp .env.example .envEdit .env with your API keys:
| Variable | Required | Where to get it |
|---|---|---|
CAPITAL_API_KEY |
Yes | Capital.com → Settings → API |
CAPITAL_IDENTIFIER |
Yes | Your Capital.com login email |
CAPITAL_PASSWORD |
Yes | Your Capital.com API password |
CAPITAL_DEMO |
Yes | Always true (enforced in code) |
TELEGRAM_BOT_TOKEN |
Yes | @BotFather on Telegram |
TELEGRAM_CHAT_ID |
Yes | Send a message to @userinfobot |
GEMINI_API_KEY |
Recommended | Google AI Studio (free tier available) |
ALPHA_VANTAGE_KEY |
Optional | Alpha Vantage (free) |
FINNHUB_KEY |
Optional | Finnhub (free tier) |
IBKR_HOST |
Optional | Default 127.0.0.1 (only if running TWS) |
IBKR_PORT |
Optional | Default 7497 (demo port — 7496 live is blocked) |
python setup_wizard.pyThe wizard will ask about modules, deployment mode, and schedule — then generate config/preferences.yaml.
# Single run with Capital.com broker
python main.py --once --broker capital
# Run with both brokers (needs IBKR TWS running on port 7497)
python main.py --once
# Run and push data to GitHub
python main.py --once --pushOn first run, the system will:
- Detect the current market regime (trending, ranging, volatile)
- Scan all instruments in your watchlist
- Score them using technical analysis + sentiment
- Match signals to strategies and assess risk
- Open paper positions for approved signals
- Send you a Telegram summary with signals, P&L, and AI analysis
python telegram_bot.pyOpen Telegram, find your bot, and send /start. You'll see an interactive menu for browsing signals, portfolio, and market data.
python monitor.py # Default 2-min loop
python monitor.py --interval 3 # 3-min loop
python monitor.py --once --dry-run # Single cycle, no tradesThe monitor runs during US market hours (9:30 AM – 4:00 PM ET) and:
- Checks open positions against current prices for SL/TP/trailing exits
- Scans a curated day-trade watchlist for new entries
- Sends Telegram alerts on position changes
IBKR (Interactive Brokers) requires TWS or IB Gateway running on your laptop — it connects via localhost:7497. Cloud Run cannot access it.
Capital.com has a REST API — works from anywhere (local or cloud).
| Local run (laptop) | Cloud Run Job | |
|---|---|---|
| IBKR data | Full US equities, real volume, scanner presets | Not available |
| Capital.com | Indices, forex, crypto, commodities, 12 stocks | Same |
| When it runs | Manually, when laptop + TWS are open | Scheduled, always |
| Data quality | Best (both brokers combined) | Good (Capital.com only) |
To get the best of both worlds, the system sends you a Telegram reminder 30 minutes before each scheduled pipeline run:
- 8:30 AM ET — You get a reminder: "Pipeline runs in 30 min"
- If you're at your laptop with TWS open, run locally:
This uses IBKR + Capital.com and pushes the richer data to GitHub.
python main.py --once --push
- If you're away — do nothing. At 9:00 AM, the cloud job runs automatically with Capital.com data.
- Either way, the Telegram bot and your local machine can read the latest data.
Whether the pipeline runs locally or in the cloud, data ends up on GitHub:
# Pull latest data (from cloud runs or your own pushes)
git pullJoe AI uses 4 active intraday strategies (swing strategies are disabled but available for re-enabling):
| Strategy | Active Regimes | Entry Logic | Exit Logic | Max Hold |
|---|---|---|---|---|
| Day Trade | All regimes | RSI 35-65, MACD histogram, volume ≥ 1.3x, ADX ≥ 15, EMA alignment | 1 ATR stop, 2.5 ATR take-profit, 0.75 ATR trailing | 1 day |
| Opening Range Breakout (ORB) | All regimes | First 15-min candle high/low as range, breakout with volume ≥ 1.5x, strong close | Opposite range boundary stop, 2x measured move target | 1 day |
| VWAP Bounce | All except high volatility | Price touches VWAP, RSI 35-65, volume confirmation, with-trend bounce | 0.8 ATR stop, 2 ATR take-profit, 0.75 ATR trailing | 1 day |
| Breakout | All regimes | Bollinger Squeeze, volume surge ≥ 1.5x, strong close | False breakout (1-bar) or measured move target | 7 days |
Disabled (available): Trend Following, Mean Reversion, Momentum — re-enable in config/strategies.yaml if you want swing trading.
Defensive mode triggers automatically when VIX > 28 or portfolio drawdown exceeds -10%, suspending all new entries and tightening stops.
Joe AI ships with three risk profiles. Set risk_profile in config/paper_trader.yaml:
| Setting | Conservative | Moderate (default) | Aggressive |
|---|---|---|---|
| Risk per trade | 1% ($10) | 3% ($30) | 5% ($50) |
| Daily gain target | $20 | $50 | $80 |
| Daily loss limit | $15 | $30 | $50 |
| Max concurrent positions | 2 | 3 | 5 |
| Take profit (ATR) | 2.0x | 2.5x | 3.0x |
| Trailing stop (ATR) | 1.0x | 0.75x | 0.5x |
| Max daily exposure | 2x balance | 3x balance | 4x balance |
To change profile, edit config/paper_trader.yaml:
risk_profile: conservative # or moderate, aggressiveIndividual settings in the config file override the profile defaults — so you can start with a profile and fine-tune specific values.
| Control | Setting | Purpose |
|---|---|---|
| Daily gain target | $50 | Stop trading when hit (protect profits) |
| Daily loss limit | $30 | Stop trading when hit (prevent tilt) |
| Risk per trade | 3% ($30) | Moderate path for $50/day target |
| Max concurrent positions | 3 | Focus over diversification |
| Consecutive loss breaker | 3 losses → 30 min pause | Prevent revenge trading |
| Per-instrument loss limit | $15/day | Don't keep losing on the same ticker |
| Max daily exposure | 3x balance | Leverage cap |
| Correlation check | Same group + direction → 50% size | Avoid doubling bets |
| Time decay exit | 60 min with < 0.3 ATR profit | Free up slots from dead trades |
| Spread filter | Skip if spread > 0.5% | Avoid costly entries |
| EOD auto-close | 3:55 PM ET | No overnight stock positions (crypto stays) |
| Session windows | Prime: 9:30-11:30, 14:30-16:00 | Tighter criteria during midday chop |
Every Sunday, the auto-tuner:
- Analyzes the last 2 weeks of paper trades per strategy
- Calculates win rate, avg P&L, avg hold time, risk-adjusted return
- Applies adjustments within ±20% of baseline values:
- Win rate < 30% → tightens entry criteria
- No trades in 2 weeks → slightly loosens criteria
- Hold time near max → tightens trailing stops
- Sharpe < 0 → flags for review (no auto-change)
- Sends a Telegram summary of changes
- Logs all adjustments to
data/paper/tuning_log.json
Run manually: python main.py --tune
- ETFs: VOO, QQQ, SCHD, SPY, IWM, DIA
- Stocks: dynamically populated from scanner presets (TOP_PERC_GAIN, TOP_VOLUME, HOT_BY_VOLUME)
- Indices: US500, US100, UK100, DE40
- Forex: EURUSD, GBPUSD, USDJPY
- Crypto: BTCUSD, ETHUSD
- Commodities: GOLD, OIL_CRUDE
- Stocks: AAPL, NVDA, TSLA, MSFT, AMZN, META, GOOGL, JPM, GS, BAC, XOM, CVX
Edit config/watchlist.yaml to add or remove instruments.
| Menu | Sub-items |
|---|---|
| Daily Briefing | Market Regime, AI Summary, Risk Assessment, After-Hours Intel |
| Stocks | Today's Signals, Earnings Calendar, Market Breadth, Sector Performance, Insider Activity |
| Crypto | Fear & Greed, BTC/ETH Overview, DeFi & Gas, Whale Activity, Overnight Signals |
| Portfolio | Open Positions, Performance Summary, Analytics, Trade History |
| Ask AI | Free-text Q&A powered by Gemini with live portfolio context |
| System | API Health, Run Pipeline |
The Crypto menu is hidden when the crypto module is disabled.
| Command | Description |
|---|---|
/start |
Show main menu |
/help |
List all commands |
/status |
Portfolio snapshot (balance, positions, regime) |
/positions |
Detailed open positions with P&L |
/performance |
Win rate, Sharpe, strategy breakdown |
/pause |
Pause new trade entries |
/resume |
Resume trading |
/blacklist AAPL |
Skip a ticker in scanning |
/whitelist AAPL |
Remove from blacklist |
The paper trader manages virtual positions with the same logic a real portfolio would use. Internally it delegates to three focused modules: PositionManager (entry/exit logic), PnLCalculator (trade journaling), and PerformanceTracker (metrics aggregation).
- Position sizing: 3% risk per trade (configurable via risk profile), adjusted by regime modifier
- Entry: auto-opens positions when signals pass risk profiler approval
- Exit: stop-loss (ATR-based), take-profit (ATR-based), trailing stops, max hold days, thesis failure
- PDT simulation: limits day trades per week (configurable)
paper_trader:
enabled: true
starting_balance: 1000.00 # Virtual starting capital
risk_profile: moderate # conservative | moderate | aggressive
risk_per_trade_pct: 3.0 # Risk 3% of balance per trade
max_concurrent_positions: 3 # Max open positions at once
max_hold_days: 1 # Default max hold duration
auto_enter: true # Auto-open positions on approved signals
entry_signals:
- STRONG_BUY
- STRONG_SELL
stop_loss:
method: atr
atr_multiplier: 1.5
take_profit:
method: atr
atr_multiplier: 3.0
pdt_simulation: true
pdt_day_trade_limit: 10To start fresh with a new balance:
# 1. Update starting_balance in config/paper_trader.yaml
# 2. Delete state files (old state is archived automatically)
rm data/paper/open_positions.json data/paper/performance.json data/paper/trade_history.csv
rm data/paper/portfolio_analytics.json data/paper/regime*.json
rm data/paper/crypto_overnight_state.json data/paper/risk_assessment.json
# 3. Run the pipeline — files will be recreated with the new balance
python main.py --once --pushAll alerts are sent via Telegram (and Discord if configured). Here's what you receive:
| Alert | When | Content |
|---|---|---|
| Signal Summary | After each pipeline run | Stock & crypto signals grouped by strategy, with RSI/MACD/volume and action taken |
| Daily P&L | After each pipeline run | Realized + unrealized P&L, portfolio value, positions entered/exited |
| Daily Briefing | After each pipeline run | Regime, balance, open positions, signals count, win rate, AI summary |
| Position Open | When a paper trade is entered | Ticker, direction, entry price, stop/target |
| Position Close | When a paper trade exits | Ticker, direction, P&L, exit reason |
| Earnings Warning | When position has earnings in ≤ 3 days | Ticker and days until earnings |
| Weekly Digest | Sunday | Week's P&L, win rate, best/worst trades, strategy breakdown, drawdown |
| System Alert | On pipeline failure | Error message and stack trace |
| Pipeline Reminder | 30 min before scheduled runs | Prompt to open TWS for enhanced data |
Beyond Telegram alerts, there are several ways to review performance and trades:
./venv/bin/python3 -m streamlit run dashboard.pyOpens a visual dashboard in your browser with portfolio charts, daily gains, strategy accuracy, equity curve, and the Go Live Readiness checklist.
cat data/findings/$(date +%Y-%m-%d).mdHuman-readable summary of the day's regime, signals, positions, and AI analysis.
cat data/paper/performance.json # Balance, win rate, total trades
cat data/paper/open_positions.json # What's open now with P&L
cat data/paper/session_state.json # Today's running P&L and trade countcolumn -t -s, data/paper/trade_history.csv | lessFull history of every closed trade with setup type, duration, session window, exit type, and P&L. Can also be opened in Google Sheets or Excel.
data/paper/anddata/findings/are committed to git — synced across cloud and local viagit push/pulldata/cache/anddata/reports/are gitignored — temporary/regenerable files only- All shared state files use cross-process file locking (
fcntl.flock) — safe for concurrent access from main.py, monitor.py, and telegram_bot.py - JSON writes are atomic (tempfile +
os.replace) inside exclusive locks to prevent corruption
| Schedule | Time (ET) | Days | What |
|---|---|---|---|
| Morning reminder | 8:30 AM | Mon–Fri | Telegram: "run locally with IBKR?" |
| Morning pipeline | 9:00 AM | Mon–Fri | Regime detection + full scan |
| Opening range capture | 9:45 AM | Mon–Fri | Record first 15-min candle for ORB strategy |
| Monitor (stocks + crypto) | Every 2 min | Mon–Fri (9:30 AM–4:00 PM) | Primary trading engine — entries, exits, ORB, VWAP |
| EOD auto-close | 3:55 PM | Mon–Fri | Close all stock/index positions |
| Afternoon pipeline | 3:00 PM | Mon–Fri | End-of-day summary |
| Monitor (crypto only) | Every 2 min | 24/7 | Crypto never sleeps — BTCUSD, ETHUSD monitored round the clock |
| Crypto morning | 8:00 AM | Daily | Crypto intelligence update |
| Crypto evening | 8:00 PM | Daily | Crypto overnight signals |
| Auto-tuner | Sunday | Weekly | Strategy parameter optimization |
| Weekly digest | Sunday | Weekly | Performance summary via Telegram |
All times are US/Eastern. Cloud Scheduler handles timezone conversion.
Run python setup_wizard.py to configure:
| Setting | Options | Default |
|---|---|---|
| Stocks module | on/off | On |
| Crypto module | on/off | Off |
| After-hours module | on/off | On |
| Deployment mode | local/cloud | Local |
| Push data after run | yes/no | No (local), Yes (cloud) |
| GitHub repo | URL | — |
| GCP project | ID | — |
| Timezone | any | US/Eastern |
| Morning run | HH:MM | 09:00 |
| Afternoon run | HH:MM | 15:00 |
Re-run the wizard any time — it shows current values in brackets.
- gcloud CLI installed and authenticated
- A GCP project (the script can create one)
- GitHub repo with this code pushed
# Set required environment variables (or the script will prompt)
export GCP_PROJECT=your-project-id
export GCP_REGION=us-central1
export GITHUB_REPO=username/repo-name
# Source your .env for secrets
source .env
# Run the deployment script
chmod +x cloud/deploy.sh
./cloud/deploy.shThe script will:
- Enable required GCP APIs
- Store secrets in Secret Manager
- Build and push the container image
- Deploy the Telegram bot as a Cloud Run Service (webhook mode)
- Create Cloud Run Jobs (pipeline + reminder)
- Set up Cloud Scheduler for automated runs and reminders
- Register the Telegram webhook
| Component | GCP Resource | Trigger |
|---|---|---|
| Telegram bot | Cloud Run Service | Webhook (always running, min 1 instance) |
| Pipeline | Cloud Run Job | Cloud Scheduler or manual |
| Reminder | Cloud Run Job | Cloud Scheduler (30 min before pipeline) |
gcloud run jobs execute trading-agent-pipeline --region=us-central1Pipeline Run (main.py)
│
├── Step 1: Regime Detection (SPY/VIX via IBKR, or US500 via Capital.com)
├── Step 2: Update existing positions (SL/TP/trailing/expiry checks)
├── Step 3: Market Scanning (IBKR scanners + Capital.com watchlist)
├── Step 4: Scoring (technical + sentiment + volume for top 15)
├── Step 5: Check defensive mode + bot state (pause/blacklist)
├── Step 6: Strategy Matching (4 intraday strategies filtered by regime)
├── Step 7: Risk Profiling (5 dimensions, hard blocks at score > 7)
├── Step 8: Trade Entry (risk-approved signals → paper positions)
├── Step 9: Report Generation (text summary)
├── Step 10: Crypto Intelligence (if enabled)
├── Step 11: Stock Intelligence (if enabled)
├── Step 12: After-Hours Intelligence (if enabled)
├── Step 13: AI Analysis (Gemini summaries + per-trade analysis)
├── Step 14: Save daily findings (JSON + Markdown)
├── Step 15: Portfolio Analytics (Sharpe, drawdown, ROI)
├── Step 16: Daily alerts (briefing + signal summary + P&L)
├── Step 17: Weekly digest (Sunday only)
├── Step 18: Auto-tuner (Sunday only)
└── Step 19: API health tracking
│
└── Output
├── data/findings/YYYY-MM-DD.json
├── data/findings/YYYY-MM-DD.md
├── data/paper/open_positions.json
├── data/paper/performance.json
├── data/paper/portfolio_analytics.json
└── git push (if --push flag or cloud mode)
│
▼
GitHub Repo (shared data store)
│
┌───────┴────────┐
▼ ▼
Telegram Bot Laptop
(Cloud Run) (git pull)
Generated by the setup wizard. Controls which modules run and deployment behavior.
modules:
stocks: true
crypto: false
after_hours: true
deployment:
mode: local
push_data_after_run: false
github_repo: ''
gcp_project: ''
gcp_region: us-central1
telegram:
mode: polling
schedule:
timezone: US/Eastern
morning_run: '09:00'
afternoon_run: '15:00'| File | Purpose |
|---|---|
config/strategies.yaml |
Strategy definitions, regime rules, entry/exit conditions |
config/strategies_baseline.yaml |
Original strategy params (baseline for auto-tuner ±20% range) |
config/trading.yaml |
Market hours, holidays, risk controls, circuit breakers |
config/paper_trader.yaml |
Starting balance, risk per trade, max positions |
config/risk_profiler.yaml |
Risk dimension weights, thresholds, hard blocks |
config/scoring.yaml |
Technical/sentiment/volume weights |
config/watchlist.yaml |
Instruments to scan per broker |
config/dashboard.yaml |
Streamlit dashboard settings |
| File | Purpose |
|---|---|
data/paper/performance.json |
Virtual balance, win rate, trade counts |
data/paper/open_positions.json |
Currently open paper positions |
data/paper/trade_history.csv |
All closed trades (used by auto-tuner and digests) |
data/paper/portfolio_analytics.json |
Sharpe ratio, max drawdown, equity curve |
data/paper/bot_state.json |
Telegram bot state (pause, blacklist) |
data/paper/tuning_log.json |
Auto-tuner adjustment history |
data/paper/regime*.json |
Market regime state and history |
data/findings/YYYY-MM-DD.json |
Daily pipeline findings (structured) |
data/findings/YYYY-MM-DD.md |
Daily pipeline findings (human-readable) |
# Pipeline
python main.py --once --broker capital # Single run, Capital.com only
python main.py --once # Single run, both brokers (needs TWS)
python main.py --once --push # Run and push data to GitHub
python main.py --once --dry-run # No API calls, use cached data
python main.py --regime-only --broker capital # Check regime only
python main.py --paper-update --broker capital # Update paper positions only
python main.py --remind # Send pipeline reminder to Telegram
python main.py --schedule 09:00 --broker capital # Schedule daily runs locally
python main.py --tune # Run auto-tuner now (regardless of day)
# Backtest
python main.py --backtest --start 2025-01-01 --end 2025-02-01 --broker capital
# Monitor (primary day-trading engine)
python monitor.py # 2-min loop, stocks + crypto during market hours
python monitor.py --crypto-only # 24/7 crypto monitoring
python monitor.py --interval 1 # 1-min loop (faster scanning)
python monitor.py --once --dry-run # Single cycle, no trades
# Telegram bot
python telegram_bot.py # Start in polling mode (local)
# Setup
python setup_wizard.py # Configure modules and deploymentai-trading-agent/
├── main.py # Pipeline orchestration (20 steps)
├── monitor.py # Intraday position monitor
├── telegram_bot.py # Interactive Telegram bot + commands
├── setup_wizard.py # First-time configuration wizard
├── agent/
│ ├── scanner.py # Market scanning (IBKR + Capital.com)
│ ├── scorer.py # Technical + sentiment scoring
│ ├── strategy.py # Strategy matching engine (delegates to strategies/)
│ ├── strategies/ # Pluggable strategy modules (BaseStrategy + registry)
│ │ ├── base.py # Abstract base class for all strategies
│ │ ├── registry.py # Auto-discovery registry for strategy plugins
│ │ ├── trend_following.py
│ │ ├── mean_reversion.py
│ │ ├── breakout.py
│ │ ├── momentum.py
│ │ ├── day_trade.py
│ │ ├── opening_range_breakout.py
│ │ └── vwap_bounce.py
│ ├── paper_trader.py # Portfolio facade (composes the three below)
│ ├── position_manager.py # Position entry/exit logic and guardrails
│ ├── pnl_calculator.py # P&L computation and trade journaling
│ ├── performance_tracker.py # Metrics aggregation (Sharpe, drawdown, etc.)
│ ├── file_lock.py # Cross-process file locking for shared state
│ ├── risk_profiler.py # 5-dimension risk assessment
│ ├── regime.py # Market regime detection
│ ├── ai_analyst.py # Gemini AI summaries + trade analysis
│ ├── alerts.py # Telegram/Discord alert manager
│ ├── performance_digest.py # Daily P&L, weekly digest, signal alerts
│ ├── auto_tuner.py # Weekly strategy parameter optimization
│ ├── crypto_data.py # Crypto intelligence (fear/greed, whales)
│ ├── stock_extras.py # Stock intelligence (earnings, breadth)
│ ├── after_hours.py # After-hours / pre-market signals
│ ├── portfolio_analytics.py # Sharpe, drawdown, ROI calculations
│ ├── resilience.py # Circuit breaker for API failures
│ ├── preferences.py # Module enable/disable logic
│ ├── news.py # Sentiment from news APIs
│ ├── cache.py # Instrument data caching
│ ├── models.py # Data models and enums
│ ├── backtester.py # Historical backtesting engine
│ ├── risk_profiles.py # Conservative/moderate/aggressive risk presets
│ └── config_validator.py # Startup config and env validation
├── brokers/
│ ├── base.py # Abstract broker interface
│ ├── ibkr_client.py # Interactive Brokers TWS client
│ └── capital_client.py # Capital.com REST API client
├── config/
│ ├── strategies.yaml # Strategy definitions
│ ├── strategies_baseline.yaml # Baseline for auto-tuner
│ ├── trading.yaml # Market hours, holidays, risk controls
│ ├── paper_trader.yaml # Paper trading settings
│ ├── risk_profiler.yaml # Risk assessment config
│ ├── scoring.yaml # Scoring weights
│ ├── watchlist.yaml # Instruments to scan
│ └── dashboard.yaml # Dashboard settings
├── cloud/
│ └── deploy.sh # GCP Cloud Run deployment script
├── data/
│ ├── paper/ # Paper trading state (git-tracked)
│ ├── findings/ # Daily findings (git-tracked)
│ ├── cache/ # Price data cache (gitignored)
│ └── reports/ # Generated reports (gitignored)
├── .env.example # Environment variable template
├── requirements.txt # Python dependencies
├── requirements-dev.txt # Development dependencies (pytest, ruff, black)
├── pyproject.toml # Project metadata and tool config
├── Makefile # Development shortcuts
├── LICENSE # MIT License
├── CONTRIBUTING.md # Contribution guidelines
├── SECURITY.md # Security policy
└── CHANGELOG.md # Version history
# Install dev dependencies
pip install -r requirements-dev.txt
# Run tests
make test
# Lint and format
make lint
make format
# Run all checks (lint + test)
make check
# See all available commands
make helpSee CONTRIBUTING.md for guidelines on submitting changes.
.envis gitignored — never committedconfig/preferences.yamlis gitignored — only.exampleis tracked- Cloud secrets stored in GCP Secret Manager
- Telegram bot only responds to the configured
TELEGRAM_CHAT_ID - Capital.com forced to demo mode (
CAPITAL_DEMO=true) - IBKR blocked from live port (7496 → 7497 only)
- GitHub token used for private repo access only (read/write data)
data/paper/anddata/findings/are tracked in git (portfolio state and daily results)data/cache/anddata/reports/are gitignored (temporary/regenerable)
Bot doesn't respond to messages
- Check
TELEGRAM_BOT_TOKENandTELEGRAM_CHAT_IDin.env - Ensure your chat ID matches (send a message to
@userinfoboton Telegram) - Make sure
telegram_bot.pyis running
Pipeline fails with "No data"
- Ensure broker API keys are set and the broker is running (IBKR TWS or Capital.com demo)
- Try
--dry-runto test with cached data
Capital.com authentication fails
- Verify API key, identifier (email), and password in
.env - Make sure
CAPITAL_DEMO=trueis set - Capital.com demo accounts may expire — create a new one if needed
Cloud Run bot not receiving messages
- Check the webhook is set:
curl https://api.telegram.org/bot<TOKEN>/getWebhookInfo - Verify the service URL is correct and accessible
Crypto data missing
- Crypto module may be disabled — check
config/preferences.yamlor re-runpython setup_wizard.py
No signals generated
- Check if trading is paused: send
/statuson Telegram - Market may be in defensive mode (VIX > 28 or drawdown > -10%)
- Signals require specific regime + technical conditions — not every scan produces entries
Git push fails
- Ensure you have push access to the repo
- For cloud: verify
GITHUB_TOKENhas repo write permissions - If SSH fails, try HTTPS:
git remote set-url origin https://github.com/<org>/<repo>.git
Reminder not arriving
- Check Cloud Scheduler is active:
gcloud scheduler jobs list --project=YOUR_PROJECT - Verify
TELEGRAM_BOT_TOKENandTELEGRAM_CHAT_IDsecrets are set in the reminder job
Cloud job runs after I already ran locally
- This is expected — the cloud job always runs on schedule. Your local push will be overwritten with Capital-only data. If this bothers you, pause the scheduler job for that run via the GCP Console.
Auto-tuner not running
- It only runs on Sundays by default. Force it with:
python main.py --tune - Check
data/paper/tuning_log.jsonfor history
- Strategy pattern — Extracted 7 strategies into pluggable
agent/strategies/package with base class + auto-discovery registry - PaperTrader decomposition — Split 795-line monolith into PositionManager, PnLCalculator, and PerformanceTracker (facade preserved for backward compatibility)
- Cross-process file locking —
agent/file_lock.pywithfcntl.flock()locks on all shared JSON/CSV state files - Broker abstraction —
BaseBrokerABC inbrokers/base.py; IBKR and Capital.com inherit from it - Config consolidation — Moved hardcoded values (market hours, holidays, risk controls) into
config/trading.yaml - Backtester realism — Slippage (0.05%) and commission ($1/trade) modeling for accurate P&L simulation
- Security — Non-root Docker user, silent
except: passblocks now log errors, safe API response handling - 344 tests — 63 new tests covering strategies, config validation, risk profiles, broker base, file locking
- Strategy overhaul — disabled swing strategies, added Opening Range Breakout (ORB) and VWAP Bounce
- Day trade config — 3% risk per trade, $50 daily target, $30 daily loss limit, 3 max positions
- Monitor as primary engine — 2-minute scan interval, opening range capture, session tracking
- Crypto 24/7 —
--crypto-onlymode for round-the-clock crypto monitoring - EOD auto-close — stocks close at 3:55 PM ET, crypto stays open
- Execution precision — time-based exits (60 min), spread tracking/filtering, session windows
- Risk tightening — correlation checks, per-instrument daily loss limits, 3x exposure cap, consecutive loss circuit breaker
- Enhanced reporting — trade journal with setup types, session analysis,
/journalcommand, streak tracking - Focused watchlist — US500, US100, AAPL, NVDA, TSLA, BTCUSD, ETHUSD, GOLD
- Paper trading reset — fresh $1,000 starting balance
- Telegram bot commands —
/status,/pause,/resume,/blacklist,/whitelist,/positions,/performance - Auto-parameter tuning — weekly strategy optimization with ±20% safe adjustments
- Daily P&L alert — realized + unrealized P&L after each pipeline run
- Weekly performance digest — Sunday report with strategy breakdown and outlook
- Signal summary alerts — stock & crypto signals grouped by strategy after each scan
- Expanded crypto watchlist — added SOLUSD, XRPUSD, DOGEUSD, ADAUSD