# Strategy Schema v1.1 — Live Evaluation Extensions (PROMOTED)

**Purpose.** Extend the v1 schema so the registry can drive **live position evaluation**, not just entry classification. Adds four optional arrays per strategy: `validation_rules`, `invalidation_conditions`, `management_rules`, `quality_indicators`. Plus a shared Type Catalog the evaluator dispatches on.

**Status.** **PROMOTED to canonical 2026-05-12.** All 8 non-sentinel strategies merged into `/system/strategies.json` (schema_version: 2). Off-book has explicit empty arrays. Mirror pairs symmetric. This doc remains the reference spec for the v1.1 fields and the Type Catalog.

**Versioning.** Additive. v1 readers ignoring unknown fields are unaffected. Promote v1.1 to canonical (`meta.schema_version: 2`) only when all 7 strategies are authored against it.

**Canonical when promoted.** Same file: `/system/strategies.json`. New arrays appear inline on each strategy entry.

---

## The four new arrays

### `validation_rules[]` — "is this trade STILL in playbook RIGHT NOW?"

Continuous checks evaluated every eval cycle (bar close, alert event, cron tick). A failed required rule downgrades the live grade or transitions the trade to OFF-BOOK.

```
ValidationRule = {
  id: string                    // stable kebab-case
  label: string                 // human-readable
  type: enum (Type Catalog)
  required: boolean             // true → failure forces OFF-BOOK
  checked_on: enum[]            // ["bar_close", "alert", "tick"]
  ...type-specific fields
}
```

### `invalidation_conditions[]` — "exit/reduce TRIGGERS"

Hard or soft conditions that, when satisfied, emit a recommended action. Severity controls the cockpit's behavior.

```
InvalidationCondition = {
  id: string
  label: string
  type: enum (Type Catalog)
  action: "exit" | "reduce" | "alert"
  severity: "hard" | "soft"
  ...type-specific fields
}
```

### `management_rules[]` — "expected trader actions as the trade progresses"

What the playbook says SHOULD happen. The evaluator tracks adherence — did the trader move stop to breakeven at +1 SD? Did they scale half at +2 SD? Adherence feeds the management modifier on the grade.

```
ManagementRule = {
  id: string
  label: string
  trigger: TriggerSpec          // when this rule should fire
  action: ActionSpec            // what the trader should do
}
```

### `quality_indicators[]` — "A vs B vs C drivers"

Weighted indicators that raise or lower the quality score. Score = Σ (weight × direction × satisfied). Indicators can be mutually exclusive via `exclusive_with`.

```
QualityIndicator = {
  id: string
  label: string
  type: enum (Type Catalog)
  evaluated_at: "entry" | "bar_close" | "alert"
  weight: number (0..1)
  direction: "positive" | "negative"
  exclusive_with: id[]          // mutual-exclusion group
  ...type-specific fields
}
```

---

## Type Catalog (v1.1)

The four arrays share a `type` enum so the evaluator dispatches generically. **Additive-only across minor versions.** v1.2 may add new types but cannot change existing signatures.

Expanded after authoring the full 7-strategy set; new types marked **(added)** below.

