# Trading Wizards & Graduation Tracker

> **Shipped**: 2026-05-06
> **Status**: Complete
> **Components**: Algorithm Builder Wizard, Graduation Tracker, Mini-Tours

---

## Overview

Three interconnected features for guiding users through AI trading strategy creation and the mock→paper→live graduation process:

1. **Algorithm Builder Setup Wizard** — 7-step guided flow for creating and validating AI trading strategies
2. **Mock→Paper→Live Graduation Tracker** — Visual progression dashboard with per-algorithm metrics
3. **Mini-Tours** — Feature-specific guided tours triggered by "Take a Tour" buttons

---

## Feature 1: Algorithm Builder Setup Wizard

### Access

- **URL**: `/algorithms/setup`
- **Entry Point**: "Guided Setup" button on `/admin/algorithms` page
- **Data Attribute**: `data-tour="algorithm-wizard"`

### Wizard Steps

| Step | Purpose | Gate to Proceed |
|------|---------|-----------------|
| **Welcome** | Choose creation method, quick-path toggle | Method selected |
| **Create** | Enter/generate DSL (5 methods) | Algorithm saved (receives `algorithmId`) |
| **Critique** | LLM adversarial review | `overall_assessment` != 'block' |
| **Backtest** | 90-day test with 13 metrics | Sharpe ≥ 0.5, DD ≤ 25% |
| **Validate** | Walk-forward OOS/IS check | OOS/IS ratio ≥ 0.7 |
| **Stress** | Regime replay (2008, 2020, etc.) | No regime DD > 50% |
| **Complete** | Summary + start paper trading | — |

### Creation Methods

| Method | Description |
|--------|-------------|
| **From English** | Natural language → DSL translation (Recommended) |
| **Guided Builder** | Visual step-by-step builder with DSL Primitive Browser (New) |
| **From Template** | Start from proven strategy templates |
| **Write DSL** | Manual DSL composition |
| **Import JSON** | Import existing strategy file |

### Quick Path

Toggle available in Welcome step that skips optional validation steps (Critique, Validate). Useful for experienced users who want faster iteration.

### Files

```
packages/fe/src/components/algorithms/wizard/
├── AlgorithmBuilderWizard.tsx    # Main wizard with progress indicator
├── useWizardProgress.ts          # localStorage persistence (24h expiry)
├── types.ts                      # WizardState, step types, thresholds
├── index.ts                      # Exports
└── steps/
    ├── WelcomeStep.tsx           # Method selection + quick path toggle
    ├── CreateStep.tsx            # DSL manual/NL/import/template
    ├── CritiqueStep.tsx          # LLM pre-flight review
    ├── BacktestStep.tsx          # 90-day historical test
    ├── ValidateStep.tsx          # Walk-forward validation
    ├── StressTestStep.tsx        # Regime stress test
    └── CompleteStep.tsx          # Summary + paper launch

apps/web/src/app/algorithms/setup/
└── page.tsx                      # Wizard page route
```

### API Endpoints

| Endpoint | Method | Handler |
|----------|--------|---------|
| `/api/predict/v1/algorithms` | POST | `handleCreateAlgorithm` |
| `/api/predict/v1/algorithms/translate` | POST | `handleTranslateAlgorithm` |
| `/api/predict/v1/algorithms/:id/critique` | POST | `handleCritiqueAlgorithm` |
| `/api/predict/v1/algorithms/:id/backtest` | POST | `handleBacktestAlgorithm` |
| `/api/predict/v1/algorithms/:id/walk-forward` | POST | `handleWalkForwardBacktest` |
| `/api/predict/v1/algorithms/:id/stress-test` | POST | `handleStressTestAlgorithm` |
| `/api/predict/v1/algorithms/:id/paper` | POST | `handleStartPaperRun` |

### Progress Persistence

Wizard state is persisted to localStorage with 24-hour expiry:
- Key: `agencio-algorithm-wizard-progress`
- Auto-resume prompt on return
- Cleared on completion or manual reset

### AI Help Integration

Each step includes `AskAbout` buttons for contextual AI assistance:
- **Backtest Step**: Sharpe Ratio, Maximum Drawdown
- **Validate Step**: Walk-Forward Validation, Overfitting
- **Stress Test Step**: Stress Testing, Market Regimes
- **Wizard Header**: General wizard explanation

---

## Feature 2: Graduation Tracker

### Access

- **URL**: `/trading?tab=graduation`
- **Location**: "Graduation" tab in TradingDashboard
- **Data Attribute**: `data-tour="graduation-tracker"`

### Tiers

```
[1] Mock ———————— [2] Paper ———————— [3] Live
 ✓ Complete        ◉ Active           ○ Locked
```

| Tier | Requirements |
|------|--------------|
| **Mock** | Always available (default) |
| **Paper** | Broker configured + credentials verified |
| **Live** | 30 days paper experience + MFA acknowledged + admin approval |

### Algorithm Graduation Metrics

Each algorithm tracks 4 metrics for live graduation:

| Metric | Required | Purpose |
|--------|----------|---------|
| Days in Paper | 30 | Minimum time in paper trading |
| Trade Count | 50 | Minimum trades executed |
| Sharpe Ratio | ≥ 1.0 | Risk-adjusted return quality |
| Max Drawdown | ≤ 15% | Risk control |

### Files

