# M2/M3 Code Quality Refactoring Plan

**Last Updated:** 2025-09-12

## 1. Objective

Improve the readability, maintainability, and clarity of the core M2/M3 logic block within `MainStrategy.pine` without causing a performance regression from our new **256,537%** "Golden Baseline".

This is a high-risk refactoring effort due to the component's known fragility, as documented in `M2_Indicator_Regression_Investigation.md`.

## 2. Methodology

A strict, methodical approach will be followed to minimize risk.

1.  **Isolate Work:** All work will be done on a dedicated `feature/m2-refactor` branch.
2.  **Analyze First:** No code will be changed until a thorough forensic analysis is complete and a specific to-do list is created.
3.  **Implement Incrementally:** Changes will be made in small, logical chunks.
4.  **Test Continuously:** After each significant change, a 1D backtest will be run to check for any deviation from the 256k% baseline. If a regression occurs, the change will be reverted and re-evaluated.
5.  **Final Verification:** Once all tasks are complete, a final backtest will confirm that the baseline performance is fully maintained. Only then will the changes be considered for merging.
    *   **Performance Check:** After final verification, check the script's execution time. The pre-refactor execution time is approximately **9 seconds**. We must ensure the refactoring has not introduced significant performance overhead.

## 3. Phase 1: Forensic Analysis & Task Creation

This initial phase involves a deep dive into the M2/M3 code block in `MainStrategy.pine` to identify specific areas for improvement. The goal is to produce a concrete checklist of refactoring tasks.

### Task 1: Correct Smoothing Logic & Clarify Naming

**Objective:** Fix the currently misleading smoothing logic and rename variables for clarity.

**Specific Actions:**

1.  **Correct Smoothing Logic:** The `micro`, `mini`, and `tiny` offsets are all incorrectly smoothed with the `shortOffset`'s smoothing length. We will fix this by introducing new, dedicated smoothing length inputs for each.
    *   Add new input: `i_m2LeadingIndicator_microOffset_smoothingLength`
    *   Add new input: `i_m2LeadingIndicator_miniOffset_smoothingLength`
    *   Add new input: `i_m2LeadingIndicator_tinyOffset_smoothingLength`
    *   Update the `m2_smoothed_microOffset`, `m2_smoothed_miniOffset`, and `m2_smoothed_tinyOffset` calculations to use their new, corresponding smoothing lengths.

2.  **Clarify `...Slope` variables:** These variables calculate the slope of a historically-offsetted series. The names should reflect this.
    *   `m2_smoothedTinyOffsetSlope` -> `m2_slope_tinyOffset`
    *   `m2_smoothedShortOffsetSlope` -> `m2_slope_shortOffset`
    *   `m2_smoothedMediumOffsetSlope` -> `m2_slope_mediumOffset`
    *   `m2_smoothedLongOffsetSlope` -> `m2_slope_longOffset`

3.  **Clarify `...DiffTo...` variables:** These variables calculate an absolute difference. We will rename them to make this explicit, paving the way for a future migration to percentage-based differences.
    *   `m2_tinyOffsetDiffToNbarsOut` -> `m2_diff_abs_tinyOffset_to_future`
    *   `m2_shortOffsetDiffToNbarsOut` -> `m2_diff_abs_shortOffset_to_future`
    *   `m2_mediumOffsetDiffTo12barsOut` -> `m2_diff_abs_mediumOffset_to_future`

### Task 2: Code Duplication Analysis

**Objective:** Find and consolidate redundant calculations.

**Specific Actions:**

1.  **Consolidate `is...Rising/Falling` Logic:** The calculation of the rising and falling status for the various M2 offsets is inconsistent and contains bugs.
    *   **Bug:** `isM2SmoothedTinyOffsetRising` and `isM2SmoothedTinyOffsetFalling` are incorrectly calculated using `m2_smoothed_shortOffset` as their source.
    *   **Action:**
        1.  Correct the source for the `tinyOffset` rising/falling calculations to use the `m2_smoothed_tinyOffset` variable (after it has been fixed in Task 1).
        2.  Verify that all other `is...Rising` and `is...Falling` variables are using their correct corresponding source (e.g., `isM2SmoothedShortOffsetRising` uses `m2_smoothed_shortOffset`).
        3.  Ensure there are no other instances of the same `ta.rising` or `ta.falling` calculation being performed and stored in different variables.

### Task 3: Logic & Commenting Analysis

**Objective:** Add comments to explain obscure logic.

**Specific Actions:**

1.  **Document the "Future Value" Calculation:** The block of code that calculates `m2_smoothedTiny_N_bars_out` and the subsequent `...DiffToNbarsOut` variables is highly non-intuitive.
    *   **Action:** Add a detailed block comment explaining the methodology:
        1.  The strategy uses a historical offset (`i_m2LeadingIndicator_...Offset`) to treat the M2 money supply data as a leading indicator.
        2.  It then calculates a "future" value by looking at this offsetted series *minus* a certain number of bars (`i_m2LeadingIndicator_barsToRightOfShortLength`).
        3.  The difference between this "future" value and the "current" offsetted value is used to determine the projected trend or momentum of the M2 indicator.
    *   This comment will clarify the purpose of these complex historical lookups.

### Task 4: Future Enhancement - Migrate to Percentage Differences

**Objective:** Improve the robustness of the "difference to future" calculations by migrating them from absolute values to percentage-based differences.

**Specific Actions:** This is a future task. Once the initial cleanup is complete, we will investigate the best way to implement and test this change, potentially creating new variables like `m2_diff_pct_tinyOffset_to_future` to run in parallel with the absolute versions for comparison.
