# AI Trader — Complete User Guide

End-to-end guide for creating, testing, and running AI trading strategies.

---

## Overview

The AI Trader lets you:

1. **Create** strategies from plain English — AI translates your idea into executable logic
2. **Test** against historical data — backtest, walk-forward, and stress test
3. **Paper trade** with simulated money — prove your strategy works
4. **Go live** with real broker execution — after meeting safety requirements
5. **Monitor** autonomous operation — with daily AI review and audit trails

All users start in **Mock mode** with $100k virtual money. Paper and live trading require meeting safety criteria.

---

## The Trading Flow

```
English    →    AI Translation    →    Backtest    →    Walk-Forward    →    Stress Test    →    Live
prompt          + critique              90 days          overfit check        6 crisis           execution
                                                                              periods
                                                              ↓                                    ↑
                                                    ┌─────────────────────────┐                   │
                                                    │ Graduation Gates:       │                   │
                                                    │ - Statistical quality   │ ──────────────────┘
                                                    │ - Walk-forward pass     │
                                                    │ - Risk acknowledgement  │
                                                    └─────────────────────────┘
```

Every step is gated — you cannot skip ahead.

---

## Step 1: Create Your Strategy

### From English

1. Go to **Trading > Strategies**
2. Click **From English**
3. Describe your strategy in plain language:

   > "Buy SPY when RSI(14) is below 30 and VIX is above 25. Exit when RSI crosses above 50 or I lose 5%."

4. AI translates your description into executable logic
5. Review the generated strategy
6. Edit if needed, then save

### What Happens Behind the Scenes

- Your English is converted to a structured strategy format
- The system validates all signals and parameters
- Invalid or unknown signals are automatically rejected
- Up to 3 retries if the first translation has issues
- Every rejection is logged for transparency

---

## Step 2: Critique (AI Review)

Before testing, get an adversarial AI review of your strategy.

### What the Critique Checks

| Issue Type | Example |
|------------|---------|
| **Survivorship bias** | "You're trading TSLA using only data from its best years" |
| **Look-ahead** | "Your indicator references prices that wouldn't be available yet" |
| **Regime fragility** | "RSI mean reversion only works in certain market conditions" |
| **Risk gaps** | "No stop loss defined — drawdowns will compound" |

### How to Use

1. Click the **Critique** button on your strategy
2. Read the AI's findings
3. Decide whether to address the issues or proceed

---

## Step 3: Backtest

Test your strategy against 90 days of historical data.

### Running a Backtest

1. Click **Backtest** on your strategy
2. Wait for results (usually under a minute)
3. Review the metrics

### Key Metrics

| Metric | What It Measures | Good Value |
|--------|------------------|------------|
| **Sharpe Ratio** | Risk-adjusted return | > 1.0 |
| **Sortino Ratio** | Downside risk-adjusted return | > 1.0 |
| **Max Drawdown** | Worst peak-to-trough decline | < 20% |
| **Win Rate** | Percentage of profitable trades | > 50% |
| **Profit Factor** | Gross profit / gross loss | > 1.5 |
| **Calmar Ratio** | Annual return / max drawdown | > 1.0 |

### Backtest Features

- **Realistic slippage** — simulates market impact
- **Safety guardrails** — stops if risk limits are breached
- **Transaction costs** — includes estimated fees
- **Tuning panel** — try different risk parameters without saving

---

## Step 4: Walk-Forward Testing

Detect overfitting by testing on data the strategy hasn't "seen."

### How It Works

1. Data is split into rolling windows
2. Strategy is optimized on each training portion
3. Performance is measured on the test portion
4. Results are compared across windows

### Understanding Results

| Result | Meaning |
|--------|---------|
| **Robust** | Test performance matches training — strategy generalizes well |
| **Borderline** | Some performance drop — proceed with caution |
| **Overfit** | Large drop in test performance — strategy may not work live |

### Key Metric: OOS/IS Ratio

- **Out-of-Sample (OOS)**: Performance on test data
- **In-Sample (IS)**: Performance on training data
- **Target**: Ratio ≥ 0.7 required for live graduation

---

## Step 5: Regime Stress Test

Test how your strategy performs during market crises.

### Crisis Periods Tested

| Regime | Period | What Happened |
|--------|--------|---------------|
| 2008 Financial Crisis | Oct 2007 – Jun 2009 | 50%+ market crash |
| COVID Crash | Feb – Apr 2020 | 34% crash in weeks |
| 2022 Rate Shock | Jan – Oct 2022 | Aggressive Fed tightening |
| Volmageddon | Feb – Apr 2018 | VIX spike, XIV blowup |
| Dot-com Bust | Mar 2000 – Oct 2002 | Tech bubble burst |
| Calm Baseline | 2019 | Control period |

