# AI Trading Guide

Create, test, and run AI-powered trading strategies — from a simple idea to live execution.

---

## Overview

The Algorithm Builder lets you create trading strategies in multiple ways:

1. **Natural Language** — Describe your strategy in plain English (Recommended)
2. **Guided Builder** — Build step-by-step with visual entry/exit conditions
3. **DSL Primitive Browser** — Explore 417 signal primitives across 14 categories
4. **Templates** — Start from proven strategy templates
5. **Manual DSL** — Write strategy code directly

All strategies go through a rigorous testing process before live trading.

---

## Creating Your First Strategy

### Step 1: Open the Strategy Builder
1. Navigate to **Trading > Strategies** (or **Admin > Algorithms** for full access)
2. Click **New Strategy**
3. Choose your creation method

### Step 2: Describe Your Strategy

**Using Natural Language** (Recommended for beginners):

Write what you want in plain English. For example:

> "Buy SPY when RSI drops below 30 and the 50-day moving average is above the 200-day moving average. Sell when RSI goes above 70 or price drops 5% from entry."

The AI will translate this into a testable strategy.

**Using the Guided Builder**:

1. Go to Trading > Algorithms > Primitives tab (or use "Guided Builder" in the wizard)
2. Browse 417 primitives across 14 categories:
   - **Price** — Current price, VWAP, volume, price changes
   - **Technical** — RSI, MACD, moving averages, Bollinger Bands, ATR
   - **Sentiment** — News score, social sentiment, analyst ratings, fear/greed
   - **Macro** — VIX levels, yield curve, Fed funds, economic indicators
   - **Prediction Markets** — Polymarket/Kalshi probabilities
   - **Pattern** — FVG zones, candlestick patterns, support/resistance
   - **Options** — Implied volatility, put/call ratio, gamma exposure
   - **PINN** — Physics-Informed Neural Network predictions
   - **Fundamental** — P/E ratio, earnings, revenue growth
   - **Position** — Current position info, P&L, holding periods
   - **Sizing** — Kelly criterion, volatility-adjusted sizing
   - **Composer** — Combine signals with all(), any(), count()
   - **Weather** — El Nino, climate risk indicators
   - **LLM** — AI-powered analysis and event detection

3. Use the Simple Strategy Builder to visually create entry/exit conditions
4. Copy the generated DSL or click "Create Strategy"

### Step 3: AI Review
After creating your strategy, the AI performs an adversarial review:

- Looks for logical flaws
- Identifies potential risks
- Suggests improvements
- Validates against best practices

You'll see a critique report with any concerns.

---

## Testing Your Strategy

### Backtest (90 Days)
Test against historical data:

1. Click **Backtest**
2. Choose date range and starting capital
3. Run the test
4. Review results:

| Metric | What It Means |
|--------|---------------|
| Total Return | Overall profit/loss percentage |
| Sharpe Ratio | Risk-adjusted return (higher is better) |
| Max Drawdown | Largest peak-to-trough decline |
| Win Rate | Percentage of profitable trades |
| Trade Count | Number of trades executed |

**Good benchmarks**: Sharpe > 1.0, Max Drawdown < 20%, Win Rate > 50%

### Walk-Forward Validation
Test on data the strategy hasn't "seen":

1. Click **Walk-Forward**
2. The system trains on 70% of data, tests on 30%
3. Results show out-of-sample performance
4. Look for **consistency** between in-sample and out-of-sample

### Stress Testing
Test against historical crisis periods:

| Scenario | Period | What It Tests |
|----------|--------|---------------|
| 2008 Financial Crisis | Sep-Nov 2008 | Market crash |
| COVID Crash | Feb-Mar 2020 | Rapid decline |
| 2022 Bear Market | Jan-Oct 2022 | Prolonged downturn |
| Flash Crash | May 6, 2010 | Sudden volatility |

A good strategy should survive (or at least limit losses) in crisis scenarios.

---

## Paper Trading

After testing, run your strategy in paper mode:

### Starting Paper Trading
1. Click **Start Paper Trading**
2. Confirm your settings
3. The strategy runs with simulated execution

### What Paper Trading Simulates
- Real market data
- Realistic order fills (with slippage)
- Position tracking
- P&L calculation

### Monitoring Paper Trades
- View real-time positions
- Track cumulative performance
- See individual trade history
- Review AI commentary on trades

### Graduation Requirements
To move from paper to live, you need:

| Requirement | Threshold |
|-------------|-----------|
| Days in paper | 30 minimum |
| Trade count | 50+ trades |
| Sharpe ratio | ≥ 1.0 |
| Max drawdown | ≤ 15% |

---

## Live Trading

### Prerequisites
Before going live:
- MFA enabled on your account
- Broker account connected and tested
- Paper trading requirements met
- Strategy approved by system review

