# Requirements Document

## Introduction

The Intelligent Trade Recommendation System enhances the Signal Dashboard platform by providing clear, actionable trading recommendations with confidence scoring, multiple price targets, and probability estimates. The system addresses critical gaps in the current trade setup generation: contradictory signal detection, single-target limitations, and lack of directional guidance for non-professional traders.

The system analyzes multi-dimensional signals (sentiment, technical, momentum, S/R positioning) to recommend both LONG and SHORT directions with confidence scores, identifies multiple S/R-based price targets with probability estimates, and detects signal conflicts to prevent contradictory recommendations.

## Glossary

- **Trade_Recommendation_Engine**: The core system component that analyzes signals and generates directional recommendations with confidence scores
- **Direction_Analyzer**: Component that evaluates LONG vs SHORT direction based on signal alignment
- **Target_Generator**: Component that identifies multiple S/R levels as price targets
- **Probability_Estimator**: Component that calculates likelihood of reaching each target
- **Signal_Conflict_Detector**: Component that identifies contradictions between sentiment, technical, and momentum signals
- **Recommendation_Summary**: User-facing output containing recommended action, confidence, reasoning, and risk level
- **S/R_Level**: Support/Resistance level with strength score and price
- **Signal_Alignment**: Degree of agreement between sentiment, technical, momentum, and fundamental dimensions
- **Confidence_Score**: Percentage (0-100%) indicating likelihood of success for a directional recommendation
- **Target_Probability**: Percentage likelihood of price reaching a specific target level
- **ATR**: Average True Range, volatility measure used for stop-loss calculation
- **R:R_Ratio**: Risk-to-Reward ratio comparing potential profit to potential loss
- **Composite_Score**: Weighted aggregate score (0-100) from all dimensions
- **Dimension_Score**: Individual score for technical, sr_quality, sentiment, fundamental, or momentum dimension

## Requirements

### Requirement 1: Bidirectional Trade Setup Generation

**User Story:** As a trader, I want to see both LONG and SHORT trade setups for each ticker, so that I can evaluate opportunities in both directions regardless of market conditions.

#### Acceptance Criteria

1. WHEN the Trade_Recommendation_Engine analyzes a ticker, THE Trade_Recommendation_Engine SHALL generate both a LONG setup and a SHORT setup
2. THE Trade_Recommendation_Engine SHALL calculate separate entry prices, stop losses, and targets for each direction
3. WHEN generating a LONG setup, THE Trade_Recommendation_Engine SHALL use resistance levels as targets and support levels for stop-loss calculation
4. WHEN generating a SHORT setup, THE Trade_Recommendation_Engine SHALL use support levels as targets and resistance levels for stop-loss calculation
5. THE Trade_Recommendation_Engine SHALL store both setups in the TradeSetup model with distinct direction fields

### Requirement 2: Direction Confidence Scoring

**User Story:** As a non-professional trader, I want to see confidence scores for LONG vs SHORT directions, so that I can understand which direction has higher probability of success.

#### Acceptance Criteria

1. THE Direction_Analyzer SHALL calculate a confidence score (0-100%) for the LONG direction
2. THE Direction_Analyzer SHALL calculate a confidence score (0-100%) for the SHORT direction
3. WHEN sentiment is bullish AND technical score is above 60 AND momentum score is above 60, THE Direction_Analyzer SHALL assign LONG confidence above 70%
4. WHEN sentiment is bearish AND technical score is below 40 AND momentum score is below 40, THE Direction_Analyzer SHALL assign SHORT confidence above 70%
5. WHEN signal dimensions contradict each other, THE Direction_Analyzer SHALL reduce confidence scores for both directions below 60%
6. THE Direction_Analyzer SHALL store confidence scores in the TradeSetup model for each direction

### Requirement 3: Multiple Price Target Identification

**User Story:** As a trader, I want multiple price targets at different S/R levels, so that I can implement staged profit-taking and proper risk management.

#### Acceptance Criteria

1. WHEN generating targets for a LONG setup, THE Target_Generator SHALL identify 3 to 5 resistance levels above the entry price
2. WHEN generating targets for a SHORT setup, THE Target_Generator SHALL identify 3 to 5 support levels below the entry price
3. THE Target_Generator SHALL classify targets as Conservative (nearest), Moderate (mid-range), or Aggressive (furthest)
4. THE Target_Generator SHALL calculate the R:R ratio for each target level
5. WHEN fewer than 3 S/R levels exist in the target direction, THE Target_Generator SHALL use the available levels and flag the setup as having limited targets
6. THE Target_Generator SHALL order targets by distance from entry price

### Requirement 4: Target Probability Estimation

**User Story:** As a trader, I want to know the probability of reaching each price target, so that I can set realistic expectations and plan my exits.

#### Acceptance Criteria