### What to Look For

- No regime with > 30% loss
- No regime with > 20% drawdown
- Reasonable performance in at least 4 of 6 regimes

---

## Step 6: Paper Trading

Run your strategy with simulated money using live prices.

### How Paper Trading Works

- **Real-time prices** from live markets
- **Simulated execution** with realistic slippage
- **Full guardrail protection** — same safety as live
- **Trade history** — every fill is recorded
- **No real money at risk**

### Starting Paper Trading

1. Pass backtest and walk-forward requirements
2. Click **Paper Trade** on your strategy
3. Configure position size and risk limits
4. Click **Start**

### Monitoring Paper Trades

- View open positions and P&L
- See trade history with entry/exit details
- Check daily AI review (EOD Critic)
- Review slippage and sizing decisions

---

## Step 7: Graduation to Live

After paper trading, you can apply for live trading.

### Graduation Requirements

| Requirement | Why |
|-------------|-----|
| **Statistical Quality** (PSR ≥ 0.95) | Ensures observed performance isn't luck |
| **Walk-Forward Pass** (ratio ≥ 0.7) | Proves strategy generalizes |
| **Risk Acknowledgement** | You understand real money is at stake |
| **Broker Connected** | Live execution requires a real broker |
| **MFA Enabled** | Security requirement for live trading |

### Applying for Graduation

1. Meet all paper trading requirements
2. Connect a live broker at Settings > Brokers
3. Enable MFA at Settings > Security
4. Click **Graduate to Live** on your strategy
5. Sign the risk acknowledgement
6. Begin live trading

---

## Step 8: Live Execution

Live strategies execute real orders through your broker.

### Before First Live Trade

The system checks:
1. Your execution mode is set to "Live"
2. Platform-wide live trading is enabled
3. You've acknowledged the MFA-gated risk warning
4. Your broker connection is working

### Live Trading Features

- **Real orders** sent to your broker
- **Same guardrails** as paper trading
- **Daily AI review** of your strategy
- **Audit trail** of all decisions

---

## Safety Features

### Five Layers of Protection

| Layer | What It Does | Override |
|-------|--------------|----------|
| **L1: Account Limits** | Stops if daily loss or drawdown exceeded | Manual only |
| **L2: Strategy Circuit Breakers** | Pauses after consecutive losses | Auto-resumes after cooldown |
| **L3: Event Blackouts** | Skips trading during earnings, FOMC | Per-symbol, others continue |
| **L4: Anomaly Detection** | Pauses if slippage or regime changes | Auto-resumes when cleared |
| **L5: PANIC Button** | Kills all active strategies immediately | Manual restart |

### L1 and L5 Cannot Be Modified by AI

The system ensures that account-level safety limits and the emergency stop cannot be changed by any automated process.

---

## Pre-Trade Defenses

Three defenses run before every trade:

### 1. Slippage-Aware Sizing

Reduces order size if expected slippage would eat too much of your edge.

- Uses your actual trade history to estimate slippage
- Falls back to conservative defaults for new symbols
- Prevents oversized orders in illiquid markets

### 2. Correlation Haircut

Reduces position size if you're running multiple strategies on correlated assets.

- Prevents concentration risk across strategies
- Automatically detects correlation between holdings
- Applies a diversification adjustment

### 3. End-of-Day Critic

Daily AI review of every active strategy.

- Reviews last 24 hours of performance
- Can sign off (continue unchanged) or escalate
- Escalation triggers the full proposal/review process
- Cannot directly modify your strategy — only recommend

---

## Self-Modification (AI Jury)

If your strategy underperforms, the AI can propose changes.

### The Review Process

1. **Proposer** — generates a suggested change
2. **Critic** — adversarial review ("find what's wrong")
3. **Judge** — accept, reject, or escalate to human
4. **Confidence Check** — low confidence forces human review
5. **Backtest** — changes must pass 90-day validation

### Your Control Options

| Mode | Behavior |
|------|----------|
| **Full Autonomous** | AI applies approved changes automatically |
| **Semi-Autonomous** | AI proposes, you approve |
| **Manual Only** | No AI modifications allowed |

### Safety Limits

- Maximum 5 modifications per strategy run
- Low confidence always escalates to you
- All decisions are logged in the audit trail

---

## Managing Running Strategies

### Stop Individual Strategies