### Starting Live Trading
1. Request live approval (automatic if requirements met)
2. Confirm broker connection
3. Acknowledge risk disclosures
4. Click **Go Live**

### Live Safeguards
Multiple layers protect your capital:

| Safeguard | What It Does |
|-----------|--------------|
| Daily Loss Limit | Stops trading if daily loss exceeds threshold |
| Position Limits | Caps maximum position size |
| Correlation Monitor | Reduces exposure when strategies correlate |
| Order Limits | Maximum order size per trade |
| Kill Switch | Instantly stop all trading |

### Stopping a Live Strategy
- Click **Stop** on the strategy
- Choose: **Flatten positions** (sell everything) or **Hold positions** (stop new trades only)
- Strategy enters cooldown period

---

## Strategy Self-Modification

Your strategy can adapt over time with AI assistance.

### Modification Modes

**Mode 1: Manual Only** (Safest)
- AI analyzes performance
- You review suggestions
- You manually approve any changes

**Mode 2: AI-Proposed, Human-Approved** (Default for live)
- AI proposes improvements
- Changes require your approval
- Full transparency on what's changing

**Mode 3: Autonomous** (Advanced)
- AI makes changes within defined bounds
- Daily review by AI critic
- Escalation on concerns

### The AI Jury System
For significant changes, a three-part review:

1. **Proposer** — Suggests the change
2. **Critic** — Challenges the proposal
3. **Judge** — Makes final decision

Changes are only applied if the judge approves with high confidence.

---

## Understanding Signals

### Technical Signals
| Signal | Description |
|--------|-------------|
| RSI | Relative Strength Index (0-100) |
| MACD | Trend and momentum indicator |
| SMA/EMA | Moving averages (50, 200 day) |
| Bollinger | Volatility bands |
| ATR | Average True Range (volatility) |

### Sentiment Signals
| Signal | Description |
|--------|-------------|
| News Score | Aggregated news sentiment |
| Social Score | Reddit/Twitter sentiment |
| Analyst Rating | Buy/hold/sell consensus |
| Human vs Bot | Automation detection |

### Macro Signals
| Signal | Description |
|--------|-------------|
| VIX Level | Market fear gauge |
| Yield Curve | Bond market signal |
| Fed Funds | Interest rate environment |

### Pattern Signals
| Signal | Description |
|--------|-------------|
| FVG Detected | Fair Value Gap present |
| Support Bounce | Price near support |
| Breakout | Price breaking resistance |

---

## Risk Management

### Position Sizing
Control how much to invest per trade:

- **Fixed Amount** — Same dollar amount each trade
- **Percent of Portfolio** — Percentage of total value
- **Kelly Criterion** — Mathematically optimal sizing
- **Volatility-Adjusted** — Smaller positions in volatile markets

### Stop Losses
Automatic exit when trade goes against you:

- **Fixed Percentage** — Exit at X% loss
- **Trailing Stop** — Moves up with price, locks in gains
- **ATR-Based** — Based on volatility

### Daily Limits
Platform-wide protections:

| Limit | Default | Adjustable |
|-------|---------|------------|
| Daily loss | 5% | Yes |
| Max position | 25% of portfolio | Yes |
| Max orders/day | 100 | Yes |

---

## Supported Asset Classes

| Asset Class | Brokers | Notes |
|-------------|---------|-------|
| US Stocks | Alpaca, IBKR, Schwab | Full support |
| US ETFs | Alpaca, IBKR, Schwab | Full support |
| Crypto | Binance | Spot and perpetuals |
| Forex | Pepperstone | 70+ pairs |
| Options | IBKR | Coming soon |

---

## Best Practices

### Do
- Start with simple strategies
- Test thoroughly before paper trading
- Paper trade for at least 30 days
- Monitor live strategies daily
- Set appropriate position limits

### Don't
- Skip backtesting
- Ignore the AI critique
- Over-optimize for historical data
- Risk more than you can afford to lose
- Set it and forget it completely

---

## Troubleshooting

### Strategy Won't Start
- Check broker connection
- Verify sufficient buying power
- Ensure MFA is enabled
- Review any error messages

### Poor Performance
- Compare to backtest results
- Check for market regime change
- Review recent trades for issues
- Consider parameter adjustments

### Unexpected Trades
- Review strategy logic
- Check for signal conflicts
- Verify position sizing settings
- Contact support if unexplained

---

## Next Steps

1. **Create a simple strategy** — Start with one or two signals
2. **Backtest it** — See how it would have performed
3. **Paper trade** — Run it with simulated money
4. **[Set up a broker](./04-broker-setup.md)** — Enable real execution

---

*Trading involves risk. Past performance does not guarantee future results.*
