# Feature Specification: Condition Analyzer Indicator

## 1. High-Level Goal

To create a "Condition Analyzer" indicator that provides a detailed, instance-by-instance view of which trading signals are active whenever a primary "trigger" condition fires. This tool is designed to help strategists identify effective filtering conditions to improve the precision of entries and exits, forming a key part of the condition refinement workflow.

## 2. Key Features (User Stories)

*   As a user, I want to select a single "trigger" condition from a dropdown list containing all available long entry conditions.
*   As a user, I want to see a table that populates with data as the script executes over the chart's history.
*   The table's top header row should display "Condition Name" in the first cell, followed by the date of each trigger event (e.g., "01-25-24").
*   The table's first column (the row headers) should list the names of all available long entry conditions, in the same order they are presented in the main strategy.
*   When the selected trigger condition fires, a new column for that event should be added to the table.
*   In this new event column, a colored square will appear in the row of any other condition that was also `true` on the same bar. The cell will be empty if the condition was `false`.
*   As a user, I want the color of the square to match the color used for that condition in the `IndicatorLongEntryConditions.pine` script to maintain visual consistency across tools.
*   As a user, I want to hover my mouse over any colored cell to see a tooltip with the condition name and the date of the event, allowing for a compact view.
*   As a user, I want to control the text size in the table to make it more or less compact.
*   As a user, I want the option to display date headers vertically to save horizontal space.
*   As a user, I want to be able to hide the row and column headers to create a dense, "heatmap" style view.
*   As a user, I want an option to automatically hide rows for conditions that never fired, to focus only on relevant data.

## 3. Implementation Plan

*   **New Script:** All logic will be contained in a new script: `IndicatorConditionAnalyzer.pine`.

*   **Synchronization Requirement:** This indicator must duplicate all necessary inputs and calculation logic from `MainStrategy.pine`. This is a critical maintenance step to ensure the analyzer has access to the true state of all conditions as seen by the strategy.

*   **User Inputs:**
    *   An `input.string()` with a dropdown (`options`) will allow the user to select the primary "trigger" condition. The list of options will be the names of all long entry conditions.
    *   Boolean `input.bool()` switches to control the visibility of row and column headers.
    *   A boolean `input.bool()` to toggle vertical date headers.
    *   A boolean `input.bool()` to enable or disable the "Hide Empty Rows" feature.
    *   A string `input.string()` with options (`size.tiny`, `size.small`, etc.) to control the table's text size.

*   **Data Storage:**
    *   An `array` of a custom `type` will be used to store a "snapshot" of all condition states for each trigger event. This allows the indicator to collect all events as it executes over the historical bars and then render them all at once.
    *   **Example Data Structure:**
        ```pinescript
        type ConditionSnapshot
            int bar_index
            int time // Added to store the timestamp of the event
            // A boolean for each condition in the strategy
            bool longCondition_original
            bool longCondition_new
            // ... etc. for all ~40 conditions

        var array<ConditionSnapshot> triggerEvents = array.new<ConditionSnapshot>()
        ```
    *   **Note on Array Initialization:** Arrays of literals must be created using `array.from()`, as `const string[] = [...]` or `string[] = [...]` is not valid syntax.
        ```pinescript
        // Correct
        conditionNames = array.from("name1", "name2")
        ```

*   **Trigger Logic:**
    *   On each bar, the script will check if the user-selected trigger condition is `true`.
    *   If it is, the script will instantiate a new `ConditionSnapshot` object, populate it with the boolean values of all other conditions on that bar, and push the object into the `triggerEvents` array.

*   **Table Rendering:**
    *   A `table` object will be used for the display. The table will be drawn on the last bar to ensure all historical data has been processed.
    *   The table will be cleared and redrawn on every update.
    *   The first row (column headers) and first column (row headers) will be drawn with the event numbers and condition names, respectively.
    *   **Date Formatting:** Column headers will display the date of the trigger event, formatted using `str.format("{0,date,MM-dd-yy}", snapshot.time)`. A helper function will render this string vertically by inserting newlines between characters if the user has enabled that option.
    *   **Dynamic Row Filtering:** If "Hide Empty Rows" is enabled, the script will first iterate through all captured events to build a new set of arrays (`namesToDraw`, `colorsToDraw`, `indicesToDraw`) containing only the conditions that were active at least once. The table will then be rendered using these filtered arrays.
    *   **Conditional Header Rendering:** The drawing of row and column headers will be wrapped in `if` blocks controlled by the user's boolean input switches.
    *   **Cell Rendering:** The script will iterate through the `triggerEvents` array. Each element in the array corresponds to a column in the table. For each event, it will iterate through the list of conditions to be drawn and use `table.cell()` to set the background color of the appropriate cell if the condition was `true` in that snapshot.
    *   **Tooltips:** The `tooltip` argument of `table.cell()` will be used extensively. Data cells will display the date and condition name. Header cells will display the bar index.

## 4. Challenges & Considerations

*   **Table Cell Limit:** TradingView tables are limited to approximately 50 columns and 50 rows. With ~40 long entry conditions, we will be near the row limit. The number of columns will be limited to ~50 trigger events. The implementation should gracefully handle this, perhaps by only displaying the most recent 50 events if more are found.
*   **Performance:** Redrawing a large table can be performance-intensive. The logic should be efficient, and rendering should only occur once all historical bars are processed.
*   **Synchronization Overhead:** The need to keep inputs and logic synchronized with `MainStrategy.pine` is a significant maintenance burden. This is a known constraint of the project's architecture and a mandatory step when updating any shared logic.
*   **Pine Script Syntax Quirks:** Development revealed several syntax requirements that must be respected:
    *   Array literals must be initialized with `array.from()`. The `const` qualifier cannot be used on arrays.
    *   Function parameter names cannot be the same as reserved keywords (e.g., `text`).
    *   String manipulation functions like `str.substring()` are version-dependent. Ensure the correct function is used for the script's effective version.

## 5. Role in the Development Workflow

This tool will become an essential part of the process outlined in `add_new_condition_guide.md`. After a new condition is added, a developer can: See `add_new_condition_guide.md`.
1.  Enable only the new condition in the main strategy to see its general performance.
2.  Use the **Condition Analyzer** with the new condition as the "trigger".
3.  Analyze the table to see which other signals consistently fire alongside the new condition, especially on trades that turned out to be unprofitable.
4.  Use this insight to add filtering logic (e.g., `my_new_condition and not some_other_condition`) to improve the new condition's quality.

## 6. Future Enhancements

### 6.1. Historical Lookback

*   **Concept:** Add an optional feature to display the state of all conditions for the bar(s) immediately preceding the trigger event (e.g., `t-1`, `t-2`). This can provide valuable context about the setup leading to a signal.
*   **Implementation:**
    *   This would be controlled by a user input, disabled by default.
    *   The `ConditionSnapshot` type would be expanded to store boolean states for `t`, `t-1`, and `t-2`.
    *   The table would render additional columns for each historical lookback period (e.g., "Trigger 1 (t)", "Trigger 1 (t-1)", "Trigger 1 (t-2)").
*   **Consideration:** This would significantly reduce the number of trades that can be viewed simultaneously due to the 50-column limit (from ~49 trades to ~16 trades if `t-1` and `t-2` are enabled). This is an acceptable trade-off for deep analysis on a focused date range.