Click **Stop** on any running strategy to:
- Paper: close positions at current prices
- Live: flatten positions via your broker
- Preserve all history and data

### Resume Requests

If the server restarts while strategies are running:
- You'll see resume requests for interrupted strategies
- Review market conditions
- Click **Resume** or **Reject**

### Auto-Restart Settings

Configure how strategies behave after interruptions:
- **Auto-restart enabled** — resumes automatically
- **Max auto-restarts** — after N restarts, requires manual approval

---

## PANIC Button

Emergency stop for all active strategies.

### Position Handling Options

| Mode | What Happens | When to Use |
|------|--------------|-------------|
| **Close All** | Flatten everything immediately | Default — eliminates all risk |
| **Stop New Only** | Stop trading, keep positions | Only if you'll manage manually |
| **Close Longs Only** | Close longs, keep shorts | If shorts have protective stops |
| **Close Shorts Only** | Cover shorts, keep longs | Eliminates unlimited-loss risk |
| **Protect Shorts** | Set stop-loss on shorts, then stop | Emergency protection |

### Warning

Some modes leave positions exposed. Only use them if you intend to manage positions manually through your broker.

---

## Multi-Symbol Strategies

Strategies can trade multiple symbols simultaneously.

### How It Works

- Strategy logic runs for each symbol
- Cash is shared across the portfolio
- Equity is aggregated
- Event blackouts apply per-symbol

### Example

A strategy trading `[SPY, QQQ, IWM]`:
- Evaluates entry/exit for each symbol
- Can hold positions in all three
- If SPY has earnings, only SPY is blacked out

---

## Derivatives and Shorts

### Perpetual Swaps

- Available through Binance
- Leverage 1-125x depending on symbol
- No expiration date
- Funding rate costs/credits every 8 hours

### Futures

- Available through Interactive Brokers
- Standard contracts: ES, NQ, CL, GC, etc.
- Fixed expiration dates
- Quantity in contracts, not dollars

### Short Selling

Create strategies that profit when prices fall:

```
Entry: RSI(14) > 70 (overbought)
Direction: Short
Exit: RSI(14) < 50 or stop-loss
```

**Important**: Stop-losses on shorts trigger when price *rises*, not falls.

---

## Audit Trail

All AI decisions are logged and viewable.

### Audit Tabs

| Tab | Shows |
|-----|-------|
| **Rejections** | Failed translations and why |
| **Jury Decisions** | Modification proposals and verdicts |
| **EOD Critic** | Daily review results |

Each entry includes:
- Timestamp
- AI model used
- Decision and reasoning

---

## Troubleshooting

### Strategy Won't Translate

- Simplify your description
- Use explicit signal names (RSI, SMA, etc.)
- Check for contradictory conditions

### Backtest Takes Too Long

- Reduce the number of symbols
- Simplify strategy logic
- Try a shorter test period

### Can't Graduate to Live

1. Check PSR requirement (≥ 0.95)
2. Verify walk-forward pass (ratio ≥ 0.7)
3. Ensure broker is connected
4. Confirm MFA is enabled

### Live Order Rejected

- Verify broker connection
- Check account has sufficient funds
- Ensure symbol is tradeable
- Review position limits

---

## Best Practices

### Do

- Start with simple strategies
- Use paper trading extensively
- Set reasonable position sizes
- Keep stop-losses enabled
- Review AI critiques carefully
- Monitor live strategies daily

### Don't

- Skip paper trading
- Disable safety guardrails
- Ignore AI warnings
- Over-leverage positions
- Trade without stop-losses
- Set unrealistic expectations

---

## Quick Reference

### Where to Find Things

| Want | Location |
|------|----------|
| Create strategy | Trading > Strategies > From English |
| Backtest | Click Play icon on strategy row |
| Walk-forward | Click Activity icon |
| Stress test | Click AlertTriangle icon |
| Paper trade | Click TrendingUp icon |
| Safety settings | Strategy > Risk Controls |
| Broker setup | Settings > Brokers |
| Audit trail | Strategies > Audit button |

---

## Related Guides

- [Trading Wizard](./15-trading-wizard.md) — Guided strategy creation
- [Making Trades](./16-making-trades.md) — Manual trading
- [Broker Setup](./17-broker-setup-detailed.md) — Connect your broker
- [Algorithm Reference](./14-algorithm-reference.md) — Signal reference
- [Pattern Detection](./05-pattern-detection.md) — Technical patterns

---

*AI trading involves risk of loss. Only trade with money you can afford to lose. Past performance does not guarantee future results.*