1. THE Probability_Estimator SHALL calculate a target probability percentage (0-100%) for each price target
2. WHEN calculating probability, THE Probability_Estimator SHALL consider S/R level strength score (higher strength increases probability)
3. WHEN calculating probability, THE Probability_Estimator SHALL consider distance from entry (closer targets receive higher probability)
4. WHEN calculating probability, THE Probability_Estimator SHALL consider signal alignment (aligned signals increase probability by 10-20%)
5. WHEN calculating probability, THE Probability_Estimator SHALL consider ATR (higher volatility increases probability for distant targets)
6. THE Probability_Estimator SHALL assign Conservative targets probability above 60%
7. THE Probability_Estimator SHALL assign Moderate targets probability between 40% and 70%
8. THE Probability_Estimator SHALL assign Aggressive targets probability below 50%

### Requirement 5: Signal Conflict Detection

**User Story:** As a trader, I want to be warned when signals contradict each other, so that I can avoid high-risk trades with mixed indicators.

#### Acceptance Criteria

1. THE Signal_Conflict_Detector SHALL compare sentiment classification (bearish/neutral/bullish) with technical score direction
2. WHEN sentiment is bearish AND technical score is above 60, THE Signal_Conflict_Detector SHALL flag a sentiment-technical conflict
3. WHEN sentiment is bullish AND technical score is below 40, THE Signal_Conflict_Detector SHALL flag a sentiment-technical conflict
4. THE Signal_Conflict_Detector SHALL compare momentum score with technical score
5. WHEN momentum score and technical score differ by more than 30 points, THE Signal_Conflict_Detector SHALL flag a momentum-technical conflict
6. THE Signal_Conflict_Detector SHALL store conflict flags in the TradeSetup model
7. WHEN conflicts are detected, THE Signal_Conflict_Detector SHALL reduce confidence scores by 15-25%

### Requirement 6: Recommendation Summary Generation

**User Story:** As a non-professional trader, I want a clear recommendation summary with action, confidence, and reasoning, so that I can make informed trading decisions without analyzing raw data.

#### Acceptance Criteria

1. THE Recommendation_Summary SHALL include a recommended action field with values: "LONG (High Confidence)", "LONG (Moderate Confidence)", "SHORT (High Confidence)", "SHORT (Moderate Confidence)", or "NEUTRAL (Conflicting Signals)"
2. WHEN LONG confidence is above 70% AND LONG confidence exceeds SHORT confidence by 20%, THE Recommendation_Summary SHALL recommend "LONG (High Confidence)"
3. WHEN SHORT confidence is above 70% AND SHORT confidence exceeds LONG confidence by 20%, THE Recommendation_Summary SHALL recommend "SHORT (High Confidence)"
4. WHEN confidence scores differ by less than 20%, THE Recommendation_Summary SHALL recommend "NEUTRAL (Conflicting Signals)"
5. THE Recommendation_Summary SHALL include reasoning text explaining the recommendation based on signal alignment
6. THE Recommendation_Summary SHALL include a risk level assessment: Low (all signals aligned), Medium (minor conflicts), or High (major conflicts)
7. THE Recommendation_Summary SHALL display the composite score alongside the recommendation

### Requirement 7: Trade Setup API Enhancement

**User Story:** As a frontend developer, I want the trade setup API to return enhanced recommendation data, so that I can display confidence scores, multiple targets, and probabilities in the UI.

#### Acceptance Criteria

1. WHEN the trade setup API endpoint is called for a ticker, THE API SHALL return both LONG and SHORT setups
2. THE API SHALL include confidence_score field for each setup
3. THE API SHALL include a targets array with 3-5 target objects for each setup
4. WHEN returning target objects, THE API SHALL include price, distance_from_entry, rr_ratio, probability, and classification (Conservative/Moderate/Aggressive) fields
5. THE API SHALL include conflict_flags array listing detected signal conflicts
6. THE API SHALL include recommendation_summary object with action, reasoning, and risk_level fields
7. THE API SHALL return setups ordered by confidence score (highest first)

### Requirement 8: Historical S/R Strength Integration

**User Story:** As a system, I want to use historical S/R level strength in probability calculations, so that targets at stronger levels receive higher probability estimates.

#### Acceptance Criteria

1. THE Probability_Estimator SHALL retrieve the strength score from the SRLevel model for each target
2. WHEN an S/R level has strength score above 80, THE Probability_Estimator SHALL increase target probability by 10-15%
3. WHEN an S/R level has strength score below 40, THE Probability_Estimator SHALL decrease target probability by 10-15%
4. THE Probability_Estimator SHALL normalize strength scores to a 0-1 scale before applying to probability calculation
5. WHEN an S/R level has been tested multiple times historically, THE Probability_Estimator SHALL increase its weight in probability calculation

### Requirement 9: Volatility-Adjusted Target Selection

**User Story:** As a trader, I want target selection to account for volatility, so that targets are realistic given the ticker's typical price movement.

#### Acceptance Criteria

1. THE Target_Generator SHALL retrieve the current ATR value for the ticker
2. WHEN ATR is high (above 5% of current price), THE Target_Generator SHALL include more distant S/R levels as valid targets
3. WHEN ATR is low (below 2% of current price), THE Target_Generator SHALL limit targets to S/R levels within 3x ATR distance
4. THE Target_Generator SHALL calculate target distance as a multiple of ATR
5. THE Target_Generator SHALL exclude S/R levels that are less than 1x ATR from entry price

