# 44 — Pattern Detection & AI Features Reference

> **Status**: Complete as of 2026-05-06
> **Purpose**: Comprehensive documentation of all pattern matching, anomaly detection, and AI classification features
> **Audit status**: Verified against code in `packages/be/src/` — Full audit 2026-05-06

---

## Table of Contents

1. [Price Action Patterns](#1-price-action-patterns)
2. [Gap Detection & Opportunities](#2-gap-detection--opportunities)
3. [Candlestick Patterns](#3-candlestick-patterns)
4. [Flow Pattern Detection](#4-flow-pattern-detection)
5. [Black Swan Detection](#5-black-swan-detection)
6. [Paradox Detection](#6-paradox-detection)
7. [Whale/Bot Classification](#7-whalebot-classification)
8. [Sentiment Analysis](#8-sentiment-analysis)
9. [Market Regime Detection](#9-market-regime-detection)
10. [DSL Signal Primitives](#10-dsl-signal-primitives)
11. [Pattern Auto-Trading](#11-pattern-auto-trading)
11b. [User Pattern Import](#11b-user-pattern-import-custom-patterns-with-ai-validation)
11c. [Pattern Timing Analysis](#11c-pattern-timing-analysis-time-of-day--day-of-week)
12. [Database Schema](#12-database-schema)
13. [API Endpoints](#13-api-endpoints)
14. [UI Pages & Components](#14-ui-pages--components)
15. [Configuration & Thresholds](#15-configuration--thresholds)

---

## 1. Price Action Patterns

### 1.1 Fair Value Gap (FVG) Detection

**File**: `packages/shared/src/fvg.ts`

| Pattern | Detection Logic |
|---------|-----------------|
| **Bullish FVG** | 3-candle pattern where `candle[i].low > candle[i-2].high` (gap above) |
| **Bearish FVG** | 3-candle pattern where `candle[i].high < candle[i-2].low` (gap below) |
| **Tapped State** | Gap is filled when later candle wick enters the zone |

```typescript
detectFVGs(candles, { minSizePct?: number }): FVG[]

interface FVG {
  type: 'bullish' | 'bearish';
  high: number;
  low: number;
  size: number;
  filled: boolean;
  filledAt?: string;
}
```

### 1.2 Price Action Pattern Detector

**File**: `packages/be/src/insights/price-action-patterns.ts`

| Pattern | Description | State Machine |
|---------|-------------|---------------|
| `cluster_breakout_retest` | Price breaks cluster, taps, continues | forming → triggered → confirmed/failed |
| `support_bounce` | Bullish bounce off support level | n/a |
| `resistance_rejection` | Bearish rejection at resistance | n/a |
| `breakout_continuation` | Breakout followed by trend continuation | n/a |
| `false_breakout` | Breakout that failed and reversed | n/a |
| `double_bottom/top` | Classic reversal patterns | framework |
| `higher_low/lower_high` | Trend continuation patterns | n/a |

**Configuration**:
```typescript
MIN_BARS = 20                    // Minimum bars for detection
CLUSTER_LOOKBACK = 20            // Days to look for clusters
MAX_CLUSTER_RANGE_PCT = 3.0      // Max cluster range
MIN_BARS_IN_CLUSTER = 5          // Min bars to form cluster
RETEST_TOLERANCE_PCT = 0.5       // Retest price tolerance
SWING_WINDOW = 3                 // Bars for swing detection
MIN_CONFIDENCE = 0.4             // Minimum pattern confidence
```

**Output**:
```typescript
interface PriceActionPattern {
  type: PatternType;
  status: 'forming' | 'triggered' | 'confirmed' | 'failed';
  direction: 'bullish' | 'bearish';
  confidence: number;  // 0-1
  evidence: string[];
  tradeSuggestion?: { entry, stop, target };
}
```

---

## 2. Gap Detection & Opportunities

**File**: `packages/be/src/trading/gap-detection/index.ts` (591 lines)

### 2.1 Gap Types (8 Categories)

| Gap Type | Description | Detection Method |
|----------|-------------|------------------|
| `fvg` | Fair Value Gap | 3-candle price gap |
| `arbitrage` | Cross-market arbitrage | Price divergence across exchanges |
| `stat_arb` | Statistical arbitrage | Mean reversion opportunity |
| `liquidity` | Liquidity gap | Volume/spread anomaly |
| `event` | Event-driven gap | News/earnings gap |
| `opening` | Opening gap | Overnight price change |
| `breakaway` | Breakaway gap | Trend continuation gap |
| `exhaustion` | Exhaustion gap | Trend reversal signal |

### 2.2 Fill Probability Model

```typescript
interface GapOpportunity {
  type: GapType;
  symbol: string;
  assetClass: AssetClass;
  direction: 'bullish' | 'bearish';
  gapPct: number;
  fillProbability: number;      // 0-1, learned from historical fills
  expectedFillTime: number;      // Hours
  tradeSuggestion: {
    entry: number;
    stop: number;
    target: number;
    riskRewardRatio: number;
  };
  confidence: number;            // 60 + (gapPct × 10), capped at 95
}
```

### 2.3 Historical Fill Rates

| Gap Type | Direction | Avg Fill Rate | Avg Fill Time |
|----------|-----------|---------------|---------------|
| FVG | Bullish | ~72% | 2-5 days |
| FVG | Bearish | ~68% | 2-5 days |
| Opening | — | ~80% | Same day |
| Breakaway | — | ~45% | Variable |

### 2.4 Outcome Tracking

- `resolution`: filled, expired, invalidated
- `actual_fill_time`, `actual_fill_price`
- `prediction_accuracy`: Used to improve future probability estimates

---

## 3. Candlestick Patterns

**File**: `packages/be/src/algorithms/dsl/types.ts` (lines 677-725)

### 3.1 Single-Candle Patterns (6)

| Pattern | DSL Primitive | Detection |
|---------|---------------|-----------|
| Doji | `doji()` | Open ≈ Close (< 0.1% body) |
| Hammer | `hammer()` | Small body at top, long lower wick (2x+ body) |
| Inverted Hammer | `inverted_hammer()` | Small body at bottom, long upper wick |
| Shooting Star | `shooting_star()` | Like inverted hammer but after uptrend |
| Marubozu Bullish | `marubozu_bullish()` | Full body candle, no wicks, close > open |
| Marubozu Bearish | `marubozu_bearish()` | Full body candle, no wicks, close < open |

### 3.2 Two-Candle Patterns (2)

| Pattern | DSL Primitive | Detection |
|---------|---------------|-----------|
| Engulfing Bullish | `engulfing_bullish()` | Green candle fully engulfs prior red |
| Engulfing Bearish | `engulfing_bearish()` | Red candle fully engulfs prior green |

### 3.3 Three-Candle Patterns (4)

| Pattern | DSL Primitive | Detection |
|---------|---------------|-----------|
| Morning Star | `morning_star()` | Red → small body → green (bullish reversal) |
| Evening Star | `evening_star()` | Green → small body → red (bearish reversal) |
| Three White Soldiers | `three_white_soldiers()` | 3 consecutive green candles, higher closes |
| Three Black Crows | `three_black_crows()` | 3 consecutive red candles, lower closes |

### 3.4 Chart Patterns (4)

| Pattern | DSL Primitive | Detection |
|---------|---------------|-----------|
| Double Bottom | `double_bottom(lookback, tolerance_pct)` | Two lows within tolerance |
| Double Top | `double_top(lookback, tolerance_pct)` | Two highs within tolerance |
| Bull Flag | `bull_flag(lookback)` | Strong up move → consolidation |
| Bear Flag | `bear_flag(lookback)` | Strong down move → consolidation |

### 3.5 Trend Patterns (4)

| Pattern | DSL Primitive | Detection |
|---------|---------------|-----------|
| Higher Highs | `higher_highs(lookback)` | Successive higher swing highs |
| Higher Lows | `higher_lows(lookback)` | Successive higher swing lows |
| Lower Highs | `lower_highs(lookback)` | Successive lower swing highs |
| Lower Lows | `lower_lows(lookback)` | Successive lower swing lows |

### 3.6 Candlestick Pattern Scanner (2026-05-07)

**File**: `packages/be/src/insights/candle-pattern-scanner.ts`

Real-time scanner that scans multiple symbols for candlestick pattern occurrences with backtest statistics.

#### Supported Patterns (18)

| Category | Patterns |
|----------|----------|
| **Single Bar (6)** | hammer, inverted_hammer, hanging_man, shooting_star, doji, marubozu |
| **Two Bar (8)** | bullish_engulfing, bearish_engulfing, bullish_harami, bearish_harami, piercing_line, dark_cloud_cover, tweezer_top, tweezer_bottom |
| **Three Bar (4)** | morning_star, evening_star, three_white_soldiers, three_black_crows |

#### API

```typescript
// Scan for pattern across symbols
POST /api/predict/v1/patterns/candle-scan
Body: {
  pattern: string,        // e.g., 'bullish_engulfing'
  symbols?: string[],     // Optional, defaults to user watchlist
  lookbackDays?: number,  // Default: 90
  maxResults?: number,    // Default: 50
  outcomeHorizon?: number // Bars to check outcome, default: 5
}

// Response
{
  data: {
    pattern: string,
    patternName: string,
    direction: 'bullish' | 'bearish' | 'neutral',
    reliability: 'high' | 'medium' | 'low',
    matches: Array<{
      symbol: string,
      timestamp: string,
      entryPrice: number,
      currentPrice: number,
      outcomePercent: number | null,
      isWin: boolean | null,
      barsAgo: number
    }>,
    stats: {
      totalOccurrences: number,
      winRate: number,
      avgReturn: number,
      bySymbol: Record<string, { count: number, winRate: number }>
    }
  }
}

// Get all pattern types
GET /api/predict/v1/patterns/candle-scan/types
```

#### UI Integration

The `/patterns` page "Candle Patterns" tab now includes:
- **Clickable pattern cards**: Click any pattern to scan watchlist
- **Detail panel**: Shows scan results, statistics, recent matches
- **Jump-to-chart**: Navigate directly to `/trading/{symbol}` for any match
- **Per-symbol breakdown**: Win rate and occurrence count per symbol

---

## 4. Flow Pattern Detection

**File**: `packages/be/src/flow/patterns.ts` (266 lines)

### 4.1 Flow Pattern Types (8)

| Pattern | Detection | Interpretation |
|---------|-----------|----------------|
| `spike` | Z-score ≥ 2.0 vs 30-day history | Unusual flow volume |
| `regime_flip` | Direction reversal between snapshots | Market sentiment shift |
| `risk_off` | Aggregate flow to safe-haven nodes | Flight to safety |
| `risk_on` | Aggregate flow to risky assets | Risk appetite |
| `credit_decoupling` | IG/HY spread divergence | Credit stress signal |
| `coordinated_flow` | 3+ edges sharing source/target above threshold | Institutional activity |
| `catalyst_reaction` | Edge movement within 2h of catalyst | News-driven flow |
| `pre_catalyst_anomaly` | Unusual flow < 4h BEFORE catalyst | Potential leak/insider |

### 4.2 Configuration

```typescript
SPIKE_ZSCORE_THRESHOLD = 2.0
RISK_FLOW_THRESHOLD = 0.15
COORDINATED_MIN_EDGES = 3
CATALYST_WINDOW_HOURS = 2
PRE_CATALYST_WINDOW_HOURS = 4
```

---

## 5. Black Swan Detection

**File**: `packages/be/src/all-seeing-eye/black-swan/detector.ts`

### 5.1 Anomaly Detection

| Metric | Threshold | Meaning |
|--------|-----------|---------|
| Z-Score | 2.5 sigma | 1-in-80 event (p ≈ 0.012) |
| Minimum samples | 30 | Required for reliability |

### 5.2 Event Type Classification (12 Types)

| Event Type | Triggering Signals |
|------------|-------------------|
| `market_crash` | S&P, NASDAQ, DOW collapse, VIX spike |
| `flash_crash` | Sudden S&P drop, VIX spike, volume anomaly |
| `liquidity_crisis` | Treasury yields, credit spreads, HY/IG ratio |
| `currency_crisis` | DXY, EURUSD, emerging FX |
| `geopolitical` | Gold, Oil, defense stocks, VIX |
| `pandemic` | Healthcare, travel, retail, sentiment |
| `infrastructure` | Utilities, tech, cloud providers |
| `cyber` | Tech, security stocks, crypto |
| `natural_disaster` | Insurance, utilities, REITs |
| `regulatory` | Crypto, fintech, banking |
| `contagion` | Emerging markets, high-yield spreads |
| `systemic` | Banking, financial sector, credit |

### 5.3 Leading Indicator Signals

| Signal | Detection | Threshold |
|--------|-----------|-----------|
| **Yield Curve Inversion** | 3M-10Y, 2s10s, 5s30s spreads | < 0 (inverted) |
| **Credit Spread Breakout** | HY spread, HY/IG ratio | 90th+ percentile |
| **MOVE-VIX Divergence** | Bond vol spike, equity VIX calm | MOVE > 100, VIX < 20 |
| **Real Yield Stress** | TIPS yields, breakeven inflation | Spike or collapse |
| **SOFR Funding Stress** | SOFR - Fed Funds spread | > 25bps stress, > 50bps crisis |
| **Peripheral Contagion** | BTP-Bund spread | > 200bps stress, > 300bps crisis |

### 5.4 Severity Levels

```
elevated → high → severe → extreme
```

Calculated from: anomaly score, max Z-score, correlation breaks, convergence.

---

## 6. Paradox Detection

**Files**:
- `packages/be/src/all-seeing-eye/insights/paradox-detector.ts`
- `packages/be/src/all-seeing-eye/insights/paradox-rules.ts`
- `packages/be/src/all-seeing-eye/calibration/` (historical crisis data)

### 6.1 Paradox Context (18 Rules)

```typescript
interface ParadoxContext {
  vix: number;
  spyReturn1d: number;
  spyReturn1w: number;
  yield10Y: number;
  yieldSpread2s10s: number;
  economicSurpriseIndex: number;
  headlineSentiment: number;
  geopoliticalIntensity: number;
  activeGeopoliticalEvents: string[];
  marketRegime: MarketRegime;
  btcReturn1d: number;
  goldReturn1d: number;
  cryptoFearGreed: number;
  leadingIndicators: {
    moveIndex: number;
    realYield10Y: number;
    breakeven5Y: number;
    sofrRate: number;
    fedFundsRate: number;
    hySpread: number;
    igSpread: number;
    btpBundSpread: number;
    curveSlope3m10y: number;
    curveSlope5s30s: number;
  };
}
```

### 6.2 Regime-Aware Thresholds (Migration 161)

| Regime | SOFR Stress | MOVE Panic | HY Elevated |
|--------|-------------|------------|-------------|
| Pre-2008 | 25bps | 150 | 400bps |
| ZIRP 2009-15 | 25bps | 130 | 500bps |
| Normalization 2015-19 | 25bps | 120 | 450bps |
| Pandemic 2020-21 | 15bps | 160 | 550bps |
| Inflation 2022-23 | 30bps | 170 | 500bps |
| **Post-2023** | **40bps** | 150 | 550bps |

**Note**: Post-2023 SOFR threshold raised because SOFR structurally trades 10-25bps above Fed Funds.

### 6.3 False Positive Tracking

- Records every paradox trigger with signal snapshot
- Maps 18 rules to expected outcomes (equity_selloff, credit_crisis, etc.)
- Tracks actual SPY return / VIX change in outcome window
- Calculates FP rate per rule over time

---

## 7. Whale/Bot Classification

**File**: `packages/be/src/insights/tick-classifier.ts`

### 7.1 Classification Labels (6 Buckets)

| Label | Criteria |
|-------|----------|
| `retail` | Whale ratio < 0.25, bot signature < 0.30 |
| `market_maker` | Bot signature ≥ 0.55, \|imbalance\| ≤ 0.15 |
| `fund_rebalance` | Whale ratio ≥ 0.40, bot signature < 0.50, directional |
| `liquidation_cascade` | Whale ≥ 0.40, bot ≥ 0.50, imbalance ≤ -0.35 |
| `coordinated` | Bot ≥ 0.70, \|imbalance\| ≥ 0.45 |
| `unknown_flow` | Mixed evidence |

### 7.2 Core Metrics

| Metric | Range | Formula |
|--------|-------|---------|
| **Whale Ratio** | 0-1 | Top 5% trade sizes / total volume |
| **Bot Signature** | 0-1 | Weighted: round nums (¼) + repeated size (¼) + sub-second bursts (½) |
| **Aggressor Imbalance** | -1 to +1 | (Buy Vol - Sell Vol) / Total Vol |

### 7.3 Advanced Microstructure Metrics

| Metric | Purpose | Threshold |
|--------|---------|-----------|
| **VPIN** | Informed trading probability | > 0.5 = elevated toxicity |
| **Kyle's Lambda** | Price impact coefficient | High = low liquidity |
| **Bimodality** | Retail vs institutional mix | BC > 0.555 = bimodal |
| **Trailing Digit Entropy** | Bot detection | Low = algorithmic |
| **Interarrival Variance** | Timing analysis | Low = bot |

### 7.4 Data Sources

| Asset Class | Source | Direction Available |
|-------------|--------|-------------------|
| Crypto | Binance aggTrades | Yes (isBuyerMaker) |
| Equities | Polygon trades | No (needs tick-rule inference) |
| Forex | — | Not available |

---

## 8. Sentiment Analysis

**File**: `packages/be/src/insights/divergence-engine.ts`

### 8.1 Divergence Classification (5 States)

| Class | Condition | Interpretation |
|-------|-----------|----------------|
| `HUMAN-DRIVEN` | Sentiment + price correlated (r ≥ 0.30) | Real conviction |
| `BOT-LIKELY` | Price moved, sentiment flat | Algorithmic |
| `SOCIAL-NOISE` | Sentiment moved, price flat | No follow-through |
| `QUIET` | Neither moved | Low activity |
| `INSUFFICIENT` | < 4 price days or 0 sentiment days | No data |

### 8.2 Thresholds

```typescript
SENTIMENT_MOVE_THRESHOLD = 0.10   // |Δ avg_sentiment| in [-1, 1]
PRICE_MOVE_THRESHOLD = 0.02       // 2%
CORRELATION_HUMAN_THRESHOLD = 0.30 // Pearson r
MIN_DAYS_PRICE = 4
MIN_DAYS_SENTIMENT = 3
```

### 8.3 Sentiment Sources

Priority order:
1. **Ticker-specific** — UPPERCASE symbol as topic (highest priority)
2. **Generic fallback** — Asset-class topics (stocks, crypto, fx)
3. **None** — When no data available

### 8.4 Composite Human-Automation Score

**File**: `packages/be/src/insights/composite-score.ts`

Output: Single signal in [-1, +1]
- +1 = human-dominated
- -1 = bot-dominated

**Sub-inputs**:
- Divergence score
- Crypto funding-rate extremity (> 0.05% per 8h = extreme)
- VIX regime bias (75th percentile = risk-off, 25th = low-vol)

---

## 9. Market Regime Detection

**File**: `packages/be/src/trading/services/market-regime-detector.ts`

### 9.1 Five Regimes

| Regime | Conditions |
|--------|------------|
| `BULL` | Trend > 0.3, VIX < 20, fear/greed > 50 |
| `BEAR` | Trend < -0.3, VIX > 20 |
| `SIDEWAYS` | Default (range-bound) |
| `CRISIS` | VIX ≥ 40 OR (correlation spike AND VIX ≥ 30) |
| `RECOVERY` | Trend > 0.2, VIX > 20, fear/greed < 40 |

### 9.2 VIX Thresholds

```typescript
VIX_LOW = 15
VIX_MODERATE = 20
VIX_HIGH = 30
VIX_EXTREME = 40
```

### 9.3 Regime-Based Risk Multipliers

| Regime | Risk Multiplier | Kelly Fraction |
|--------|-----------------|----------------|
| BULL | 1.2x | 0.50 |
| BEAR | 0.7x | 0.30 |
| SIDEWAYS | 1.0x | 0.40 |
| CRISIS | 0.3x | 0.25 |
| RECOVERY | 0.9x | 0.35 |

### 9.4 Algorithm Recommendations by Regime

| Regime | Best Strategies |
|--------|----------------|
| BULL | momentum (1.5x), trend-following (1.4x), breakout (1.3x) |
| BEAR | mean-reversion (1.4x), volatility (1.3x), technical (1.2x) |
| SIDEWAYS | mean-reversion (1.5x), range-bound (1.4x), technical (1.3x) |
| CRISIS | volatility (1.5x), risk-parity (1.4x), ensemble (1.2x) |
| RECOVERY | momentum (1.3x), trend-following (1.2x), technical (1.2x) |

---

## 10. DSL Signal Primitives

**File**: `packages/be/src/algorithms/dsl/types.ts`

### 10.1 Pattern Detection Primitives (18)

```typescript
// FVG Patterns
fvg_bullish(lookback: number) → boolean
fvg_bearish(lookback: number) → boolean
fvg_count(type: 'bullish'|'bearish', lookback: number) → number
price_in_fvg() → boolean
fvg_distance_pct() → number

// Candlestick Patterns
hammer() → boolean
doji() → boolean
morning_star() → boolean
evening_star() → boolean
engulfing_bullish() → boolean
engulfing_bearish() → boolean

// Chart Patterns
double_bottom(lookback: number) → boolean
double_top(lookback: number) → boolean
bull_flag(lookback: number) → boolean
bear_flag(lookback: number) → boolean
higher_highs(count: number) → boolean
higher_lows(count: number) → boolean
lower_highs(count: number) → boolean
lower_lows(count: number) → boolean
```

### 10.2 Crypto Edge Primitives (4)

```typescript
pump_dump_detected(symbol: string) → boolean
funding_rate_extreme(symbol: string) → boolean
liquidation_cascade(symbol: string) → boolean
fear_greed_index() → number  // 0-100
```

### 10.3 Human-Automation Primitives (2)

```typescript
human_automation_score(symbol: string) → number    // [-1, +1]
human_automation_confidence(symbol: string) → number // [0, 1]
```

### 10.4 Macro Overlay Primitives (7) — All-Seeing Eye Integration

**Files:**
- `packages/be/src/algorithms/macro-overlay-provider.ts` — Data provider
- `packages/be/src/algorithms/paper/executor.ts` — Live context wiring (lines 1462-1490)
- `packages/be/src/algorithms/backtest/engine.ts` — Backtest stubs (lines 972-978)

**Status (Updated 2026-05-06):** ✅ All primitives fully wired to executor

```typescript
// Paradox Detection
paradox_severity() → number              // 0-100, higher = more paradoxes active
paradox_active(type: string) → boolean   // Check specific paradox rule
// Types: vix-complacency, bad-news-rally, yield-equity-divergence,
//        fear-greed-mismatch, prediction-engine, crisis-calm, inversion-rally,
//        crypto-equity-decouple, vix-spike-no-selloff, surprise-regime-mismatch

// Narrative Synthesis
narrative_confidence() → number          // 0-1, LLM confidence in market thesis
narrative_theme(keyword: string) → boolean // Check if narrative matches keyword
// Examples: "fed-pivot", "recession", "rally", "complacency"

// Geopolitical & Economic
geopolitical_intensity() → number        // 0-100, geopolitical risk level
surprise_index() → number                // -100 to +100, economic data vs expectations
regime_mismatch() → boolean              // True if regime contradicts sentiment
```

**Backtest Behavior:**
| Primitive | Live/Paper | Backtest Stub |
|-----------|------------|---------------|
| `paradox_severity()` | Real ASE data | 0 (no paradoxes) |
| `paradox_active(type)` | Real ASE data | false |
| `narrative_confidence()` | Real ASE data | 0.5 (neutral) |
| `narrative_theme(keyword)` | Real ASE data | false |
| `geopolitical_intensity()` | Real ASE data | 20 (low baseline) |
| `surprise_index()` | Real ASE data | 0 (neutral) |
| `regime_mismatch()` | Real ASE data | false |

**Live Status Indicators:**
These values are visible in `/admin/algorithms` LiveStatusPanel:
- `paradoxSeverity`, `narrativeConfidence`, `geoIntensity`, `surpriseIndex`

### 10.5 Regime-Aware Sizing (1 — NEW 2026-05-04)

```typescript
kelly_regime_aware(win_prob: number, payoff_ratio: number, max_position_usd: number) → number
// Auto-scales Kelly by regime:
// BULL=0.50, SIDEWAYS=0.40, RECOVERY=0.35, BEAR=0.30, CRISIS=0.25
```

### 10.6 Pattern Statistics Primitives (7)

**File**: `packages/be/src/algorithms/paper/pattern-context.ts`

These primitives provide statistically-validated pattern trading signals:

```typescript
// Hit Rate & Sample Size
pattern_hit_rate(type: string, direction?: string) → number      // 0-1, Wilson score estimate
pattern_sample_size(type: string, direction?: string) → number   // Number of historical observations
pattern_is_significant(type: string, direction?: string) → boolean // p < 0.05

// Warming & Proximity
pattern_proximity(type: string) → number                         // 0-100, how close to triggering
pattern_active(type: string, symbol?: string) → boolean          // Is pattern forming/triggered?

// Effect Size & Confidence Intervals
pattern_effect_size(type: string, direction?: string) → number   // Cohen's d
pattern_confidence_lower(type: string, direction?: string) → number // Lower bound 95% CI
```

**Pattern Types**: `support_bounce`, `resistance_rejection`, `cluster_breakout_retest`, `double_bottom`, `double_top`, `higher_low`, `lower_high`, `fvg_fill`, `false_breakout`

### 10.7 DTW Template Primitives (4 — NEW 2026-05-10)

**Files**:
- `packages/be/src/algorithms/dsl/types.ts` — Primitive definitions
- `packages/be/src/insights/dtw-pattern-matcher.ts` — Matching engine

DTW templates allow users to capture custom chart patterns and use them as trading signals.

```typescript
dtw_template_match(threshold: number) → boolean     // True if any template matches at ≥threshold%
dtw_template_similarity() → number                  // 0-100, similarity score of best match
dtw_template_direction() → string                   // "bullish", "bearish", or "neutral"
dtw_template_name() → string                        // Name of the best matching template
```

**Example**:
```yaml
entry:
  when: all(dtw_template_match(80), dtw_template_direction() == "bullish")
  size: fixed_usd(5000)
```

**Scheduler**: `dtw-template-scan` runs hourly (configurable 1 min - 1 hour), scanning user templates against watched symbols.

**Documentation**: See [61 — DTW Pattern Templates](./61-dtw-pattern-templates.md) for full details.

---

## 11. Pattern Auto-Trading

**Files**:
- `packages/be/src/api/predict/v1/trading/patterns/handlers.ts`
- `packages/be/src/trading/services/pattern-auto-trader.ts`

### 11.1 Auto-Trade Configuration

```typescript
interface PatternAutoTradeConfig {
  userId: string;
  enabled: boolean;
  patternTypes: PatternType[];           // Which patterns to trade
  symbols: string[];                      // Watchlist or '*' for all
  direction: 'bullish' | 'bearish' | 'both';
  minConfidence: number;                  // 0-1

  // Position Sizing
  sizingMode: 'fixed_usd' | 'percent_portfolio' | 'risk_based';
  fixedUsd?: number;
  percentPortfolio?: number;
  riskPerTrade?: number;                  // % of portfolio at risk

  // Risk Overrides
  stopLossOverridePct?: number;           // Override pattern's suggested stop
  takeProfitOverridePct?: number;

  // Safety Limits
  maxDailyTrades: number;
  maxOpenPositions: number;
  cooldownMinutes: number;                // Min time between trades

  // Execution Mode
  executionMode: 'paper' | 'live';
}
```

### 11.2 Live Trading Gates (5 Gates)

| Gate | Requirement | Checked By |
|------|-------------|------------|
| **Paper Experience** | Min 7 days, 10 trades | `validatePaperExperience()` |
| **Admin Permission** | Admin-granted live flag | `user.live_trading_enabled` |
| **Platform Kill Switch** | Not in emergency mode | `getBrokerCatalog().killSwitch` |
| **MFA Acknowledgement** | User confirmed MFA | `user.mfa_live_ack_at` |
| **Broker Ping** | Adapter connection OK | `adapter.ping()` |

### 11.3 Execution Flow

```
Pattern Detected → Confidence > minConfidence?
    ↓
Check Auto-Trade Config (user + symbol + direction)
    ↓
Validate Live Gates (if executionMode='live')
    ↓
Calculate Position Size (sizing mode)
    ↓
Apply Risk Overrides (if configured)
    ↓
Execute Trade (paper or live)
    ↓
Log to pattern_auto_trade_log
```

### 11.4 Outcome Tracking

| Field | Description |
|-------|-------------|
| `outcome` | hit_target, stopped_out, expired, manual_close |
| `pnl_usd` | Realized P&L |
| `pnl_pct` | Percentage return |
| `hold_duration_hours` | Time in position |
| `pattern_accuracy` | Did pattern prediction succeed? |

---

## 11b. User Pattern Import (Custom Patterns with AI Validation)

**Files**:
- `packages/be/src/insights/pattern-import-service.ts` — Core import logic and AI interpretation
- `packages/be/src/api/predict/v1/patterns/import-handlers.ts` — API handlers
- `packages/be/src/algorithms/llm/client.ts` — Vision-enabled LLM calls
- `packages/fe/src/components/patterns/PatternImportWizard.tsx` — UI wizard

**Status**: Shipped 2026-05-07

### 11b.1 Import Methods

| Method | Description | AI Features |
|--------|-------------|-------------|
| **Natural Language** | Describe pattern in words | LLM interpretation, rule generation, readback confirmation |
| **Image Upload** | Upload chart screenshot | Claude Vision analyzes image, extracts pattern structure, key levels |
| **Chart Selection** | Select range on live chart | Price action analysis, automatic rule generation |
| **DSL Rules** | Write rules directly | Validation, suggestions for improvement |

### 11b.2 AI Interpretation Flow

```
User Input (text/image/selection)
    ↓
LLM Analysis (Claude Sonnet for vision, Opus for text)
    ↓
Generate AIInterpretation:
  - name, description
  - direction (bullish/bearish/neutral)
  - complexity (simple/medium/complex)
  - rules[] with type and params
  - triggerConditions[] (human-readable)
  - warnings[] (potential issues)
  - suggestions[] (improvements)
  - readback (explanation for confirmation)
    ↓
User Reviews Interpretation
    ↓
User Confirms → Save to user_pattern_templates
    ↓
Pattern Active → Detection runs on scheduled scans
```

### 11b.3 Vision AI Capabilities

Uses `llmVisionCall()` in `packages/be/src/algorithms/llm/client.ts`:

- Analyzes chart screenshots (JPEG, PNG, WebP)
- Identifies pattern type (double bottom, H&S, triangles, etc.)
- Extracts key price levels (support, resistance, neckline)
- Detects volume characteristics when visible
- Reads user annotations and drawings
- Returns structured JSON with rules for automation

**Supported providers**: Anthropic Direct (CLAUDE_API_KEY), AWS Bedrock (USE_BEDROCK=true)

### 11b.4 Rule Types for Custom Patterns

| Rule Type | Parameters | Description |
|-----------|------------|-------------|
| `swing_low` | `{count, lookback}` | Find N swing lows in lookback bars |
| `swing_high` | `{count, lookback}` | Find N swing highs in lookback bars |
| `price_above` | `{level: 'neckline'|'resistance'|number}` | Price closes above level |
| `price_below` | `{level: 'neckline'|'support'|number}` | Price closes below level |
| `higher_low` | `{minPct}` | Second low higher by minPct% |
| `lower_high` | `{minPct}` | Second high lower by minPct% |
| `volume_above_avg` | `{multiplier}` | Volume N times above average |
| `volume_divergence` | `{direction}` | Bullish/bearish volume divergence |
| `breakout` | `{level, direction}` | Price breaks support/resistance |
| `consolidation` | `{maxRangePct, minBars}` | Price consolidates in range |
| `trendline_touch` | `{direction}` | Price touches trend support/resistance |
| `pattern_duration` | `{minBars, maxBars}` | Pattern forms within timeframe |

### 11b.5 Database Schema

```sql
-- Migration 186_user_pattern_templates.sql

CREATE TABLE trading.user_pattern_templates (
  id TEXT PRIMARY KEY,
  user_id UUID NOT NULL REFERENCES auth.users(id),
  name TEXT NOT NULL,
  description TEXT,
  import_method TEXT NOT NULL,  -- 'natural_language'|'image_upload'|'chart_selection'|'dsl'
  rules JSONB NOT NULL,         -- Array of {type, params}
  original_input JSONB,         -- Preserved for reference
  ai_interpretation TEXT NOT NULL,
  ai_model_used TEXT,
  direction TEXT,               -- 'bullish'|'bearish'|'neutral'
  complexity TEXT,              -- 'simple'|'medium'|'complex'
  is_active BOOLEAN DEFAULT TRUE,
  alert_enabled BOOLEAN DEFAULT FALSE,
  auto_trade_enabled BOOLEAN DEFAULT FALSE,
  validation_hit_rate NUMERIC(5,4),
  validation_sample_size INTEGER,
  times_triggered INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(user_id, name)
);

CREATE TABLE trading.user_pattern_template_matches (
  id TEXT PRIMARY KEY,
  template_id TEXT NOT NULL REFERENCES trading.user_pattern_templates(id),
  user_id UUID NOT NULL REFERENCES auth.users(id),
  symbol TEXT NOT NULL,
  detected_at TIMESTAMPTZ NOT NULL,
  match_score NUMERIC(5,4) NOT NULL,
  outcome TEXT,  -- 'pending'|'target_hit'|'stopped_out'|'timeout'
  outcome_pnl_pct NUMERIC(10,4),
  mae_pct NUMERIC(10,4),
  mfe_pct NUMERIC(10,4)
);

CREATE TABLE trading.ai_discovered_patterns (
  id TEXT PRIMARY KEY,
  symbol TEXT NOT NULL,
  discovered_at TIMESTAMPTZ DEFAULT NOW(),
  pattern_description TEXT NOT NULL,
  pattern_rules JSONB NOT NULL,
  historical_matches INTEGER,
  estimated_hit_rate NUMERIC(5,4),
  discovery_confidence NUMERIC(5,4),
  user_id UUID,  -- NULL until claimed
  user_action TEXT,  -- 'pending'|'accepted'|'rejected'|'modified'
  resulting_template_id TEXT REFERENCES trading.user_pattern_templates(id)
);
```

### 11b.6 Two Pattern Template Systems

The platform maintains two complementary pattern template systems for different use cases:

| System | Table | Migration | Purpose | Use Case |
|--------|-------|-----------|---------|----------|
| **DTW Templates** | `trading.pattern_templates` | 178 | Dynamic Time Warping similarity matching | Visual pattern matching — user selects a chart range, system normalizes the price series and uses DTW algorithm to find similar historical shapes across all symbols |
| **User Import Templates** | `trading.user_pattern_templates` | 186 | AI-interpreted rule-based patterns | Semantic pattern definition — user describes patterns via natural language, chart screenshots, or DSL rules; AI interprets intent and creates trigger conditions |

**Key Differences:**

| Aspect | DTW Templates | User Import Templates |
|--------|--------------|----------------------|
| **Input** | Chart range selection only | NL text, images, chart selection, DSL |
| **Matching** | Pure mathematical (DTW distance) | Rule evaluation (swing lows, breakouts, etc.) |
| **Interpretation** | None (shape-based) | AI readback + user confirmation |
| **Best For** | "Find price action that looks like this" | "Alert me when this pattern condition occurs" |
| **Historical Validation** | DTW distance threshold | Rule match + outcome statistics |

**When to Use Each:**

- **DTW Templates** → Use when you see a specific chart shape and want to find similar historical instances without defining explicit rules
- **User Import Templates** → Use when you can describe the pattern conditions (e.g., "double bottom with volume confirmation") or have a screenshot to analyze

Both systems coexist and serve different trader needs. They share the same UI entry point (`/patterns` page) but use different backend services:
- DTW: `packages/be/src/insights/dtw-pattern-matcher.ts`
- Import: `packages/be/src/insights/pattern-import-service.ts`

---

## 11c. Pattern Timing Analysis (Time-of-Day / Day-of-Week)

**Status**: Shipped 2026-05-07

**Files**:
- `packages/be/src/insights/pattern-timing-analyzer.ts` — Core timing analysis service
- `packages/be/src/api/predict/v1/patterns/timing-handlers.ts` — API handlers
- `packages/fe/src/components/patterns/PatternTimingHeatmap.tsx` — Visual heatmap component
- `db/migrations/187_pattern_timing_stats.sql` — Schema

### 11c.1 Purpose

Analyzes **when** patterns occur to help traders identify:
1. **Optimal timing windows** — Hours/days with highest hit rates
2. **Abnormal timing** — Pattern firing at unusual times (confidence penalty)
3. **Market structure effects** — Clustering around market open/close

### 11c.2 Heatmap Visualization

```
        MON   TUE   WED   THU   FRI
  9:00  ██    ██    ██    ██    ██   ← High activity (market open)
 10:00  ██    ▓▓    ██    ▓▓    ▓▓
 11:00  ▓▓    ░░    ▓▓    ░░    ░░
 12:00  ░░    ░░    ░░    ░░    ░░   ← Low activity (lunch)
 13:00  ░░    ░░    ░░    ▓▓    ▓▓
 14:00  ▓▓    ▓▓    ▓▓    ██    ██
 15:00  ██    ██    ██    ██    ██   ← High activity (power hour)

Color intensity = occurrence frequency
Green = high hit rate, Red = low hit rate
```

### 11c.3 Abnormal Timing Detection

Uses z-score to detect when patterns fire at statistically unusual times:

```typescript
// Z-score calculation
const expected_pct = 1/24;  // Uniform distribution: ~4.17% per hour
const actual_pct = hour_count / total_count;
const zscore = (actual_pct - expected_pct) / std_dev;

// Abnormal if |zscore| > 2 (outside 95% CI)
// Confidence penalty: 12% for |z|>2, 20% for |z|>3
```

**Example Warning:**
> "This double bottom at 11:32 AM is UNUSUAL. Pattern typically fires at market open (9:30-10:30). Confidence penalty: -12%"

### 11c.4 API Endpoints

| Endpoint | Purpose |
|----------|---------|
| `GET /patterns/timing?type=X` | Full timing analysis with stats |
| `GET /patterns/timing/heatmap?type=X` | 24×7 heatmap data for visualization |
| `GET /patterns/timing/check?type=X&hour=14` | Real-time abnormal timing check |
| `GET /patterns/timing/insights?type=X` | Best/worst times + insights |

### 11c.5 Integration Points

1. **Pattern Detection** — `price-action-patterns.ts` records timing event on every pattern
2. **UI** — `PatternTimingHeatmap` component shown in pattern detail view
3. **Scheduler** — `pattern-timing-stats` job runs nightly to recompute aggregates
4. **Confidence Adjustment** — Abnormal timing can penalize pattern confidence by up to 20%

### 11c.6 Database Schema

```sql
-- Migration 187
CREATE TABLE trading.pattern_timing_events (
  id TEXT PRIMARY KEY,
  pattern_id UUID REFERENCES trading.price_action_patterns(id),
  pattern_type VARCHAR(50) NOT NULL,
  symbol VARCHAR(20) NOT NULL,
  detected_hour INTEGER NOT NULL,      -- 0-23 UTC
  detected_day_of_week INTEGER NOT NULL, -- 0-6 (Sun-Sat)
  detected_at TIMESTAMPTZ NOT NULL,
  outcome VARCHAR(20),                 -- 'hit'|'miss'|'pending'
  is_abnormal_timing BOOLEAN DEFAULT FALSE,
  timing_zscore NUMERIC(8,4)
);

-- Aggregated view for heatmap
CREATE VIEW trading.pattern_timing_heatmap AS
SELECT pattern_type, day_of_week, hour, occurrences, hit_rate, intensity
FROM ...
```

---

## 12. Database Schema

### 12.1 Pattern Tables (Migrations 080-088)

| Table | Migration | Purpose |
|-------|-----------|---------|
| `trading.price_action_patterns` | 080 | Core pattern detection records |
| `trading.pattern_subscriptions` | 080 | User alert subscriptions |
| `trading.pattern_playbook` | 080 | Named pattern templates |
| `trading.pattern_annotations` | 080 | User-drawn chart annotations |
| `trading.pattern_trigger_events` | 080 | Historical trigger log |
| `trading.pattern_auto_trade_config` | 081 | Auto-trade settings per user |
| `trading.pattern_auto_trade_log` | 081 | Execution log for auto-trades |
| `trading.gap_opportunities` | 088 | Detected gap opportunities |
| `trading.gap_trades` | 088 | Executed gap trades |
| `predict.computed_insights` | 038 | General pattern storage (kind='price_action_pattern') |
| `omniscient.black_swan_warnings` | 087 | Black swan event records |

### 12.2 Key Columns in price_action_patterns

```sql
CREATE TABLE trading.price_action_patterns (
  id UUID PRIMARY KEY,
  user_id UUID REFERENCES auth.users(id),
  symbol VARCHAR(20) NOT NULL,
  asset_class VARCHAR(20),
  pattern_type VARCHAR(50) NOT NULL,
  direction VARCHAR(10),
  status VARCHAR(20) DEFAULT 'forming',
  confidence DECIMAL(5,4),
  detected_at TIMESTAMPTZ DEFAULT NOW(),
  triggered_at TIMESTAMPTZ,
  resolved_at TIMESTAMPTZ,
  entry_price DECIMAL(20,8),
  stop_price DECIMAL(20,8),
  target_price DECIMAL(20,8),
  evidence JSONB,
  outcome VARCHAR(20),
  pnl_pct DECIMAL(10,4),
  CONSTRAINT valid_status CHECK (status IN ('forming','triggered','confirmed','failed','expired'))
);
```

### 12.3 Indexes

```sql
CREATE INDEX idx_patterns_symbol ON trading.price_action_patterns(symbol);
CREATE INDEX idx_patterns_user ON trading.price_action_patterns(user_id);
CREATE INDEX idx_patterns_status ON trading.price_action_patterns(status);
CREATE INDEX idx_patterns_type ON trading.price_action_patterns(pattern_type);
CREATE INDEX idx_patterns_active ON trading.price_action_patterns(symbol, status)
  WHERE status IN ('forming', 'triggered');
```

---

## 13. API Endpoints

### 13.1 Pattern Routes (`/api/predict/v1/patterns/*`)

| Method | Route | Handler | Description |
|--------|-------|---------|-------------|
| GET | `/patterns` | `handleListPatterns` | List detected patterns |
| POST | `/patterns/detect` | `handleDetectPatterns` | Trigger detection scan |
| GET | `/patterns/:id` | `handleGetPattern` | Get pattern detail |
| GET | `/patterns/active` | `handleGetActivePatterns` | Get active patterns |
| POST | `/patterns/subscriptions` | `handleCreateSubscription` | Subscribe to alerts |
| GET | `/patterns/playbook` | `handleGetPlaybook` | Get playbook templates |
| POST | `/patterns/candle-scan` | `handleScanCandlePattern` | Scan for candlestick pattern across symbols |
| GET | `/patterns/candle-scan/types` | `handleGetCandlePatternTypes` | Get all 18 pattern types with metadata |

### 13.2 Gap Routes (`/api/predict/v1/trading/gaps/*`)

| Method | Route | Handler | Description |
|--------|-------|---------|-------------|
| GET | `/trading/gaps` | `handleScanGaps` | Scan for gap opportunities |
| POST | `/trading/gaps/trades` | `handleExecuteGapTrade` | Execute gap trade |
| GET | `/trading/gaps/trades/:id` | `handleGetGapTrade` | Get gap trade details |

### 13.3 Pattern Trading Routes (`/api/predict/v1/trading/patterns/*`)

| Method | Route | Handler | Description |
|--------|-------|---------|-------------|
| GET | `/trading/patterns` | `handleGetPatternHistory` | Pattern history log |
| POST | `/trading/patterns/triggers` | `handlePatternTrigger` | Log trigger event |
| GET | `/trading/patterns/config` | `handleGetAutoTradeConfig` | Get auto-trade config |
| PUT | `/trading/patterns/config` | `handleUpdateAutoTradeConfig` | Update auto-trade config |

### 13.4 Black Swan Routes (`/api/predict/v1/all-seeing-eye/black-swan/*`)

| Method | Route | Handler | Description |
|--------|-------|---------|-------------|
| GET | `/all-seeing-eye/black-swan` | `handleListWarnings` | List active warnings |
| GET | `/all-seeing-eye/black-swan/:id` | `handleGetWarning` | Get warning detail |
| POST | `/all-seeing-eye/black-swan/:id/countermeasures` | `handleGetCountermeasures` | AI countermeasures |

---

## 14. UI Pages & Components

### 14.1 Pattern Pages

| Route | File | Purpose |
|-------|------|---------|
| `/patterns` | `apps/web/src/app/patterns/page.tsx` | Pattern Library - active patterns, subscriptions |
| `/trading/patterns` | `apps/web/src/app/trading/patterns/page.tsx` | Pattern Log - history, triggers, outcomes |
| `/help/patterns` | `apps/web/src/app/help/patterns/page.tsx` | Educational content |

### 14.2 Key Components

| Component | Location | Purpose |
|-----------|----------|---------|
| `PatternLibrary` | `@agencio-predict/fe/components/patterns/` | Main pattern dashboard |
| `PatternAnalyzerPanel` | `apps/web/src/components/overlays/` | Overlay analyzer |
| `GapOpportunitiesPanel` | `@agencio-predict/fe/components/trading/` | Gap scanner UI |
| `CandlestickChart` | `@agencio-predict/fe/components/trading/charts/` | Chart with FVG zones |

### 14.3 Pattern Features in Charts

- **FVG Zones**: Bullish (green) and bearish (red) gap zones overlaid on candles
- **Pattern Annotations**: User-drawn support/resistance lines
- **Pattern Alerts**: Visual indicators when pattern triggers
- **Trade Suggestions**: Entry/stop/target lines from pattern detection

### 14.4 Alert Channels

| Channel | Configuration | Delivery |
|---------|---------------|----------|
| In-App | Default | Real-time via SSE |
| Email | Requires verified email | Batched (5-min) |
| Push | Requires VAPID setup | Instant |
| Webhook | Custom URL | POST on trigger |

---

## 15. Configuration & Thresholds

### 15.1 Master Threshold Table

| Feature | Threshold | Value |
|---------|-----------|-------|
| Black Swan Z-Score | Anomaly detection | 2.5 sigma |
| Black Swan Min Samples | Reliability | 30 |
| Whale Ratio | Top trade percentile | 95th (top 5%) |
| Bot Signature | Round number weight | 0.25 |
| Bot Signature | Repeated size weight | 0.25 |
| Bot Signature | Sub-second burst weight | 0.50 |
| Divergence | Sentiment move | 0.10 |
| Divergence | Price move | 2% |
| Divergence | Correlation threshold | 0.30 |
| VIX | Low | 15 |
| VIX | Moderate | 20 |
| VIX | High | 30 |
| VIX | Extreme | 40 |
| VPIN | Elevated toxicity | > 0.5 |
| Funding Rate | Extreme | 0.05% per 8h |
| Price Action | Min bars | 20 |
| Price Action | Cluster max range | 3.0% |
| Price Action | Retest tolerance | 0.5% |

### 15.2 Persistence

All features persist to `predict.computed_insights`:
- `kind`: Pattern classification type
- `scope_type`: 'symbol' or 'market-wide'
- `scope_id`: Symbol or market identifier
- `values`: JSON payload
- `confidence`: 0-1 score
- `inputs_hash`: SHA256 for dedup
- `computed_at`: Timestamp
- `valid_until`: Optional validity window

---

## 16. User-Defined Candlestick Patterns

Users can create, import, and use custom candlestick patterns with their own detection rules. This feature allows traders to encode their own pattern recognition strategies.

### 16.1 Pattern Rule Structure

Each pattern consists of:
- **Name & Description**: Identify the pattern
- **Direction**: bullish, bearish, or neutral
- **Reliability**: high, medium, or low
- **Bar Count**: 1-10 bars in the pattern
- **Trend Context**: Optional uptrend/downtrend requirement
- **Bar Rules**: Per-bar conditions

### 16.2 Bar Rule Conditions

Each bar in a pattern can have the following conditions:

| Category | Conditions |
|----------|------------|
| Direction | bullish, bearish, or any |
| Body Size | body_pct_min, body_pct_max (% of total range) |
| Wick Ratios | upper/lower_wick_ratio_min/max (relative to body) |
| Wick Percentages | upper/lower_wick_pct_min/max (% of range) |
| Prior Bar Relations | engulfs_previous, inside_previous, opens_below_prior_low, opens_above_prior_high, opens_within_prior_body |
| Close Relations | closes_above/below_prior_midpoint, closes_above/below_bar0_midpoint, closes_higher, closes_lower |
| Gaps | gaps_up, gaps_down |
| Volume | volume_ratio_min/max (relative to prior bar) |

### 16.3 Pattern Validation

Patterns can be backtested against historical data:
- Tests against multiple symbols (default: SPY, QQQ, AAPL, MSFT, GOOGL, NVDA, TSLA, META)
- Calculates hit rate with Wilson score confidence intervals
- Measures average return and bars to target

### 16.4 Import/Export

Pattern libraries can be exported and imported as JSON:
```json
{
  "version": "1.0",
  "exportedAt": "2026-05-10T12:00:00Z",
  "patterns": [
    {
      "name": "My Custom Hammer",
      "description": "Modified hammer pattern",
      "direction": "bullish",
      "reliability": "medium",
      "rules": {
        "bars": 1,
        "rules": [
          {
            "bar": 0,
            "direction": "bullish",
            "body_pct_max": 30,
            "lower_wick_ratio_min": 2
          }
        ]
      }
    }
  ]
}
```

### 16.5 DSL Primitives

Five primitives available for AI Algorithm Builder:

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `custom_candle_match(minConfidence)` | boolean | True if user pattern matches with >= confidence |
| `custom_candle_pattern(name)` | boolean | True if specific named pattern matches |
| `custom_candle_direction()` | string | 'bullish', 'bearish', or 'neutral' |
| `custom_candle_confidence()` | number | Match confidence (0-1) |
| `custom_candle_name()` | string | Name of matched pattern |

### 16.6 Database Schema

```sql
-- trading.user_candle_patterns
id, user_id, name, description, direction, reliability,
rules (JSONB), bar_count, is_system, is_public, usage_count,
validation_stats (JSONB), created_at, updated_at

-- trading.user_candle_pattern_matches
id, pattern_id, user_id, symbol, matched_at, entry_price,
outcome, exit_price, return_pct, bars_to_exit, created_at
```

### 16.7 API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/patterns/user-candle` | List patterns |
| POST | `/patterns/user-candle` | Create pattern |
| GET | `/patterns/user-candle/:id` | Get pattern |
| PUT | `/patterns/user-candle/:id` | Update pattern |
| DELETE | `/patterns/user-candle/:id` | Delete pattern |
| POST | `/patterns/user-candle/:id/fork` | Fork pattern |
| POST | `/patterns/user-candle/:id/validate` | Validate against history |
| GET | `/patterns/user-candle/export` | Export library |
| POST | `/patterns/user-candle/import` | Import library |
| POST | `/patterns/user-candle/detect` | Detect patterns for symbol |

### 16.8 UI Component

`UserCandlePatternBuilder` component (`packages/fe/src/components/patterns/UserCandlePatternBuilder.tsx`):
- Pattern list with cards showing name, direction, bar count, reliability, validation stats
- Full editor modal with bar rule configuration
- Import/export modal for JSON library format
- Validate button to backtest patterns

---

## Key Files Reference

| Component | File |
|-----------|------|
| FVG Detection | `packages/shared/src/fvg.ts` |
| Price Action Patterns | `packages/be/src/insights/price-action-patterns.ts` |
| Black Swan Detector | `packages/be/src/all-seeing-eye/black-swan/detector.ts` |
| Paradox Detection | `packages/be/src/all-seeing-eye/insights/paradox-detector.ts` |
| Paradox Rules | `packages/be/src/all-seeing-eye/insights/paradox-rules.ts` |
| Paradox Calibration | `packages/be/src/all-seeing-eye/calibration/` |
| Tick Classifier | `packages/be/src/insights/tick-classifier.ts` |
| Divergence Engine | `packages/be/src/insights/divergence-engine.ts` |
| Composite Score | `packages/be/src/insights/composite-score.ts` |
| Regime Detector | `packages/be/src/trading/services/market-regime-detector.ts` |
| DSL Primitives | `packages/be/src/algorithms/dsl/types.ts` |
| DSL Evaluator | `packages/be/src/algorithms/dsl/evaluator.ts` |
| Macro Overlay Provider | `packages/be/src/algorithms/macro-overlay-provider.ts` |
| Paper/Live Executor | `packages/be/src/algorithms/paper/executor.ts` |
| Backtest Engine | `packages/be/src/algorithms/backtest/engine.ts` |
| User Candle Patterns Types | `packages/be/src/insights/user-candle-patterns/types.ts` |
| User Candle Patterns Repository | `packages/be/src/insights/user-candle-patterns/repository.ts` |
| User Candle Patterns Detector | `packages/be/src/insights/user-candle-patterns/detector.ts` |
| User Candle Patterns Service | `packages/be/src/insights/user-candle-patterns/service.ts` |
| User Candle Patterns API | `packages/be/src/api/predict/v1/patterns/user-candle/handlers.ts` |
| User Candle Pattern Builder UI | `packages/fe/src/components/patterns/UserCandlePatternBuilder.tsx` |

---

*Last updated: 2026-05-10*