| Type | Used in | Inputs | Semantics |
|------|---------|--------|-----------|
| `band_range` | validation | `lower_band`, `upper_band` | Price within SD band range |
| `level_hold` | validation | `level`, `side`, `tolerance_sd` | Price holding above/below a level |
| `price_below_band` / `price_above_band` | invalidation | `band`, `min_bars` | Directional band-side check |
| `price_closes_below_band` / `price_closes_above_band` | invalidation | `band`, `min_bars` | Same but bar-close only |
| `price_reaches_band` | trigger | `band` | Price has touched the band |
| `volume_above` | invalidation (compound), quality | `lookback_bars`, `multiplier` | N-bar avg volume × multiplier |
| `stop_breach` | invalidation | (none — uses trade's configured stop, polymorphic on sd_band vs structural) | Configured stop hit |
| `regime_change` | invalidation | `from`, `to` | Band regime FLIPPED (event) |
| `regime_check` **(added)** | validation | `regime` | Current regime EQUALS expected (continuous check) |
| `band_slope_threshold` **(added)** | validation, quality | `min_abs_slope` OR `max_abs_slope` | Band slope above/below threshold (fanning vs flat) |
| `time_window` | quality | `start_et`, `end_et` | Current time within ET window |
| `time_elapsed` | trigger (compound only) | `minutes_since_entry` | N minutes since entry |
| `stop_variant_match` | quality | `stop_id` | Trade's chosen stop equals this id |
| `mfe_threshold` | quality, trigger | `min_r` | Max Favorable Excursion ≥ N×R |
| `mfe_below` **(added)** | trigger (compound only) | `max_r` | Max Favorable Excursion < N×R (for stall detection) |
| `drawdown_threshold` | quality | `ref`, `multiplier` | Drawdown exceeds reference × multiplier |
| `level_test_count` **(added)** | quality | `level`, `lookback_bars`, `min_count` | Level was tested N times in lookback |
| `level_breach` **(added)** | invalidation | `level`, `side`, `min_bars` | Generic non-band level (e.g., 9 EMA) closed beyond |
| `entry_method` **(added)** | quality | `method` | Discriminator: "pullback_to_ub2", "range_break_above_ub3", etc. |
| `exit_reason` **(added)** | quality (evaluated_at: "exit") | `expected` | Exit was triggered by expected reason ("target_reached", "stop_breached", etc.) |
| `extension_sd_range` **(added)** | quality | `min_sd`, `max_sd` | Entry extension from VWAP in SD range |
| `is_re_entry_check` **(added)** | invalidation | `expected: false` | Reads `trade_state.is_re_entry`; for one-attempt-only rules |
| `prior_level_nearby` **(added)** | quality | `reference`, `level_types`, `max_distance_sd` | A nearby S/R level (PDH, prev_swing_high, etc.) within distance |
| `compound` | invalidation, **trigger (added in v1.1.1)** | `op: "and"\|"or"`, `conditions[]` or `triggers[]` | Boolean combination |

**Type count growth.** v1.1 doc started with 13 types; 8 emerged while authoring the other 6 strategies (1.3 new types per added strategy). Growth rate is high but expected for v1 — future playbooks should mostly reuse the catalog. v1.2 freeze candidate.

---

## Trigger / Action vocabulary

`TriggerSpec.type`:

- `price_reaches_band` — touched (any bar)
- `price_closes_above_band` / `price_closes_below_band` — bar close only
- `time_elapsed` — N minutes since entry (field: `minutes_since_entry`)
- `mfe_threshold` — favorable excursion hit threshold
- `mfe_below` — favorable excursion BELOW threshold (for stall detection)
- `compound` — `{op: "and"\|"or", triggers: TriggerSpec[]}` — boolean combination of triggers (added v1.1.1; mirrors compound for invalidation)

`ActionSpec.type`:

- `move_stop_to_entry` — breakeven
- `move_stop_to_band` — `band: <band_id>`
- `trail_stop` — `trail_band: <band_id>`
- `scale_out` — `fraction: 0..1`
- `exit` — close fully
- `reduce` — non-prescriptive partial close
- `alert` — notify only

---

## Stress test: `vwap-pull-in-long` fully populated

This is the JSON the merge will append to the existing v1 entry once v1.1 promotes. Verbatim, copy-pasteable.

```json
{
  "validation_rules": [
    {
      "id": "still_in_pullback_zone",
      "label": "Price still within VWAP-to--1 SD entry zone (entry conditions haven't broken)",
      "type": "band_range",
      "lower_band": "lb2",
      "upper_band": "vwap",
      "required": true,
      "checked_on": ["bar_close", "alert"]
    },
    {
      "id": "vwap_holding",
      "label": "VWAP still acting as support (bounce, not break-through)",
      "type": "level_hold",
      "level": "vwap",
      "side": "above",
      "tolerance_sd": -0.5,
      "required": true,
      "checked_on": ["bar_close"]
    }
  ],
  "invalidation_conditions": [
    {
      "id": "vwap_break_on_volume",
      "label": "Decisive close below VWAP on above-average volume",
      "type": "compound",
      "conditions": [
        {"type": "price_closes_below_band", "band": "vwap", "min_bars": 2},
        {"type": "volume_above", "lookback_bars": 20, "multiplier": 1.5}
      ],
      "action": "exit",
      "severity": "hard"
    },
    {
      "id": "stop_breached",
      "label": "Price closed beyond the trade's configured stop",
      "type": "stop_breach",
      "action": "exit",
      "severity": "hard"
    },
    {
      "id": "regime_flip_to_trend",
      "label": "Bands fanned vertically; regime shifted from rotation to trend",
      "type": "regime_change",
      "from": "rotation",
      "to": "trend",
      "action": "reduce",
      "severity": "soft"
    }
  ],
  "management_rules": [
    {
      "id": "trail_at_ub2_breakeven",
      "label": "Move stop to breakeven once +1 SD (UB2) tagged",
      "trigger": {"type": "price_reaches_band", "band": "ub2"},
      "action": {"type": "move_stop_to_entry"}
    },
    {
      "id": "scale_half_at_ub3",
      "label": "Scale 50% at +2 SD (UB3)",
      "trigger": {"type": "price_reaches_band", "band": "ub3"},
      "action": {"type": "scale_out", "fraction": 0.5}
    },
    {
      "id": "trail_behind_ub2_after_ub3",
      "label": "After +2 SD, trail remaining stop behind +1 SD (UB2)",
      "trigger": {"type": "price_reaches_band", "band": "ub3"},
      "action": {"type": "trail_stop", "trail_band": "ub2"}
    }
  ],
  "quality_indicators": [
    {
      "id": "late_session_entry",
      "label": "Entry in 14:30-15:55 ET (empirical winner bucket: +$3.13/sh avg)",
      "type": "time_window",
      "start_et": "14:30",
      "end_et": "15:55",
      "evaluated_at": "entry",
      "weight": 0.20,
      "direction": "positive"
    },
    {
      "id": "wider_stop_chosen",
      "label": "Stop is LB3 (-2 SD) — empirical winner with PF 1.67",
      "type": "stop_variant_match",
      "stop_id": "lb3",
      "evaluated_at": "entry",
      "weight": 0.25,
      "direction": "positive",
      "exclusive_with": ["tight_stop_chosen"]
    },
    {
      "id": "tight_stop_chosen",
      "label": "Stop is LB1 (-0.5 SD) — empirically unprofitable across all combos",
      "type": "stop_variant_match",
      "stop_id": "lb1",
      "evaluated_at": "entry",
      "weight": 0.30,
      "direction": "negative",
      "exclusive_with": ["wider_stop_chosen"]
    },
    {
      "id": "mfe_exceeds_2r",
      "label": "MFE exceeds 2R during the trade",
      "type": "mfe_threshold",
      "min_r": 2.0,
      "evaluated_at": "bar_close",
      "weight": 0.15,
      "direction": "positive",
      "exclusive_with": []
    },
    {
      "id": "drawdown_exceeds_planned_risk",
      "label": "Current drawdown exceeds the planned stop distance",
      "type": "drawdown_threshold",
      "ref": "planned_stop_distance",
      "multiplier": 1.0,
      "evaluated_at": "bar_close",
      "weight": 0.20,
      "direction": "negative",
      "exclusive_with": []
    }
  ]
}
```

---

## Evaluator API (consumer contract)

The pure function the registry expects from every evaluator implementation.

```
evaluate(strategy_def, trade_state, market_context) → eval_record

strategy_def: a single entry from strategies.json (with v1.1 arrays populated)

trade_state: {
  trade_id: string
  entry_time_et: ISO8601
  entry_price: number
  direction: "long" | "short"
  chosen_stop_id: string             // matches a stop_variants[].id
  chosen_target_id: string           // matches a target_variants[].id
  current_size: number               // shares/contracts (post any scales)
  original_size: number
  triggers_already_fired: id[]       // management_rule ids already actioned this trade
  unrealized_pnl_usd: number
  mae_r: number                      // worst drawdown in R-multiples
  mfe_r: number                      // best excursion in R-multiples
  is_re_entry: boolean               // (added) true if a prior trade on the same setup hit stop today; gates one-attempt-only rules
  entry_method: string|null          // (added) discriminator for trend/breakout entries: "pullback_to_ub2" | "range_break_above_ub3" | null
  prior_levels_nearby: object        // (added) cached S/R level catalog: {pdh, pdl, prev_swing_high, prev_swing_low, vwap_prev_day, ...}
  exit_reason: string|null           // (added) populated at exit only; "target_reached" | "stop_breached" | "stalled_scratch" | "manual" | null
}

market_context: {
  evaluated_at_et: ISO8601
  current_price: number
  bar_close_price: number             // latest closed bar
  vwap: number
  bands: { lb3, lb2, lb1, ub1, ub2, ub3, ub4, ub5 }   // signed SD offsets resolved to prices
  regime: "rotation" | "trend" | "unknown"
  band_slope: number                  // (added) signed slope of 1st deviation; positive = fanning up, near-zero = flat, negative = fanning down
  volume_current_bar: number
  volume_avg_20_bar: number
  ema_9: number                       // (added) for backside level_breach checks
  time_et: ISO8601
}

eval_record: {
  schema_version: 2
  evaluated_at_et: ISO8601
  trade_id: string
  grade: "A" | "B" | "C" | "F" | "OFF-BOOK"
  rules_satisfied: rule_id[]
  rules_failed: rule_id[]
  invalidation_triggered: condition_id | null
  invalidation_severity: "hard" | "soft" | null
  quality_score: number               // raw weighted sum, 0..~1.2
  quality_score_normalized: number    // mapped to 0..1
  distance_from_optimal_exit_usd: number | null
  management_triggers_to_fire: management_rule_id[]   // not yet in triggers_already_fired
  recommended_action: "hold" | "reduce" | "exit" | "trim_partial" | "scale_at_band"
  reasons: string[]
}
```

Implementation rule: **no I/O, no DB access, no side effects.** The evaluator is a pure function. The orchestration layer (the live cron, the EOD batch) is responsible for assembling `trade_state` and `market_context` from sources.

---

## Stress-test findings (the value of writing v1.1 against a real playbook)

1. **`type` namespace exploded — 12 types from one playbook.** Without the Type Catalog above, implementations will diverge. **Decision:** Type Catalog is additive-only; new types in v1.2+ require schema_version bump. Breaking changes to existing type signatures require major bump.

2. **Management rules need cross-evaluation state.** "Move stop to breakeven once +1 SD tagged" requires knowing whether the trigger already fired. Options:
   - (a) Stateful evaluator (reads prior eval rows) — loses pure-function purity.
   - (b) `trade_state.triggers_already_fired: id[]` carried in by the orchestrator — evaluator stays pure.
   - **Picked (b).** The append-only eval log IS the canonical record of which triggers fired. The orchestration layer joins the latest eval before invoking evaluator.

3. **Mutual exclusion on quality indicators.** `wider_stop_chosen` and `tight_stop_chosen` are sourced from the same `chosen_stop_id` — both can't fire. v1.1 introduces `exclusive_with: id[]`. Evaluator rule: among matching members of an exclusion group, the highest-weight one wins; others are skipped.

4. **`evaluated_at` is a new axis.** Some indicators fire once at entry (time-of-day, stop-variant-chosen); others fire every bar (MFE, drawdown). v1.1 introduces `evaluated_at: "entry" | "bar_close" | "alert"`. Entry-only indicators freeze at trade open — the evaluator must not re-evaluate them.

5. **Market context API is non-trivial.** The evaluator needs current price + all 8 SD bands resolved to prices + volume + 20-bar volume avg + regime classification + ET time + trade-specific entry/stop/size state. Documented above. The orchestration layer (live cron / EOD batch) must assemble all of this before calling evaluate(). 

6. **R-multiple math needs a canonical R formula.** "MFE > 2R" — what's 1R? Default proposed: `R = abs(entry_price - chosen_stop_price)`. For partial scaled exits, R does NOT reset (R is a property of the trade, not the position). Codify in evaluate.py.

7. **Quality-score weights don't sum to 1.0.** vwap-pull-in-long's 5 indicators sum to 1.10 with exclusion groups counting once at max (0.25 for the stop-choice group). That's fine — the grade-to-letter mapping (A ≥ 0.8, B ≥ 0.5, C ≥ 0.2, F < 0.2) lives in the evaluator, not the schema. Schema produces a score; evaluator decides letter. Decoupled.

8. **Trend strategy is blocked by broken regime classifier.** trend-trade-long's `gating.regime_required: "trend"` and its validation_rules will never satisfy in production while the regime classifier returns ROTATION for 452/452 trades. **Hard prerequisite for evaluate.py wiring on trend strategies.** Logged as a queued task.

9. **`band_range` semantics for shorts.** For `vwap-pull-in-short`, the "still in pullback zone" check uses `lower_band: vwap`, `upper_band: ub2`. The shape of the check is identical to longs, but the band ids flip. The evaluator should NOT auto-flip — the schema author writes the correct bands per direction. (Otherwise mirror logic leaks into the evaluator.)

10. **Structural stops complicate `stop_breach`.** For backside strategies, stop is `$0.02 above range_high` (structural, not band). `stop_breach` type must dispatch on the trade's `chosen_stop_id` and look up its `type: "structural"` vs `"sd_band"` from the registry to compute the actual price. Evaluator must handle both stop types.

### Findings from authoring the remaining 6 strategies (added 2026-05-12)

11. **Type catalog grew 62%** (13 → 21 types) authoring 6 more strategies. Eight new types: `regime_check`, `band_slope_threshold`, `mfe_below`, `level_test_count`, `level_breach`, `entry_method`, `exit_reason`, `extension_sd_range`, `is_re_entry_check`, `prior_level_nearby`. Growth is high but front-loaded — most "common" check shapes (band proximity, slope, level hold, exit-reason scoring, S/R confluence) are now in the catalog. Project: v1.2 onwards should add ≤2 new types per new strategy.

12. **`regime_change` (event) vs `regime_check` (continuous).** These are distinct primitives and need to coexist. `regime_change` fires once when the regime flips (invalidation event). `regime_check` is a continuous validation: "regime is still trend." A trend trade entered before a flip needs both — the change event triggers reduce; the continuous check downgrades grade as long as the rotation persists.

13. **`compound` exists in two places now.** Originally only for `invalidation_conditions`; v1.1.1 extends it to `TriggerSpec` (e.g., TD VWAP's "scratch if 15 min elapsed AND MFE < 0.3R"). Both use the same `{op, conditions[]/triggers[]}` shape — single implementation in the evaluator.

14. **`trade_state` grew.** Added `is_re_entry` (for one-attempt-only rules in backside playbooks), `entry_method` (for trend's pullback-vs-breakout distinction), `prior_levels_nearby` (for confluence quality_indicators), `exit_reason` (for evaluated_at: "exit" quality rules). The orchestration layer is now responsible for assembling more state before invoking the evaluator. This is the right tradeoff — keeps evaluator pure.

15. **`market_context` grew.** Added `band_slope` (for fanning/flatness checks) and `ema_9` (for backside level_breach). 9 EMA is the only non-VWAP-band level required by any v1.1 strategy — confirming Trader Dale + Smolen are the canonical sources. Other moving averages (50 SMA, 200 SMA from chart defaults) are quality/discretion, not registry-required.

16. **Management-rule sparsity correlates with playbook archetype.** Mean-reversion rotation (TD VWAP) and one-shot fades (backside) have 1 management rule. Pull-ins and trend trades — multi-stage setups with band-by-band management — have 3 each. The schema doesn't need to enforce this; it's emergent.

17. **Backside `exit_at_target_not_stop` / `exit_at_stop` mutual exclusion captures binary outcome cleanly.** Pairing them with `evaluated_at: "exit"` + opposite directions + `exclusive_with` means the grade reflects WHICH way the trade resolved without double-counting. Pattern is reusable for any strategy with clear binary exit outcomes.

18. **Trend-trade-long is hard-blocked** — its 3 required validation_rules include `regime_check { regime: "trend" }`. The classifier currently tags 100% of trades as ROTATION (per memory empirical 2026-04-21). Every trend trade live-grades as OFF-BOOK until the classifier is fixed. Added inline `_blocker_note` on the entry. **Decision needed:** does the schema formalize a `blockers: string[]` field on each strategy entry, so generators can refuse to live-grade a strategy with active blockers? Recommend yes — promote `_blocker_note` to `blockers: string[]` in v1.2.

19. **Quality weight sums vary by strategy** — TD VWAP totals 0.60 (3 indicators), pull-in totals 1.10 (5 indicators with one mutual-exclusion pair), trend-trade totals 0.90, backside totals 1.00 (with one mutual-exclusion pair). Mapping a 0..1.10 raw score onto A/B/C/F letter grades requires per-strategy normalization OR a global rescaler. **Recommend the evaluator computes `score_normalized = raw_score / max_possible_score_for_this_strategy`**, then maps the normalized 0..1 to letters. Schema computes raw; evaluator normalizes per strategy.

### Findings from running evaluate.py against the live registry (2026-05-12)

20. **`still_in_pullback_zone` as a required continuous validation is too strict.** **[RESOLVED 2026-05-12]** Smoke test against `vwap-pull-in-long` with a healthy mid-trade scenario showed `band_range[lb2..vwap]` failing because price LEAVES the entry zone the moment the trade starts working. Audit of all 9 strategies completed via `fix_validation_rules.py`. Result: only `vwap-pull-in-long` and `vwap-pull-in-short` had this issue (both removed `still_in_pullback_zone`). Other strategies' validation_rules were continuous-valid (td-vwap's `price_in_rotation_zone` stays within stop..target throughout the trade; trend-trade's `price_still_above_ub2` requires holding above the pullback level; backside's `still_above_vwap` requires price not yet at target). Post-fix smoke test: healthy vwap-pull-in-long mid-trade now grades A; broken-VWAP scenario still correctly OFF-BOOKs. Audit complete.

21. **Test 4 (trend-trade-long with broken regime classifier) reproduces the blocker exactly.** Evaluator returns OFF-BOOK with `regime_still_trend` in rules_failed. Confirms the blocker is concrete, not theoretical — every live trend trade will OFF-BOOK until the classifier is fixed. This is now the single most leveraged P1 task: fix regime detection → unblocks two strategies at once.

22. **`stop_breach` dispatcher needs strategy context.** **[RESOLVED 2026-05-12]** Refactored `_dispatch` and all 21 type-fn signatures to take `strategy` as a fourth parameter. Side-channel attribute removed. Smoke test still passes; behavior unchanged. Schema unchanged.

23. **`tolerance_sd` field on level_hold is unused in v1 evaluator.** The dispatcher checks above/below strictly. Implementing tolerance requires computing an SD-band-equivalent offset at the comparison level. v1.2 candidate; not critical for current usage since all current entries have `tolerance_sd: 0.0` or implicit zero.

---

## Recommended promotion sequence

1. **Freeze the Type Catalog** above. No new types until v1.2.
2. **Author v1.1 fields for the other 6 strategies** — td-vwap-long, td-vwap-short, vwap-pull-in-short, trend-trade-long, backside-scalp-short, backside-long-long. Skip off-book (auto-F sentinel, no rules).
3. **Fix the regime classifier** (queued task) — otherwise trend-trade-long can't be live-graded.
4. **Document the evaluator API** in a separate spec (above is the v1.1 contract).
5. **Promote v1.1 → schema_version: 2** in `strategies.json` once all 7 strategies are authored.
6. **Then** write `evaluate.py` — the pure function. ~200 lines if the schema is right.
7. **Then** DDL + cron for `main.live_trade_evaluations`. Live + EOD batch both call `evaluate.py`.
8. **Then** cockpit reads.

This is the same author-and-test-the-schema discipline that worked for v1. If the schema is wrong, find out in step 2 (cheap), not step 7 (expensive).

---

## Provenance

- Generated by: hand-authored v1.1 draft
- Source material: this session's architectural reframe + memory (`project_strategy_framework.md`, `project_system_contract.md`), Trader Dale VWAP book, Param Surface DB empirical 2026-04-21
- Stress-test target: `vwap-pull-in-long` (only strategy with empirical data to ground the quality_indicators)
- Last update: 2026-05-12
