# Multi-Timeframe Performance Improvement Plan

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

## Objective

To improve the performance of `MainStrategy.pine` on shorter timeframes (specifically `12H`, with `8H`, `6H`, `4H` as secondary targets) without negatively impacting the established performance on the `1D` timeframe.

## Methodology

The core methodology is to evolve the strategy from a "one-size-fits-all" model to a "timeframe-aware" model. We will systematically identify which parts of the strategy are sensitive to the chart's timeframe, analyze the reasons for performance degradation, and adapt the logic and parameters accordingly. This will be accomplished through a phased approach.

### Critical Learning: The "Conditional Assignment" Trap

Extensive testing during the M2 refactor has proven the "Execution Flow" hypothesis from `architecture.md`. The 1D baseline's performance is critically dependent on a purely linear script execution.

**Failed Pattern:**
```pinescript
// This pattern causes a performance regression on the 1D baseline.
var float m2_slope_shortOffset = na
if timeframe.period == "D"
    m2_slope_shortOffset := // calculation using 1D inputs
else
    m2_slope_shortOffset := // calculation using 12H inputs
```

**Root Cause:** Using `var` to declare a variable and then conditionally reassigning it (`:=`) inside an `if/else` block breaks the linear execution flow. This alters how Pine Script's runtime manages the historical state of variables, causing the performance degradation even when the 1D logic is identical.

**Conclusion:** To preserve the 1D baseline, we must avoid this pattern. The correct "dual-path" architecture requires creating two completely separate, parallel calculation pipelines and selecting the final output with a ternary operator (`?:`). This is now a core architectural constraint.

### Core Testing Philosophy: Isolate and Validate

To avoid the pitfalls of chasing a single "net profit" metric, which can be misleading, all future tuning will follow a more disciplined, component-focused approach.

1.  **Isolate Conditions:** When tuning or developing a new condition, it must be enabled in isolation. All other non-essential entry conditions should be disabled to get a clear signal of its individual performance.
2.  **Dual-Metric Validation:** After making a change to a specific condition, the backtesting process must validate two things:
    *   **Overall Regression Check (1D):** The overall strategy performance on the 1D chart must be checked to ensure no major regressions have been introduced to the baseline.
    *   **Condition-Specific Performance (1D & 12H):** The performance of the *specific condition under test* must be analyzed on both timeframes. This involves reviewing the trades generated *only by that condition* to assess its win rate and profitability.
3.  **Incremental Integration:** Only after a condition has been proven effective in isolation should it be re-enabled and tested in combination with other proven conditions.

This disciplined process ensures we are making data-driven improvements to individual components rather than getting distracted by the noise of the overall system.

---

### Phase 1: Establish Baseline & Create Timeframe-Aware Settings Framework

This phase is about setting up the infrastructure for our work. It provides the foundational tools that make all subsequent phases easier and is designed to deliver a quick, confidence-building win.

