# Implementation Plan: 8hr Long Exit Optimization

**Branch**: `feature/8hr-long-exit-optimization` | **Date**: 2023-10-27 | **Spec**: `spec.md`
**Input**: Feature specification from `../../docs/8hr_long_exit_optimization/spec.md`

## Summary
This feature will introduce a new long exit condition to the strategy that triggers based on the detection of classic bearish candlestick patterns ("Three Black Crows", "Bearish Engulfing", "Evening Star") on the 8-hour timeframe. This is intended to protect profits by exiting positions before a potential downturn. The feature will be controlled by a user-configurable switch and will log the specific pattern that triggered the exit.

## Technical Context
**Language/Version**: Pine Script v6
**Primary Dependencies**: Existing project libraries (`LibraryLongExit`, `LibraryUtility`)
**Storage**: N/A
**Testing**: Manual Backtesting and Visual Verification via a dedicated `Indicator` script.
**Target Platform**: TradingView
**Project Type**: Single (Strategy with supporting libraries)
**Performance Goals**: No regression on the **256,537%** 1D baseline.
**Constraints**: The new exit logic must only be active when the chart's timeframe is set to 8 hours ("480").
**Scale/Scope**: Addition of one new exit condition and three pattern detection functions.

## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*

**Simplicity**:
- Projects: [1] (main strategy) - PASS
- Using framework directly? (yes, Pine Script built-ins) - PASS
- Single data model? (yes) - PASS
- Avoiding patterns? (yes) - PASS

**Architecture**:
- EVERY feature as library? (yes, logic will be in `LibraryLongExit`) - PASS
- Libraries listed: `LibraryLongExit` (new exit logic), `LibraryUtility` (potential helpers) - PASS
- CLI per library: N/A
- Library docs: N/A

**Testing (NON-NEGOTIABLE)**:
- RED-GREEN-Refactor cycle enforced? (will be verified via visualization indicator) - PASS
- Git commits show tests before implementation? (N/A for Pine Script)
- Order: Contract→Integration→E2E→Unit strictly followed? (N/A for Pine Script)
- Real dependencies used? (yes) - PASS
- Integration tests for: new libraries, contract changes, shared schemas? (N/A for Pine Script)
- FORBIDDEN: Implementation before test, skipping RED phase - PASS

**Observability**:
- Structured logging included? (yes, via trade log reason) - PASS

**Versioning**:
- Version number assigned? (will be part of next release) - PASS

## Project Structure

### Documentation (this feature)
```text
docs/8hr-long-exit-optimization/
├── spec.md              # The feature specification
├── plan.md              # This file
└── tasks.md             # To be created by the /tasks command
```

### Source Code (repository root)
```
# Option 1: Single project (DEFAULT)
src/
├── models/
├── services/
├── cli/
└── lib/

tests/
├── contract/
├── integration/
└── unit/
```

**Structure Decision**: Option 1 (Single Project) is appropriate. The changes will be within the existing Pine Script library and strategy files.

## Phase 0: Outline & Research
1.  **Research Pine Script Implementations**:
    *   Task: "Find and validate robust Pine Script functions for detecting 'Three Black Crows'."
    *   Task: "Find and validate robust Pine Script functions for detecting 'Bearish Engulfing'."
    *   Task: "Find and validate robust Pine Script functions for detecting 'Evening Star'."
    *   Consolidate findings into `research.md`.

## Phase 1: Design & Contracts
*Prerequisites: research.md complete*

1.  **Data Model (`LibraryUtility.pine`)**:
    *   Create three new exported functions based on research:
        *   `f_isThreeBlackCrows() -> bool`
        *   `f_isBearishEngulfing() -> bool`
        *   `f_isEveningStar() -> bool`

2.  **Core Logic (`LibraryLongExit.pine`)**:
    *   Add a new boolean field `i_enable_longExit_2hrCandlePattern` to the `EnablementInputs` type.
    *   Add a new boolean field `longExit_8hrCandlePattern` to the `Results` type.
    *   In the main `f_calculateLongExit` function, implement the logic:
        *   Check if `timeframe.period == "480"`.
        *   If true, call the three pattern detection functions from `LibraryUtility`.
        *   Set `longExit_8hrCandlePattern` to `true` if any of the patterns are detected.
    *   Update the aggregated `longExit` boolean to include the new condition.
    *   Update the `longExitConditionName` logic to return the correct pattern name (e.g., "Exit: 8hr Three Black Crows") when the condition fires.

3.  **Integration (`MainStrategy.pine`)**:
    *   Add the new `input.bool()` for `i_enable_longExit_8hrCandlePattern`, disabled by default.
    *   Pass the new enablement input to the `LibraryLongExit` function call.

4.  **Visualization (`IndicatorLongExitBooleans.pine`)**:
    *   Mirror the new `input.bool()` from the main strategy.
    *   Update the library call to pass the new input.
    *   Add a new `plot()` call to visualize when `longExit_8hrCandlePattern` is true, allowing for visual verification (the "test").

## Phase 2: Task Planning Approach
*This section describes what the /tasks command will do - DO NOT execute during /plan*

**Task Generation Strategy**:
- Generate tasks based on the Phase 1 design.
- **TDD Order**: The first implementation task will be to add the plot to `IndicatorLongExitBooleans.pine`. This plot will serve as our failing "test".
- **Dependency Order**: Create utility functions first, then library logic, then integrate into the main strategy.
- Mark tasks that can be done in parallel [P], such as creating the three utility functions.

**Estimated Output**: 10-15 numbered, ordered tasks in `tasks.md`.