Developer Handoff - Grid Exit Strategy Implementation

Date: 2026-02-01
Status: Ready for Development
Phase: Phase 2 - Complete Grid Exit Strategy
Estimated Effort: 50-70 hours


Quick Start

What You’re Building

You’re implementing the Grid Exit Strategy - the core value proposition of the regime management system. This enables profitable grid trading at scale by identifying regime breaks before they destroy accumulated profits.

Current State:

  • Phase 1 COMPLETE - All 6 regime detection metrics implemented (ADX, Efficiency Ratio, Autocorrelation, OU Half-Life, Normalized Slope, Bollinger Bandwidth)
  • PR#6 merged to main - 60 tests passing, 100% coverage
  • Real metrics working - No more hardcoded dummy values

What’s Missing:

  • ❌ Exit state transitions (WARNING → LATEST_ACCEPTABLE_EXIT → MANDATORY_EXIT)
  • ❌ Trigger logic for each exit state
  • ❌ State tracking in Git
  • ❌ Historical data loading
  • ❌ Integration tests

Key Documents

START HERE:

  1. EPIC-phase-2-exit-strategy.md - Your detailed work breakdown

    • 6 stories with acceptance criteria
    • Technical specifications
    • Test requirements
    • Definition of done
  2. RAIA.md - Risks, Assumptions, Issues, Actions log

    • Critical assumptions to validate
    • Known risks and mitigations
    • Actions to track
  3. implementation-plan.md - Complete SOW (Phases 1-5)

    • Phase 2 details (lines 447-712)
    • Context on what comes after

Reference Documents:

  • prd.md - Product requirements (partial - workflow paused at step 5)
  • design-review.md - Architecture and gap analysis
  • regime-management/requirements.md - Original requirements
  • regime-management/design.md - System design

Phase 2 Execution Plan

Story Sequence (Recommended Order)

Week 1:

  1. Story 2.4: Historical Data Loading (4-6h)

    • Build foundation for other stories
    • Implement MetricsHistoryLoader
    • Test with real metrics from market-maker-data/
  2. Story 2.1: LATEST_ACCEPTABLE_EXIT Triggers (8-12h)

    • Implement 4 trigger conditions
    • Unit tests for each trigger
    • Configurable thresholds

Week 2: 3. Story 2.2: WARNING Triggers (4-6h)

  • Implement 2+ condition logic
  • Unit tests for combinations
  1. Story 2.3: State Transition Tracking (4-6h)
    • Git-backed state history
    • Rate limiting logic

Week 3: 5. Story 2.5: Integration & E2E Testing (8-12h)

  • Wire everything together
  • Real data validation
  • Performance testing
  1. Story 2.6: Configuration & Documentation (4-6h)
    • YAML configuration
    • Documentation
    • Tuning guides

Critical Design Decisions

1. Evaluation Cadence: 1-Hour (Not 15-Minute)

Decision: Start with 1-hour evaluation cycle
Rationale: Research indicates 12-24 hour warning windows for regime transitions
Assumption to Validate: See RAIA A001, A004 - will be tested in Phase 4 backtesting
Implementation: Kubernetes CronJob schedule: "0 * * * *"

If assumption proves wrong: Can switch to 15-minute or adaptive cadence

2. WARNING Requires 2+ Conditions (Not Single)

Decision: WARNING state requires 2+ warning conditions to trigger
Rationale: Prevent false alarms from single noisy indicators
Configuration: warning.minimum_conditions_required: 2

Why This Matters: Single-condition triggers would generate excessive notifications and erode user trust

3. Git-Backed State Tracking

Decision: Store state transitions in market-maker-data/exit_states/{symbol}/
Rationale: Immutable audit trail, version controlled, no database needed
Format: Daily JSON files per symbol

4. Rate Limiting

Decision: Prevent notification spam with state-specific rate limits:

  • WARNING: Max 1 per 4 hours
  • LATEST_ACCEPTABLE_EXIT: Max 1 per 2 hours
  • MANDATORY_EXIT: Max 1 per 1 hour

Why: Prevent notification fatigue while ensuring critical alerts get through


Testing Strategy

Unit Tests (Target: 90%+ Coverage)

Each trigger function:

  • Happy path (trigger fires)
  • Boundary conditions (threshold = value, threshold +/- epsilon)
  • Edge cases (missing data, insufficient history, NaN values)
  • Invalid inputs

State tracking:

  • File creation, appending, reading
  • Rate limiting with real timestamps
  • Cache invalidation

Historical loading:

  • Load from Git (mocked file system)
  • Multi-timeframe extraction
  • Cache hit/miss scenarios

Integration Tests (5+ Scenarios)

See Story 2.5 for detailed scenarios:

  1. Full state progression: NORMAL → WARNING → LATEST_ACCEPTABLE → MANDATORY
  2. WARNING requires 2+ conditions
  3. Rate limiting prevents spam
  4. LATEST_ACCEPTABLE triggers independently
  5. Real data validation (last 7 days)

Real Data Validation

Critical: Run completed exit evaluator against last 7 days of metrics from market-maker-data/