### Requirement 10: Recommendation Persistence and History

**User Story:** As a trader, I want to track how recommendations change over time, so that I can evaluate the system's accuracy and learn from past recommendations.

#### Acceptance Criteria

1. THE Trade_Recommendation_Engine SHALL store each generated recommendation with a timestamp
2. THE Trade_Recommendation_Engine SHALL preserve previous recommendations when generating new ones
3. THE API SHALL provide an endpoint to retrieve recommendation history for a ticker
4. WHEN retrieving history, THE API SHALL return recommendations ordered by timestamp (newest first)
5. THE API SHALL include actual_outcome field indicating whether targets were reached (to be updated post-trade)

### Requirement 11: Frontend Recommendation Display

**User Story:** As a trader, I want to see recommendations clearly displayed in the ticker detail page, so that I can quickly understand the suggested action and targets.

#### Acceptance Criteria

1. THE Ticker_Detail_Page SHALL display the recommendation summary prominently at the top
2. THE Ticker_Detail_Page SHALL show LONG and SHORT setups side-by-side with confidence scores
3. THE Ticker_Detail_Page SHALL display targets in a table with columns: Classification, Price, Distance, R:R, Probability
4. WHEN signal conflicts exist, THE Ticker_Detail_Page SHALL display a warning badge with conflict details
5. THE Ticker_Detail_Page SHALL highlight the recommended direction with visual emphasis (border, background color)
6. THE Ticker_Detail_Page SHALL display risk level with color coding: green (Low), yellow (Medium), red (High)

### Requirement 12: Scanner Integration with Recommendations

**User Story:** As a trader, I want the scanner to show recommended direction and confidence, so that I can quickly filter for high-confidence opportunities.

#### Acceptance Criteria

1. THE Scanner_Page SHALL display a "Recommended Action" column showing the recommended direction and confidence level
2. THE Scanner_Page SHALL allow filtering by recommended action (LONG High, LONG Moderate, SHORT High, SHORT Moderate, NEUTRAL)
3. THE Scanner_Page SHALL allow filtering by minimum confidence score
4. THE Scanner_Page SHALL display the highest-probability target for each setup in the table
5. WHEN a user clicks a setup row, THE Scanner_Page SHALL navigate to the ticker detail page with the recommendation expanded

### Requirement 13: Admin Configuration for Recommendation Thresholds

**User Story:** As an admin, I want to configure confidence score thresholds and probability calculation weights, so that I can tune the recommendation system based on market conditions.

#### Acceptance Criteria

1. THE Admin_Settings_Page SHALL provide inputs for high confidence threshold (default: 70%)
2. THE Admin_Settings_Page SHALL provide inputs for moderate confidence threshold (default: 50%)
3. THE Admin_Settings_Page SHALL provide inputs for signal alignment weight in probability calculation (default: 15%)
4. THE Admin_Settings_Page SHALL provide inputs for S/R strength weight in probability calculation (default: 20%)
5. THE Admin_Settings_Page SHALL provide inputs for distance penalty factor in probability calculation (default: 0.1)
6. WHEN admin saves settings, THE Settings_Service SHALL update the configuration in the Settings model
7. THE Trade_Recommendation_Engine SHALL retrieve current thresholds from Settings before generating recommendations

### Requirement 14: Recommendation Calculation Performance

**User Story:** As a system, I want recommendation generation to complete within acceptable time limits, so that users receive timely updates without delays.

#### Acceptance Criteria

1. WHEN generating recommendations for a single ticker, THE Trade_Recommendation_Engine SHALL complete within 500 milliseconds
2. WHEN the scheduled job generates recommendations for all tickers, THE Trade_Recommendation_Engine SHALL process at least 10 tickers per second
3. THE Trade_Recommendation_Engine SHALL use database query optimization to retrieve all required dimension scores in a single query
4. THE Trade_Recommendation_Engine SHALL cache S/R levels for each ticker to avoid repeated database queries
5. WHEN recommendation generation fails for a ticker, THE Trade_Recommendation_Engine SHALL log the error and continue processing remaining tickers

### Requirement 15: Recommendation Data Model Extension

**User Story:** As a developer, I want the TradeSetup model extended to store recommendation data, so that all recommendation information persists in the database.

#### Acceptance Criteria

1. THE TradeSetup model SHALL include a confidence_score field (Float, 0-100)
2. THE TradeSetup model SHALL include a targets field (JSON array of target objects)
3. THE TradeSetup model SHALL include a conflict_flags field (JSON array of strings)
4. THE TradeSetup model SHALL include a recommended_action field (String: LONG_HIGH, LONG_MODERATE, SHORT_HIGH, SHORT_MODERATE, NEUTRAL)
5. THE TradeSetup model SHALL include a reasoning field (Text)
6. THE TradeSetup model SHALL include a risk_level field (String: Low, Medium, High)
7. THE TradeSetup model SHALL maintain backward compatibility with existing entry_price, stop_loss, target, and rr_ratio fields for the primary target