1.  **Quantify Performance (The "Before" Picture):**
    *   **Action:** Run the current `MainStrategy.pine` on the `1D` timeframe and record key performance metrics (Net Profit, Profit Factor, Max Drawdown, # of Trades). This is our **Golden Baseline**.
    *   **Action:** Run the same strategy on the `12H` timeframe and record the same metrics. This is our **Improvement Target**.

2.  **Implement a Timeframe-Aware Settings Manager:**
    *   **Concept:** Create a system that allows strategy parameters (e.g., indicator lengths, thresholds) to have different values based on the chart's current timeframe.
    *   **Action:** Implement a function or set of functions (likely in `LibraryUtility.pine` or a new dedicated library) that can be called from `MainStrategy.pine`. This function will take a parameter name and return the appropriate value for the active timeframe (`1D`, `12H`, etc.).
    *   **Goal:** This immediately decouples the `1D` settings from the shorter timeframe settings, allowing us to tune for `12H` without any risk to the `1D` baseline.

---

### Phase 2: Analyze and Adapt Key Indicators

With the framework from Phase 1 in place, this phase focuses on diagnosing *why* the strategy underperforms on shorter timeframes and adapting the indicators to handle the increased noise and speed.

1.  **Visual Analysis with a "Component Analyzer":**
    *   **Concept:** The existing `IndicatorConditionAnalyzer.pine` shows the final boolean outcome. We need to see the *inputs* to those decisions.
    *   **Action:** Create a new `ComponentAnalyzer.pine` indicator script. This script will not show a table, but will instead plot the key *float* values from our libraries that are used in the long entry conditions (e.g., `rsid_osc`, `stoch_value`, `m2_shortOffsetDiffToNbarsOut`, `macd_slope_current`).
    *   **Methodology:** Use this new analyzer to visually compare the behavior of these components on the `1D` chart vs. the `12H` chart around successful and failed trade signals. This will highlight which components become too "noisy" or behave erratically on the shorter timeframe.
    *   **Refinement:** Iteratively refine the analyzer by adding/removing components and scaling values with vastly different ranges (e.g., using `f_scale_ToRange`) to ensure all plots are readable and comparable. This includes plotting raw values in the data window for debugging.

2.  **Hypothesis-Driven Tuning:**
    *   **Concept:** Based on the visual analysis, form specific, testable hypotheses.
    *   **Example Hypothesis:** *"The `rsid_osc` value is too volatile on the `12H` chart, causing false signals. Increasing its lookback period specifically for the `12H` timeframe should smooth it out and improve performance."*
    *   **Action:** Use the Timeframe-Aware Settings Manager (from Phase 1) to test these hypotheses by adjusting parameters for the `12H` chart only.
    *   **Test:** Rerun the `12H` backtest after each change and compare the metrics to the `12H` target baseline to measure improvement.

    **Guiding Principle for Defaults:** When creating new timeframe-specific inputs (e.g., `_12H`), the default values should be set intelligently:
    *   For **length- or offset-based parameters**, the default should be calculated to maintain the same *time duration* as the 1D setting (e.g., a 10-bar 1D lookback becomes a 20-bar 12H lookback).
    *   For **threshold-based parameters** (e.g., RSI levels, slope values), the default should start as the same value as the 1D setting.

    **Progress Log:**
    *   **RSI:** Created separate 1D/12H inputs for `lookback`, `overbought`, and `oversold`. Found better performing defaults for 12H.
    *   **Stochastic:** Created separate 1D/12H inputs for `smoothK` and `lengthStoch`. Found that shorter lengths (`2`, `12`) performed better on 12H, contrary to the initial "more smoothing" hypothesis. This improved performance.
    *   **MACD:** Created separate 1D/12H inputs for `fast_length`, `slow_length`, and `signal_length`. Found that slightly longer lengths (`15`, `35`) improved performance on 12H.

    **Next Steps (as of 2025-09-09):**
    *   **Adapt Realized Price:** The next component to adapt for multi-timeframe support is the Realized Price indicator. This involves creating `_1D` and `_12H` inputs for its parameters in `MainStrategy.pine` and using the `f_getParamForTimeframe_int` utility to select the appropriate values.
        *   **Action Plan:**
            1.  In `MainStrategy.pine`, identify all `input` variables related to `realizedPriceSettings`.
            2.  For each input, create a `_1D` and a `_12H` version.
            3.  Apply the "Guiding Principle for Defaults":
                *   For length-based inputs (`smoothingLength`, `realizedPriceLength`, `pivotLeft`, `pivotRight`, `gaussianLen`), set the `_12H` default to be `2 *` the `_1D` default to maintain the same time duration.
                *   For threshold-based inputs (`gaussianMult`, `bullNuplThreshold`, `bearNuplThreshold`), set the `_12H` default to be the same as the `_1D` default.
            4.  Use `utils.f_getParamForTimeframe_int` (or a new `_float` version if needed) to create new timeframe-aware variables from these inputs.
            5.  Update the `realizedPriceSettings` object to use these new timeframe-aware variables.
            6.  Following the "Core Testing Philosophy," disable all other long entry conditions except for those related to Realized Price (`realized_price_bull_div`, etc.).
            7.  Run backtests on 1D and 12H to validate the change, checking for overall regression on 1D and analyzing the specific performance of the Realized Price conditions on both timeframes.

    *   **M2 Indicator (On Hold):** Work on adapting the M2 Leading Indicator for multi-timeframe support is currently on hold. Due to its complexity and fragility, **no work should be attempted on this component without first thoroughly reviewing the "Future Work" section of `M2_Indicator_Regression_Investigation.md`**.

---

### Phase 3: Address Logic Refinements and Specific Issues

This phase tackles more complex logic problems and pre-existing issues that may be hindering performance across all timeframes.

1.  **Fix Known Issues:**
    *   **Action:** Systematically work through the issues documented in `issues.txt`.
    *   **Priority Example:** The "Medium" priority issue (`Refactored exit logic has caused performance degradation`) is a prime candidate. The current `final_exit := finalExitCondition and not longCondition` logic is likely too general and needs to be refined to respect specific entry/exit condition pairings.

2.  **Refine Core Logic:**
    *   **Concept:** As we gain insights from Phase 2, we may discover that some conditions are fundamentally unsuited for shorter timeframes, or that new, faster-reacting conditions are needed.
    *   **Action:** This could involve disabling certain entry/exit conditions on shorter timeframes or developing new conditions specifically for them. The modular architecture will make adding or modifying these conditions straightforward.

---