```
packages/fe/src/components/trading/
├── GraduationTracker.tsx         # Main component (~600 lines)
├── TradingDashboard.tsx          # Includes graduation tab

packages/be/src/api/predict/v1/user/progression/
└── handlers.ts                   # handleGetUserProgression

apps/web/src/app/api/predict/v1/user/progression/
└── route.ts                      # GET endpoint
```

### API Response Shape

```typescript
interface UserProgressionResponse {
  currentTier: 'mock' | 'paper' | 'live';
  tiers: {
    mock: { complete: boolean };
    paper: {
      complete: boolean;
      requirements: {
        brokerConfigured: boolean;
        credentialsVerified: boolean;
      };
    };
    live: {
      complete: boolean;
      requirements: {
        paperExperienceDays: { current: number; required: number; met: boolean };
        adminApproval: boolean;
        mfaAcknowledged: boolean;
      };
    };
  };
  algorithms: AlgorithmProgress[];
}
```

### AI Help Integration

Header includes "Ask AI" button for explaining the graduation system:
- What are the requirements for each tier?
- Why is there a 30-day paper trading minimum?
- What metrics need to be met to graduate an algorithm?

---

## Feature 3: Mini-Tours

### Overview

Feature-specific guided tours that provide targeted onboarding for specific features.

### Available Tours

| Tour ID | Feature | Steps |
|---------|---------|-------|
| `algorithms-mini` | AI Algorithm Builder | 5 steps |
| `trading-mini` | Trading Dashboard | 4 steps |
| `datasets-mini` | Dataset Import | 4 steps |

### Files

```
packages/fe/src/store/mini-tours.ts    # Tour definitions + Zustand store
apps/web/src/app/api/predict/v1/user/mini-tours/complete/route.ts
```

### Tour State

- Stored in Zustand with `persist` middleware
- Completion synced to backend via `POST /api/predict/v1/user/mini-tours/complete`
- Per-tour completion tracking

### Usage

```tsx
import { useMiniToursStore, MINI_TOURS } from '@agencio-predict/fe/store';

function MyComponent() {
  const { startTour, hasCompletedTour } = useMiniToursStore();

  return (
    <button onClick={() => startTour('algorithms-mini')}>
      Take a Tour
    </button>
  );
}
```

---

## Database Migration

**Migration**: `db/migrations/175_onboarding_enhancements.sql`

```sql
-- User feature usage tracking
CREATE TABLE predict.user_feature_usage (
  user_id UUID REFERENCES auth.users(id),
  feature_id TEXT NOT NULL,
  first_used_at TIMESTAMPTZ DEFAULT NOW(),
  PRIMARY KEY (user_id, feature_id)
);

-- Risk acknowledgments for live trading
CREATE TABLE predict.user_risk_acknowledgments (
  user_id UUID REFERENCES auth.users(id),
  acknowledged_at TIMESTAMPTZ DEFAULT NOW(),
  risk_version TEXT DEFAULT 'v1',
  PRIMARY KEY (user_id)
);

-- Mini-tour completion tracking
CREATE TABLE predict.user_mini_tour_completions (
  user_id UUID REFERENCES auth.users(id),
  tour_id TEXT NOT NULL,
  completed_at TIMESTAMPTZ DEFAULT NOW(),
  steps_completed INTEGER DEFAULT 0,
  total_steps INTEGER DEFAULT 0,
  skipped BOOLEAN DEFAULT FALSE,
  PRIMARY KEY (user_id, tour_id)
);

-- Wizard progress tracking
CREATE TABLE predict.user_wizard_progress (
  user_id UUID REFERENCES auth.users(id),
  wizard_id TEXT NOT NULL,
  current_step TEXT NOT NULL,
  state JSONB DEFAULT '{}',
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  PRIMARY KEY (user_id, wizard_id)
);
```

---

## Integration Points

### Sidebar Navigation

Added `data-tour` attributes for tour targeting:
- `data-tour="algorithm-wizard"` on Guided Setup link
- `data-tour="graduation-tracker"` on Graduation tab
- `data-tour="datasets"` on Datasets page

### TradingDashboard

Added "graduation" to `TabType` union and `VALID_TABS` array:
```typescript
type TabType = 'overview' | 'positions' | ... | 'graduation';
```

### Admin Algorithms Page

Added Guided Setup button before "From English" in the header action bar.

---

## AI Assistant Integration

All major components include contextual AI help using the `AskAbout` component:

```tsx
import { AskAbout } from '../assistant';

// In component
<AskAbout
  topic="Sharpe Ratio"
  prompt="Explain the Sharpe Ratio for trading strategies..."
  className="text-xs"
/>
```

The AI assistant opens with a pre-filled, context-aware question about the specific topic, helping users understand complex trading concepts without leaving the workflow.

---

## Verification Checklist

- [ ] Navigate to `/algorithms/setup`, complete all 7 steps
- [ ] Verify algorithm created and paper run started
- [ ] Check `/trading?tab=graduation` shows correct tier and algorithm progress
- [ ] Test "Ask AI" buttons open assistant with correct prompts
- [ ] Test mini-tour completion persists to backend
- [ ] Verify localStorage wizard resume works after page reload

---

## Related Documentation

- `docs/12-algorithm-builder.md` — Full algorithm builder specification
- `docs/13-broker-integration.md` — Broker layer design
- `docs/33-trading-workflow.md` — 6-stage trading workflow
- `docs/AI-TRADING-USER-GUIDE.md` — End-user trading guide