Validate:

  • Exit states are reasonable (no wild oscillations)
  • State transitions make sense
  • No excessive false positives
  • Timing aligns with regime changes

Configuration Management

Exit Strategy Config (config/exit_strategy_config.yaml)

exit_rules:
  latest_acceptable_exit:
    transition_persistence_4h_bars: 2
    transition_persistence_1h_bars: 4
    mean_reversion_halflife_multiplier: 2.0
    volatility_expansion_threshold: 1.25
    zscore_reversion_failure_bars: 6
    
  warning:
    minimum_conditions_required: 2  # CRITICAL
    transition_probability_threshold: 0.40
    regime_confidence_decline_bars: 3
    efficiency_ratio_threshold: 0.6
    mean_reversion_slowdown_threshold: 1.5
    volatility_expansion_min: 1.10
    volatility_expansion_max: 1.25
    
  mandatory_exit:
    consecutive_closes_outside_range: 2
    directional_swing_bars: 6
    stop_loss_buffer_atr: 0.1
    
notifications:
  rate_limits:
    warning_min_hours: 4
    latest_acceptable_min_hours: 2
    mandatory_min_hours: 1

All thresholds must be configurable - no hardcoded values in code


Code Structure

New Files to Create

repos/market-making/metrics-service/src/
├── exit_strategy/
│   ├── triggers/
│   │   ├── __init__.py
│   │   ├── latest_acceptable.py      # Story 2.1
│   │   └── warning.py                # Story 2.2
│   ├── state_tracker.py              # Story 2.3
│   └── history_loader.py             # Story 2.4
└── tests/
    ├── unit/
    │   ├── test_latest_acceptable_triggers.py
    │   ├── test_warning_triggers.py
    │   ├── test_state_tracker.py
    │   └── test_history_loader.py
    └── integration/
        └── test_exit_strategy_flow.py  # Story 2.5

Files to Modify

repos/market-making/metrics-service/src/
└── exit_strategy/
    └── evaluator.py                  # Story 2.5 - wire up all triggers

Git Workflow

Branch Strategy

# Create feature branch from main
git checkout main
git pull origin main
git checkout -b feature/phase-2-exit-strategy
 
# Work on individual stories
git checkout -b feature/story-2.1-latest-acceptable-triggers
# ... implement, test, commit ...
git push origin feature/story-2.1-latest-acceptable-triggers
# Create PR, get reviewed, merge to feature/phase-2-exit-strategy
 
# Repeat for each story
# When Phase 2 complete, merge feature/phase-2-exit-strategy to main

Commit Messages

[STORY-2.1] Implement TRANSITION persistence trigger

- Add check_transition_persistence() function
- Support 4h and 1h bar persistence checking
- Configurable thresholds via YAML
- Unit tests with 90% coverage

Testing Locally

Run Unit Tests

cd repos/market-making/metrics-service
pytest tests/unit/test_latest_acceptable_triggers.py -v

Run Integration Tests

pytest tests/integration/test_exit_strategy_flow.py -v

Run Against Real Data

# Load last 7 days of metrics from market-maker-data repo
python -m src.exit_strategy.validate_real_data \
  --data-repo ../../../market-maker-data \
  --symbol ETH-USDT \
  --days 7

Check Coverage

pytest --cov=src/exit_strategy --cov-report=html
open htmlcov/index.html

Definition of Done (Phase 2)

Code Complete

  • All 6 stories implemented and merged
  • No hardcoded thresholds (all via YAML config)
  • Type hints throughout
  • Docstrings for all functions

Testing Complete

  • 90%+ test coverage for exit strategy code
  • All unit tests passing
  • All integration tests passing
  • Real data validation complete (no wild state oscillations)

Documentation Complete

  • Configuration documented
  • Trigger logic explained
  • Tuning guide created
  • README updated

Quality Gates

  • Code reviewed by Craig
  • CI/CD passing
  • No linting errors
  • Performance acceptable (<1 second per evaluation)

Support & Questions

Primary Contact: Craig

Key Resources:

  • Implementation plan: implementation-plan.md (lines 447-712)
  • RAIA log: RAIA.md (track assumptions and risks)
  • Original requirements: regime-management/requirements.md

Stuck? Check:

  1. EPIC-phase-2-exit-strategy.md for detailed acceptance criteria
  2. implementation-plan.md for technical context
  3. RAIA.md for known issues and assumptions
  4. Phase 1 code (metrics implementation) for patterns and style

Next Steps After Phase 2

Phase 3: Position Risk Quantification (30-40h)

  • KuCoin position tracker
  • Capital risk calculator
  • Enhanced notifications with risk metrics

Phase 4: Testing & Validation (40-50h)

  • Backtesting framework (validates RAIA assumptions)
  • Comprehensive test coverage
  • CI/CD integration

Phase 5: Operational Improvements (20-30h)

  • Audit logging
  • KPI tracking
  • Investor documentation

Ready to Start? Begin with Story 2.4 (Historical Data Loading) - it’s the foundation for everything else.

Questions Before Starting? Review EPIC-phase-2-exit-strategy.md and reach out to Craig.

Good luck! 🚀