Jump to content

Alpha Research: Difference between revisions

From PlusEV Wiki Page
No edit summary
No edit summary
Line 1: Line 1:
= Multi_Timeframe Dynamic Trend Reversion (MTF_DTR) =
= Multi_Timeframe Dynamic Trend Reversion (MTF_DTR) =
----
----
----


Line 6: Line 7:
== What Is This Strategy? ==
== What Is This Strategy? ==


'''Multi_Timeframe Dynamic Trend Reversion (MTF_DTR)''' - A systematic intraday trading strategy that enters when price pulls back to 21-period Moving Average during established trends.
'''Multi-Layer Confluence (MLC)''' is a systematic intraday trading strategy that requires multiple analytical layers to align before taking a trade. Think of it as a '''layered cake''' - each layer must be present for a valid setup.


== Timeframes Used ==
== The Layered Architecture ==
 
<pre>
┌─────────────────────────────────────────────────────────────┐
│                                                            │
│  LAYER 5: ENTRY TECHNIQUE (MA21 Zone)                    │  ← Final trigger
│  Price must be near 21-period MA (±25 points)              │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 4: SETUP QUALITY GRADING                          │  ← Quality gate
│  5-factor scoring: Only A+, A, B grades trade              │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 3: MARKET STATE ANALYSIS                          │  ← Context
│  7 algorithms detect: Railroad, Creeper, Phase, etc.      │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 2: DIRECTION FILTER (MA21 Slope)                  │  ← Hard filter
│  Rising MA = LONG only | Declining MA = SHORT only        │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 1: MULTI-TIMEFRAME ANALYSIS  ◄── THE FOUNDATION    │
│  5 timeframes must show trend alignment                    │
│  Daily → 4H → 1H → 15M → 5M                              │
│                                                            │
└─────────────────────────────────────────────────────────────┘
</pre>
 
<div style="background:#ffffcc; border:1px solid #ffcc00; padding:10px; margin:10px 0;">
'''Key Insight:''' A trade only happens when ALL layers align. MTF Analysis is the foundation - without trend alignment across timeframes, nothing else matters.
</div>
 
== Instrument Details ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Timeframe !! Purpose
! Parameter !! Value
|-
|-
| '''5-Minute''' || Entry timeframe - signals and trade execution
| '''Instrument''' || MCX Crude Oil Futures
|-
|-
| '''15-Minute''' || Confirmation timeframe
| '''Lot Size''' || 100 barrels
|-
|-
| '''1-Hour''' || Primary timeframe for trend analysis
| '''Tick Value''' || 1 point = Rs 100 per lot
|-
|-
| '''4-Hour''' || Higher timeframe context (MTF)
| '''Market Hours''' || 9:00 AM - 11:30 PM IST
|-
|-
| '''Daily''' || Context timeframe for overall direction
| '''Strategy Hours''' || 10:00 AM - 9:59 PM IST (blocks hours 9, 22, 23)
|}
|}


= PART 2: Core Concept =
== Backtest Results ==
 
'''Trade pullbacks to 21-period Moving Average (MA21) during established trends.'''
 
When Market is trending, price naturally pulls back to 21 MA before continuing. We enter at these pullback zones, trading WITH trend direction.
 
== Why It Works ==
 
# '''Mean Reversion''' - Price tends to return to average after moving away
# '''Trend Following''' - We only trade in direction of the trend
# '''Value Entry''' - Entering on pullbacks gives better risk:reward
# '''Institutional Behavior''' - Big players accumulate at MA zones
 
== "MA is a ZONE" Principle ==
 
<blockquote>
'''"MA is a ZONE, not a thin line or exact value"'''
 
Entry is allowed within '''±25 points''' of MA21, not just at exact MA value.
</blockquote>
 
'''Why ±25 points?'''
* Price rarely touches MA exactly
* Gives room for entry without chasing
 
----
 
= PART 3: DIRECTION DETERMINATION (The Foundation) =
 
<div style="background:#ffcccc; border:2px solid #cc0000; padding:10px; margin:10px 0;">
'''THIS IS THE MOST IMPORTANT RULE'''
 
MA21 slope determines ONLY direction we can trade. This is a '''HARD FILTER'''
</div>
 
== MA21 Slope = Trade Direction ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA21 Slope !! Allowed Direction !! Logic
! Metric !! Value
|-
|-
| '''Rising''' (↗) || '''LONG only''' || Trade with uptrend, never short
| '''Period''' || 19 months
|-
|-
| '''Declining''' (↘) || '''SHORT only''' || Trade with downtrend, never long
| '''Total Trades''' || 7,534
|-
|-
| '''Flat''' (→) || Use MTF direction || Let higher timeframes decide
| '''Win Rate''' || 57.6%
|}
 
== How Slope Is Calculated ==
 
{| class="wikitable"
|-
|-
! Slope Value !! Classification !! Threshold
| '''Profit Factor''' || 1.20
|-
|-
| > +0.01% || RISING || Bullish - LONG only
| '''Initial Capital''' || Rs 1.00 Lakhs
|-
|-
| < -0.01% || DECLINING || Bearish - SHORT only
| '''Final Value''' || Rs 26.48 Lakhs
|-
|-
| Between ±0.01% || FLAT || Use MTF consensus
| '''Total Return''' || '''2,548%'''
|}
|}
== Direction Determination Algorithm ==
def determine_direction(ma21_slope, mtf_direction):
    """
    THE PRIMARY FILTER - Direction must align with MA21 slope.
    This filter runs BEFORE any other analysis.
    """
    if ma21_slope > 0.0001:  # 0.01% threshold
        return LONG  # Rising MA = LONG only
    elif ma21_slope < -0.0001:  # -0.01% threshold
        return SHORT  # Declining MA = SHORT only
    else:  # Flat MA
        return mtf_direction  # Use multi-timeframe consensus


----
----


= PART 4: ENTRY CONDITIONS (Gate Checks) =
= PART 2: THE EDGE (Why This Works) =
 
== Overview: Hard vs Soft Filters ==
 
{| class="wikitable"
|-
! Filter Type !! Behavior !! Examples
|-
| '''HARD''' || Must pass ALL or NO TRADE || MA21 slope, hour filter, price in zone, grade
|-
| '''SOFT''' || Affects score but doesn't block || MTF alignment, market state, penalties
|}
 
== HARD FILTERS (Must Pass ALL) ==
 
These filters '''block trades entirely''' if any one fails:
 
=== 1. MA21 Slope Alignment ===
* Direction MUST match MA21 slope
* Rising MA = LONG only
* Declining MA = SHORT only
* '''Fail = NO TRADE'''
 
=== 2. Price in MA Zone ===
* Price must be within '''±25 points''' of MA21
* Too far above/below = not a pullback entry
* '''Fail = NO TRADE'''
 
=== 3. Hour Filter ===
* Block hours: '''9, 22, 23''' (market open/close volatility)
* Allowed: 10:00 AM - 9:00 PM IST
* '''Fail = NO TRADE'''


=== 4. Setup Quality Grade ===
== Core Philosophy ==
* Must achieve grade '''A+, A, or B''' (score ≥ 70)
* Grade C/D/F = not good enough quality
* '''Fail = NO TRADE'''


== SOFT FILTERS (Affect Score) ==
The edge comes from '''requiring multiple independent confirmations''' before trading. Each layer filters out bad trades:
 
These filters affect the quality score but don't block trades:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Filter !! Effect !! Impact
! Layer !! What It Filters Out
|-
| MTF Alignment || 30% weight in grading || Low alignment = lower score
|-
|-
| Creeper Move || -50 penalty || Can still pass if base high
| MTF Analysis || Counter-trend trades, choppy markets
|-
|-
| Railroad Trend || +15 bonus || Quality boost
| Direction Filter || Trades against the dominant trend
|-
|-
| Price-MA Struggle || -30 penalty || Can still pass
| Market State || Dangerous conditions (creeper moves, institutional fights)
|-
|-
| Wrong Trend Phase || -25 penalty || Can still pass
| Quality Grading || Low-probability setups (C, D, F grades)
|-
|-
| Institutional Fight || 0.7x multiplier || Reduces but doesn't block
| Entry Technique || Chasing price far from value (MA21)
|}
|}


== Filter Flow Diagram ==
== The Math ==
 
If each layer has 70% accuracy independently:
* Single layer: 70% edge
* 2 layers: 70% × 70% = 49% of trades pass, but higher quality
* 5 layers: Only the '''best setups''' survive all filters


<pre>
'''Result:''' Fewer trades, but each trade has multiple confluences supporting it.
PRICE BAR RECEIVED
      │
      ▼
┌──────────────────────────────────────────┐
│  HARD FILTER 1: MA21 Slope Alignment    │
│  Is direction aligned with MA21 slope?  │
│  Rising MA + LONG signal = ✓            │
│  Rising MA + SHORT signal = ✗ NO TRADE  │
└──────────────────────────────────────────┘
      │ PASS
      ▼
┌──────────────────────────────────────────┐
│  HARD FILTER 2: Price in MA Zone        │
│  Is price within ±25 pts of MA21?        │
│  YES = ✓  |  NO = ✗ NO TRADE            │
└──────────────────────────────────────────┘
      │ PASS
      ▼
┌──────────────────────────────────────────┐
│  HARD FILTER 3: Hour Filter              │
│  Is current hour allowed?                │
│  Hours 10-21 = ✓  |  9,22,23 = ✗ NO TRADE│
└──────────────────────────────────────────┘
      │ PASS
      ▼
┌──────────────────────────────────────────┐
│  SOFT FILTERS: Calculate Quality Score  │
│  • MTF alignment (30%)                  │
│  • Trend strength (20%)                  │
│  • Key level proximity (20%)            │
│  • Entry quality (15%)                  │
│  • Risk/Reward (15%)                    │
│  ± Penalties and Bonuses                │
└──────────────────────────────────────────┘
      │
      ▼
┌──────────────────────────────────────────┐
│  HARD FILTER 4: Grade Check              │
│  Score ≥ 70 = Grade B+ = ✓ TRADE        │
│  Score < 70 = Grade C- = ✗ NO TRADE    │
└──────────────────────────────────────────┘
      │ PASS
      ▼
    GENERATE SIGNAL
</pre>


----
----


= PART 5: MULTI-TIMEFRAME (MTF) ANALYSIS =
= PART 3: LAYER 1 - MULTI-TIMEFRAME ANALYSIS (The Foundation) =


<div style="background:#ffffcc; border:1px solid #ffcc00; padding:10px; margin:10px 0;">
<div style="background:#e6ffe6; border:1px solid #00cc00; padding:10px; margin:10px 0;">
'''Note:''' MTF is a '''SOFT FILTER''' (30% weight). It contributes to the quality score but does NOT block trades on its own. A trade with poor MTF alignment can still pass if other factors compensate.
'''THIS IS THE FOUNDATION''' - Everything else builds on top of MTF alignment. If timeframes disagree, we don't trade.
</div>
</div>


== Timeframe Hierarchy ==
== The 5 Timeframes ==
 
We analyze '''5 timeframes''' from highest to lowest:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Timeframe !! Purpose !! Weight
! Timeframe !! Role !! Weight
|-
|-
| '''Daily (1D)''' || Context/Bias || Highest weight
| '''Daily (1D)''' || Overall market bias || Highest
|-
|-
| '''4-Hour (4H)''' || Primary Trend || High weight
| '''4-Hour (4H)''' || Primary trend direction || High
|-
|-
| '''1-Hour (1H)''' || Confirmation || Medium weight
| '''1-Hour (1H)''' || Trend confirmation || Medium
|-
|-
| '''15-Min (15M)''' || Entry Timing || Lower weight
| '''15-Minute (15M)''' || Entry timing context || Lower
|-
|-
| '''5-Min (5M)''' || Execution || Lowest weight
| '''5-Minute (5M)''' || Execution timeframe || Lowest
|}
|}


== Per-Timeframe Analysis ==
== What We Analyze Per Timeframe ==
 
For each timeframe, the '''Trend Analysis Core''' calculates:
 
=== 1. Trend Direction ===


{| class="wikitable"
For each of the 5 timeframes, the system calculates:
|-
! MA21 Slope !! Direction
|-
| > +0.01% || UP
|-
| < -0.01% || DOWN
|-
| Between ±0.01% || SIDEWAYS
|}
 
=== 2. MA Trending Status ===


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA Slope Magnitude !! Status
! Analysis !! Description !! Source
|-
|-
| > 0.05% || TRENDING (MA is clearly moving)
| '''MA21 Value''' || 21-period Moving Average || trend_analysis_core.py
|-
|-
| < 0.05% || FLAT (MA is consolidating)
| '''MA21 Slope''' || Rising/Flat/Declining || trend_analysis_core.py
|}
 
=== 3. Price-MA Struggle Detection ===
 
{| class="wikitable"
|-
|-
! Condition !! Detection !! Impact
| '''MA200 Value''' || 200-period Moving Average || trend_analysis_core.py
|-
|-
| Price within 0.5% of MA21 for multiple bars || STRUGGLING || -30 penalty
| '''Price vs MA21''' || Above/Below/At the MA || trend_analysis_core.py
|-
|-
| Price clearly moving away from MA21 || CLEAR TREND || No penalty
| '''Trend Direction''' || UP/DOWN/NEUTRAL || trend_analysis_core.py
|}
|}


== Alignment Score Calculation ==
== MTF Alignment Score ==


<pre>
<pre>
For each timeframe:
For each timeframe:
   - Check if direction matches expected direction
   1. Determine trend direction (UP/DOWN/NEUTRAL)
  - Assign weight based on timeframe importance
   2. Check if aligned with trade direction
 
   3. Apply timeframe weight
Alignment Score = Σ(Weight_i × Aligned_i) / Σ(Weight_i)
   4. Sum weighted alignment scores
 
Example:
   Daily: UP (aligned) × 1.0 weight = 1.0
  4H: UP (aligned) × 0.86 weight = 0.86
   1H: UP (aligned) × 0.72 weight = 0.72
  15M: DOWN (not aligned) × 0.58 weight = 0
   5M: UP (aligned) × 0.44 weight = 0.44


   Score = (1.0 + 0.86 + 0.72 + 0 + 0.44) / (1.0 + 0.86 + 0.72 + 0.58 + 0.44)
Example (LONG trade):
        = 3.02 / 3.60 = 0.84 (84% alignment)
   Daily:  UP (aligned)    × 1.00 weight = 1.00
  4H:    UP (aligned)    × 0.86 weight = 0.86
  1H:    UP (aligned)    × 0.72 weight = 0.72
  15M:    DOWN (not aligned) × 0.58 weight = 0.00
  5M:    UP (aligned)    × 0.44 weight = 0.44
  ─────────────────────────────────────────────
  Total MTF Score: 3.02 / 3.60 = 83.9% aligned
</pre>
</pre>


----
== Why MTF Matters ==
 
= PART 6: MARKET STATE DETECTION =
 
The system detects '''7 market state patterns''' that affect setup quality:
 
== 1. Railroad Trend Detection ==
 
'''What:''' Strong, consistent trend with minimal pullbacks.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Threshold
! Scenario !! MTF Alignment !! Action
|-
|-
| Bar Analysis || 5 most recent bars
| All 5 timeframes aligned || 100% || '''High conviction trade'''
|-
|-
| Strong Bars || 80%+ must close in same direction
| 4 of 5 aligned || ~85% || Trade with normal size
|-
|-
| Bar Body || > 0.3% of price
| 3 of 5 aligned || ~70% || Proceed with caution
|-
| 2 or fewer aligned || <60% || '''Reduced quality score'''
|}
|}
'''Impact:''' '''+15 bonus''' to setup score


----
----


== 2. Creeper Move Detection ==
= PART 4: LAYER 2 - DIRECTION DETERMINATION =


'''What:''' Slow, grinding price action with small bars.
<div style="background:#ffe6e6; border:1px solid #ff0000; padding:10px; margin:10px 0;">
'''HARD FILTER''' - This is non-negotiable. MA21 slope determines the ONLY direction we can trade.
</div>
 
== The Rule ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Threshold
! MA21 Slope !! Allowed Direction !! Logic
|-
| '''Rising''' (↗) || LONG only || Trade with uptrend, never short
|-
|-
| Bar Range || Average < 0.5% of price
| '''Declining''' (↘) || SHORT only || Trade with downtrend, never long
|-
|-
| Analysis Period || Last 7 bars
| '''Flat''' (→) || Use MTF direction || Higher timeframes decide
|}
|}


'''Impact:''' '''-50 penalty''' to setup score (avoid these!)
== Slope Calculation ==
 
<pre>
Slope % = (MA21[current] - MA21[previous]) / MA21[previous] × 100


----
Thresholds:
  > +0.01%  → RISING (LONG only)
  < -0.01%  → DECLINING (SHORT only)
  ±0.01%  → FLAT (use MTF consensus)
</pre>
 
== Algorithm ==


== 3. Two-Day Trend Analysis ==
<source lang="python">
def determine_trade_direction(ma21_slope, mtf_direction):
    """
    HARD FILTER - Direction alignment is mandatory.
    Source: trend_analysis_core.py
    """
    SLOPE_THRESHOLD = 0.0001  # 0.01%


'''What:''' Trend must be visible on Daily for 2+ days.
    if ma21_slope > SLOPE_THRESHOLD:
        return LONG  # Rising MA = LONG only
    elif ma21_slope < -SLOPE_THRESHOLD:
        return SHORT  # Declining MA = SHORT only
    else:
        return mtf_direction  # Flat = defer to MTF
</source>


{| class="wikitable"
== Why 80% of Trades Were SHORT ==
|-
! Requirement !! Description
|-
| Daily Bars || 2+ consecutive bars in same direction
|-
| Purpose || Filters noise, ensures real trend
|}


'''Impact:''' Missing = '''-30 penalty'''
In the backtest period, MA21 was predominantly declining:
* Market was in a sustained downtrend
* Rising MA periods were shorter/fewer
* This is '''expected behavior''' - strategy adapts to market conditions


----
----


== 4. Trend Phase Classification ==
= PART 5: LAYER 3 - MARKET STATE ANALYSIS =
 
== The 7 Market State Algorithms ==
 
The system runs 7 independent algorithms to understand current market context:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Phase !! Bars into Trend !! Action !! Impact
! # !! Algorithm !! What It Detects !! Impact
|-
|-
| '''EARLY''' || 0-15 bars || Avoid || -25 penalty
| 1 || '''Railroad Tracks''' || Strong momentum bars in sequence || +15% bonus
|-
|-
| '''MIDDLE''' || 15-40 bars || '''TARGET''' || No penalty
| 2 || '''Creeper Move''' || Slow grinding trend (dangerous) || '''-50% penalty'''
|-
|-
| '''LATE''' || 40+ bars || Avoid || -25 penalty
| 3 || '''Two-Day Trend''' || Trend visible on Daily for 2+ days || Required for A+
|}
 
----
 
== 5. Institutional Fight Detection ==
 
'''What:''' Big players battling each other.
 
{| class="wikitable"
|-
|-
! Indicator !! Sign
| 4 || '''Phase Analysis''' || Accumulation/Distribution/Markup/Markdown || Phase mismatch = -25%
|-
|-
| Volume || 1.5x+ average
| 5 || '''Institutional Activity''' || Big player accumulation/distribution || Fight = 0.7× multiplier
|-
|-
| Price Action || Narrow range with high volume
| 6 || '''Break of Structure (BOS)''' || Key level breaks || Affects stop placement
|-
|-
| Wicks || Long wicks (rejection)
| 7 || '''Volatility Regime''' || High/Normal/Low volatility || Adjusts expectations
|}
|}


'''Impact:''' '''0.7x multiplier''' on final score
== Penalty System ==
 
----
 
== 6. Break of Structure (BOS) ==
 
'''What:''' Price breaking significant swing high/low.


{| class="wikitable"
{| class="wikitable"
|-
|-
! BOS Type !! Description
! Condition !! Penalty !! Rationale
|-
| Creeper Move Detected || '''-50 points''' || Slow trends often reverse suddenly
|-
| MA Struggle (price fighting MA) || -30 points || Indecision, likely to chop
|-
|-
| SWING_HIGH_BREAK || Price breaks above prior swing high
| No Two-Day Trend || -30 points || Trend not established enough
|-
|-
| SWING_LOW_BREAK || Price breaks below prior swing low
| Phase Mismatch || -25 points || Trading against market phase
|-
|-
| PDH_BREAK || Previous Day High break
| No Key Level Nearby || -50 points || No technical confluence
|-
|-
| PDL_BREAK || Previous Day Low break
| Institutional Fight || '''×0.70 multiplier''' || Big players fighting each other
|}
|}


----
== Bonus System ==
 
== 7. Volatility Classification ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Volatility !! ATR % of Price !! Adjustment
! Condition !! Bonus !! Rationale
|-
|-
| HIGH || > 1.0% || Wider stops needed
| Railroad Tracks || '''+15 points''' || Strong momentum confirmation
|-
|-
| MEDIUM || 0.3% - 1.0% || Normal stops
| At Key Level || +10 points || Technical confluence present
|-
|-
| LOW || < 0.3% || Tighter stops
| Clean Entry Setup || +10 points || Clear technical pattern
|}
|}


----
----


= PART 7: SETUP QUALITY GRADING =
= PART 6: LAYER 4 - SETUP QUALITY GRADING =


== 5-Factor Weighted Scoring ==
== The 5-Factor Scoring System ==


Every potential trade is scored on 5 factors:
Every potential trade is scored on 5 factors:
Line 436: Line 321:
! Factor !! Weight !! What It Measures
! Factor !! Weight !! What It Measures
|-
|-
| '''Timeframe Alignment''' || 30% || How well all timeframes agree
| '''Timeframe Alignment''' || '''30%''' || How well all 5 timeframes agree
|-
|-
| '''Trend Strength''' || 20% || Quality of trend (railroad vs creeper)
| '''Trend Strength''' || '''20%''' || Quality of the trend (Railroad vs Creeper)
|-
|-
| '''Key Level Proximity''' || 20% || Is entry near significant level?
| '''Key Level Proximity''' || '''20%''' || Is entry near significant S/R level?
|-
|-
| '''Entry Quality''' || 15% || Clean entry technique, near MA
| '''Entry Quality''' || '''15%''' || How clean is the entry technique?
|-
|-
| '''Risk/Reward''' || 15% || How favorable is the R:R
| '''Risk:Reward''' || '''15%''' || Is the R:R ratio favorable?
|}
|}


== Score Calculation ==
<div style="background:#e6f3ff; border:1px solid #3399ff; padding:10px; margin:10px 0;">
'''Note:''' Weights sum to 100%. Timeframe Alignment has highest weight (30%) because MTF is the foundation.
</div>


<pre>
== Grade Thresholds ==
Base Score = (TF_score × 0.30) + (Trend_score × 0.20) + (KeyLevel_score × 0.20)
          + (Entry_score × 0.15) + (RR_score × 0.15)
 
Adjusted Score = Base Score + Bonuses - Penalties
 
If Institutional Fight: Final Score = Adjusted Score × 0.7
</pre>
 
== Penalties ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Condition !! Penalty !! Reason
! Grade !! Score Range !! Action !! Position Size
|-
|-
| Creeper Move || '''-50''' || Poor quality price action
| '''A+''' || 90-100 || Trade with full conviction || 2 lots
|-
|-
| MA Struggle || '''-30''' || Price fighting the MA
| '''A''' || 80-89 || Trade with confidence || 1 lot
|-
|-
| No Two-Day Trend || '''-30''' || Trend not established
| '''B''' || 70-79 || Trade normally || 1 lot
|-
|-
| Wrong Trend Phase || '''-25''' || Not in MIDDLE phase
| '''C''' || 60-69 || '''NO TRADE''' || -
|-
|-
| Far from Key Level || '''-50''' || No confluence
| '''D''' || 50-59 || '''NO TRADE''' || -
|-
|-
| Far from MA || '''-40''' || Not a pullback entry
| '''F''' || <50 || '''NO TRADE''' || -
|}
|}


== Bonuses ==
== A+ Grade Special Requirements ==


{| class="wikitable"
To achieve A+ grade, ALL conditions must be true:
|-
* Final score ≥ 90
! Condition !! Bonus !! Reason
* All 5 timeframes aligned with trade direction
|-
* Entry within ±25 points of MA21
| Railroad Trend || '''+15''' || High quality trend
* Two-day trend present on Daily
|-
* No institutional fight detected
| At Key Level || '''+10''' || Confluence present
|-
| Clean Entry || '''+10''' || Clear technical setup
|}


== Grade Thresholds ==
== Score Calculation Example ==


{| class="wikitable"
<pre>
|-
Trade Setup: LONG on 5-min chart
! Grade !! Min Score !! Action
|-
| '''A+''' || 90+ || Trade with full conviction
|-
| '''A''' || 80-89 || Trade with confidence
|-
| '''B''' || 70-79 || Trade normally
|-
| '''C''' || 60-69 || '''NO TRADE'''
|-
| '''D''' || 50-59 || '''NO TRADE'''
|-
| '''F''' || <50 || '''NO TRADE'''
|}


== A+ Special Requirements ==
Factor Scores (0-100 each):
  Timeframe Alignment: 85  × 0.30 = 25.5
  Trend Strength:      90  × 0.20 = 18.0
  Key Level Proximity: 70  × 0.20 = 14.0
  Entry Quality:      80  × 0.15 = 12.0
  Risk:Reward:        75  × 0.15 = 11.25
                              ──────────
  Base Score:                    80.75


To achieve A+ grade, ALL must be true:
Penalties Applied:
* Score ≥ 90
  - No Railroad Tracks: 0
* All timeframes aligned
  - No Creeper: 0
* Entry near MA21 (within ±25 pts)
  - Has Two-Day: 0
* Two-day trend present
                              ──────────
* No institutional fight
  Final Score: 80.75 → Grade: A
</pre>


----
----


= PART 8: ENTRY TECHNIQUES =
= PART 7: LAYER 5 - ENTRY TECHNIQUE =


== Available Techniques ==
== The MA21 Zone Principle ==


=== Universal (Both Directions) ===
<blockquote>
'''"The MA is a ZONE, not a thin line"'''


{| class="wikitable"
Entry is allowed within '''±25 points''' of MA21, not just at the exact MA value.
|-
</blockquote>
! Technique !! Description
 
|-
== Why ±25 Points? ==
| '''NEAR_MA''' || Entry when price is near MA21 zone (±25 pts)
 
|}
* Price rarely touches MA exactly
* Allows for normal market noise
* Captures the "value zone" around the average
* Based on typical Crude Oil volatility


=== Long-Specific ===
== Available Entry Techniques ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Technique !! Description
! Technique !! Direction !! Description
|-
|-
| GREEN_BAR_AFTER_PULLBACK || Green candle after pullback
| '''NEAR_MA''' || Both || Price within ±25 pts of MA21 (most common)
|-
|-
| MA_BOUNCE_LONG || Bounce off MA21 in uptrend
| MA_BOUNCE_LONG || Long || Price touches MA21 and bounces up
|-
|-
| BOS_ENTRY_LONG || Entry after break of structure (upside)
| MA_BOUNCE_SHORT || Short || Price touches MA21 and rejects down
|-
|-
| BREAKOUT_PULLBACK_LONG || Pullback after breakout
| GREEN_BAR_AFTER_PULLBACK || Long || Bullish candle after pullback to MA
|-
|-
| DISCOUNT_ZONE_LONG || Buy in lower zone of range
| RED_BAR_AFTER_RALLY || Short || Bearish candle after rally to MA
|}
 
=== Short-Specific ===
 
{| class="wikitable"
|-
|-
! Technique !! Description
| BOS_ENTRY_LONG || Long || Break of structure to upside
|-
|-
| RED_BAR_AFTER_RALLY || Red candle after rally
| BOS_ENTRY_SHORT || Short || Break of structure to downside
|-
| MA_BOUNCE_SHORT || Rejection from MA21 in downtrend
|-
| BOS_ENTRY_SHORT || Entry after break of structure (downside)
|-
| BREAKOUT_PULLBACK_SHORT || Pullback after breakdown
|-
| PREMIUM_ZONE_SHORT || Sell in upper zone of range
|}
|}


== Selection Logic ==
== Entry Selection Logic ==


<source lang="python">
<source lang="python">
def select_entry_technique(price, ma21, direction, has_bos, has_pullback):
def select_entry_technique(price, ma21, direction, market_state):
     # Most common: price near MA zone
    """
     if abs(price - ma21) <= 25:
    Select best entry technique based on conditions.
    Source: signal_generation_trade_management.py
    """
    ma_distance = abs(price - ma21)
 
     # Most common: price in MA zone
     if ma_distance <= 25: # ±25 points
         return NEAR_MA
         return NEAR_MA


     # Break of structure detected
     # Break of structure detected
     elif has_bos:
     if market_state.has_bos:
         if direction == LONG:
         return BOS_ENTRY_LONG if direction == LONG else BOS_ENTRY_SHORT
            return BOS_ENTRY_LONG
        else:
            return BOS_ENTRY_SHORT


     # Pullback pattern detected
     # Pullback/Rally pattern
     elif has_pullback:
     if market_state.has_pullback:
         if direction == LONG:
         return GREEN_BAR_AFTER_PULLBACK if direction == LONG else RED_BAR_AFTER_RALLY
            return GREEN_BAR_AFTER_PULLBACK
        else:
            return RED_BAR_AFTER_RALLY


     # Default: MA bounce
     return NEAR_MA  # Default
    else:
        if direction == LONG:
            return MA_BOUNCE_LONG
        else:
            return MA_BOUNCE_SHORT
</source>
</source>


----
----


= PART 9: PROBABILITY ZONES =
= PART 8: STOP LOSS CALCULATION =


== Halves & Thirds Analysis ==
== Stop Loss Methods (Priority Order) ==
 
Based on price position within recent swing range:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Zone !! Position !! Continuation Probability
! Priority !! Method !! Description
|-
| '''Top Third''' || 67-100% || 80% chance of new high
|-
|-
| '''Top Half''' || 50-67% || 65% continuation
| 1 || '''BOS-Based Stop''' || Below/above break of structure level
|-
|-
| '''Bottom Half''' || 33-50% || 35% continuation
| 2 || '''Swing-Based Stop''' || Below recent swing low (LONG) or above swing high (SHORT)
|-
|-
| '''Bottom Third''' || 0-33% || 15% (85% likely lower)
| 3 || '''Default Stop''' || Fixed 40 points from entry
|}
|}


== Zone-Based Trading Rules ==
== Minimum Stop Distance ==


=== Trending Market ===
<div style="background:#ffffcc; border:1px solid #ffcc00; padding:10px; margin:10px 0;">
'''MINIMUM: 40 points''' - Stops closer than 40 points are automatically widened to 40.
</div>


{| class="wikitable"
This prevents:
|-
* Getting stopped out by normal noise
! Zone !! LONG !! SHORT
* Excessive trading costs from tight stops
|-
* Whipsaws in volatile Crude Oil market
| Top Third || Allowed (after pullback) || Blocked
|-
| Bottom Third || Blocked || Allowed (after rally)
|}


=== Sideways Market ===
== Stop Calculation Algorithm ==


{| class="wikitable"
<source lang="python">
|-
def calculate_stop_loss(entry_price, direction, market_state):
! Zone !! LONG !! SHORT
    """
|-
    Calculate stop loss with minimum enforcement.
| Top Third || Blocked (overextended) || Allowed
    Source: signal_generation_trade_management.py
|-
    """
| Bottom Third || Allowed || Blocked
    MIN_STOP_DISTANCE = 40.0  # points
|}


== Three-Finger Spread ==
    # Try BOS-based stop first
    if market_state.bos_level:
        stop = market_state.bos_level - 5  # 5pt buffer


'''What:''' Large separation between Price, MA21, and MA200.
    # Try swing-based stop
    elif market_state.swing_low and direction == LONG:
        stop = market_state.swing_low - 5


<pre>
    # Default stop
Detection:
    else:
- Distance(Price to MA21) > 2% of price
        if direction == LONG:
- AND Distance(MA21 to MA200) > 2% of price
            stop = entry_price - MIN_STOP_DISTANCE
</pre>
        else:
            stop = entry_price + MIN_STOP_DISTANCE


'''Impact:''' Expect profit-taking soon (bearish for longs, bullish for shorts)
    # ENFORCE MINIMUM
    actual_distance = abs(entry_price - stop)
    if actual_distance < MIN_STOP_DISTANCE:
        if direction == LONG:
            stop = entry_price - MIN_STOP_DISTANCE
        else:
            stop = entry_price + MIN_STOP_DISTANCE


== Crash Bar Detection ==
    return stop
</source>


'''What:''' Abnormally large bar indicating structural break.
----


{| class="wikitable"
= PART 9: TARGET CALCULATION =
|-
! Characteristic !! Threshold
|-
| Bar Size || 2x average bar size
|-
| Close Position || Within 30% of extreme
|}


'''Special Rule:''' Crash bar in sideways market + top zone → Override to SHORT
== The 50% Rule ==


----
<div style="background:#e6f3ff; border:1px solid #3399ff; padding:10px; margin:10px 0;">
'''Target = 50% of distance to MA21'''


= PART 10: EXIT MANAGEMENT =
For mean reversion trades, we target halfway back to the moving average.
</div>


== Overview ==
== Why 50%? ==


{| class="wikitable"
* Conservative target ensures higher hit rate
|-
* Based on "divide the move in half" principle
! Exit Type !! Trigger !! Typical Result
* Captures partial reversion without being greedy
|-
* Works well with trailing stop to capture more
| '''Stop Loss''' || Price hits stop (static or trailing) || Loss or locked profit
|-
| '''Take Profit''' || Price hits target || Winner (always)
|-
| '''Timeout''' || 8 hours elapsed || Exit at market
|}


== Initial Stop Loss: 40 Points ==
== Minimum Target Rule ==


{| class="wikitable"
<pre>
|-
Minimum Target = Risk × 1.5
! Method !! Description
|-
| '''Default''' || 40 points from entry
|-
| '''Structure-Based''' || Below swing low (LONG) / Above swing high (SHORT)
|-
| '''MA-Based''' || MA21 value ± 25 points buffer
|-
| '''Minimum''' || Always at least 40 points
|}


=== Stop by Entry Technique ===
Example:
  Entry: 5700
  Stop: 5660 (40 points risk)


{| class="wikitable"
  50% to MA might give: 30 points
|-
  But minimum is: 40 × 1.5 = 60 points
! Technique !! Stop Placement
|-
| NEAR_MA || 40 pts default
|-
| BOS_ENTRY || Below/above structure (10-bar lookback + 5pt buffer)
|-
| MA_BOUNCE || Below/above MA21 zone
|-
| BREAKOUT_PULLBACK || Below/above pullback low/high
|}


----
  Final Target: 5760 (60 points)
</pre>


== DYNAMIC STOP MANAGEMENT ==
== Target Calculation ==


<div style="background:#ccffcc; border:2px solid #00cc00; padding:10px; margin:10px 0;">
<source lang="python">
'''IMPORTANT:''' Stop loss is NOT static! It moves dynamically to lock in profits.
def calculate_target(entry_price, stop_price, ma21, direction):
    """
    PDF-based target: 50% of distance to MA, with minimum.
    Source: signal_generation_trade_management.py
    """
    risk_distance = abs(entry_price - stop_price)
    min_target = risk_distance * 1.5  # Minimum 1.5:1 R:R


This explains why '''72.3% of exits are "stop"''' but many are '''profitable trades'''!
    # Calculate 50% move toward MA
</div>
    distance_to_ma = abs(entry_price - ma21)
    target_distance = distance_to_ma * 0.5


=== Phase 1: Breakeven Stop ===
    # Enforce minimum
    target_distance = max(target_distance, min_target)


'''Trigger:''' When trade reaches '''25 points profit'''
    if direction == LONG:
        return entry_price + target_distance
    else:
        return entry_price - target_distance
</source>


{| class="wikitable"
----
|-
! Parameter !! Value
|-
| Activation || 25 points in profit
|-
| New Stop || Entry price + 2 pts buffer
|-
| Purpose || Eliminate loss, lock small profit
|}


'''Example (LONG at 5500):'''
= PART 10: DYNAMIC STOP MANAGEMENT =


<pre>
== Two-Phase Protection ==
Entry: 5500
Original Stop: 5460 (40 pts risk)


Price reaches 5525 (+25 pts profit):
After entry, stops are managed dynamically in two phases:
→ Stop moves from 5460 to 5502 (entry + 2 buffer)
→ Worst case now = +2 pts profit (NOT -40 loss!)
</pre>
 
=== Phase 2: Trailing Stop (ATR-Based) ===
 
'''Trigger:''' When trade reaches '''20 points profit'''


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Phase !! Trigger !! Action
|-
|-
| Method || ATR_MULTIPLE (adapts to volatility)
| '''Phase 1: Breakeven''' || +25 points profit || Move stop to entry + 2 points
|-
|-
| ATR Period || 14 bars
| '''Phase 2: Trailing''' || +20 points profit || Trail stop using ATR × 2
|-
| ATR Multiplier || 2.0
|-
| Trailing Distance || ATR × 2 (dynamic)
|-
| Minimum Distance || 15 points
|-
| Activation || 20 points in profit
|}
|}


'''How It Works:'''
== Phase 1: Breakeven Stop ==


<pre>
<pre>
Current ATR = 12 points
Configuration:
Trailing Distance = 12 × 2 = 24 pts
  breakeven_activation = 25 points
 
  breakeven_buffer = 2 points
Price at 5540 (LONG from 5500):
→ New Stop = 5540 - 24 = 5516
 
Price at 5560:
→ New Stop = 5560 - 24 = 5536 (moved UP)


Price reverses to 5536:
Example (LONG from 5700):
EXIT at 5536 = +36 pts PROFIT
  Price reaches 5725 (+25 pts profit)
Shows as "stop" exit but is profitable!
  Stop moves from 5660 to 5702 (entry + 2)
 
  Trade is now "risk-free"
Key Rule: Stop can only move in profitable direction, NEVER back.
</pre>
</pre>


=== Complete Stop Movement Example ===
== Phase 2: Trailing Stop ==


<pre>
<pre>
LONG Entry: 5500
Configuration:
Original Stop: 5460 (-40 pts risk)
  trailing_stop_activation = 20 points
Target: 5560 (+60 pts)
  trailing_stop_method = ATR_MULTIPLE
  atr_period = 14 bars
  atr_multiplier = 2.0
  minimum_trail_distance = 15 points


Trade Progress:
Example (LONG from 5700, ATR = 12):
─────────────────────────────────────────────────
   Trailing Distance = 12 × 2 = 24 points
Price    Profit   Action                Stop Now
─────────────────────────────────────────────────
5500    0        Entry                5460
5510    +10      Waiting...            5460
5520    +20      Trailing activates    5490 (5520-30)
5525    +25      Breakeven activates  5502 (max of 5490, 5502)
5540    +40      Trail continues      5510
5560    +60      TARGET HIT!          ---


OR if price reverses:
  Price at 5740:
5540    +40      Trail at 5510        5510
  → Trail stop = 5740 - 24 = 5716
5520    +20      Stop unchanged        5510
5510    +10      STOP HIT              EXIT +10 profit
─────────────────────────────────────────────────
</pre>


----
  Price at 5760:
  → Trail stop = 5760 - 24 = 5736 (moved UP)


== Take Profit: 60 Points ==
  Price drops to 5736:
 
  → STOPPED OUT at 5736 (profit locked)
{| class="wikitable"
</pre>
|-
! Calculation !! Value
|-
| '''Primary''' || 50% of distance to MA21
|-
| '''Minimum''' || Risk × 1.5 = 40 × 1.5 = 60 pts
|-
| '''Final''' || MAX(50% to MA, 60 pts) = Usually 60 pts
|}
 
'''Risk:Reward = 1.5:1'''
* Risk 40 pts to gain 60 pts
* Risk Rs 4,000 to gain Rs 6,000
 
----
 
== Timeout: 8 Hours ==
 
* If trade doesn't hit stop or target within 8 hours
* Exit at current market price
* Prevents overnight holding
* Used in 5% of trades (374 out of 7,534)
 
----


== Slippage Modeling ==
== Why Both Phases? ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Slippage
! Phase !! Purpose
|-
| Entry (base) || +1.0 points
|-
|-
| Stop Loss exit || +2.0 points (worse fill)
| Breakeven || Eliminate risk quickly once trade moves in favor
|-
|-
| Take Profit exit || +0.5 points (limit order)
| Trailing || Let winners run while protecting accumulated profit
|-
| Market Impact || Up to 2.0 points (capped)
|}
|}


----
----


= PART 11: RISK MANAGEMENT =
= PART 11: SLIPPAGE & COSTS =


== Position Sizing ==
== Realistic Slippage Model ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Event !! Slippage !! Rationale
|-
|-
| Position Size || 1 lot (100 barrels)
| '''Entry''' || +1.0 point || Normal market fill
|-
|-
| Risk per Trade || 40 pts × Rs 100 = Rs 4,000
| '''Stop Loss Exit''' || +2.0 points || Stops slip more in fast moves
|-
|-
| Reward per Trade || 60 pts × Rs 100 = Rs 6,000
| '''Target Exit''' || +0.5 points || Limit orders have minimal slippage
|-
| Max Concurrent || 1 trade at a time
|}
|}


Line 887: Line 660:
! Cost Type !! Value
! Cost Type !! Value
|-
|-
| Brokerage || Rs 20 per lot per leg (Dhan)
| Commission || Rs 20 per lot per side
|-
|-
| CTT || 0.01% on sell side
| STT || 0.01% on sell side
|-
|-
| Total Round-trip || ~Rs 95 per trade
| Exchange Fees || ~Rs 2 per lot
|-
|-
| Total Costs (7,534 trades) || Rs 5.93 Lakhs
| Stamp Duty || State-dependent
|}
|}


== Risk Metrics ==
== Why Model Slippage? ==
 
* Backtest results must reflect real trading
* Prevents over-optimistic performance estimates
* Stop loss slippage is higher because stops often trigger during fast moves
* Total costs ~Rs 79 per round-trip lot
 
----
 
= PART 12: EXIT RULES =
 
== Three Exit Conditions ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Exit Type !! Condition !! % of Exits
|-
| Risk per Trade || Rs 4,000 (4% of initial capital)
|-
|-
| Risk:Reward || 1:1.5 (40:60)
| '''Stop Loss''' || Price hits stop (original or trailing) || 72.3%
|-
|-
| Required Win Rate || 40% to break even
| '''Target''' || Price hits take profit level || 22.8%
|-
|-
| Actual Win Rate || 57.6% (profitable)
| '''Timeout''' || End of day (no overnight holds) || 5.0%
|}
|}
== Why 72% Stop Exits but 57% Win Rate? ==
This seems contradictory but makes sense:
* '''Trailing stops lock in profits''' - many "stop exits" are actually winning trades
* Breakeven stops trigger at +25 pts, trailing at +20 pts
* A trade can be stopped out at +30 pts profit (counted as stop exit but is a WIN)
== End-of-Day Exit ==
<pre>
All positions closed before market close:
  - Market closes at 11:30 PM IST
  - 15-minute buffer before close
  - Prevents overnight gap risk
</pre>


----
----


= PART 12: SIGNAL GENERATION FLOW =
= PART 13: PUTTING IT ALL TOGETHER =


== Complete Pipeline ==
== Trade Flow ==


<pre>
<pre>
┌─────────────────────────────────────────────────────────────────────────────┐
┌─────────────────────────────────────────────────────────────────┐
│                        SIGNAL GENERATION PIPELINE                        │
│  STEP 1: Load data for all 5 timeframes                       
├─────────────────────────────────────────────────────────────────────────────┤
│  Daily, 4H, 1H, 15M, 5M OHLCV data                           
│                                                                            │
└─────────────────────────────────────────────────────────────────┘
│  STEP 1: DATA COLLECTION                                                   
                              ↓
│  ┌─────────────────────────────────────────────────────────────────────┐ 
┌─────────────────────────────────────────────────────────────────┐
│  │ • Load OHLCV data for all 5 timeframes                              │ 
│  STEP 2: LAYER 1 - MTF Analysis (Foundation)                   
│  │ • Calculate MA21 and MA200 for each timeframe                       │ 
│  Calculate MA21, MA200, trend direction for each timeframe    
│  │ • Calculate ATR for volatility measurement                          │ 
│  Compute MTF alignment score                                   
│  └─────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
│                                                                          │
                             
│  STEP 2: DIRECTION DETERMINATION (HARD FILTER #1)                         
┌─────────────────────────────────────────────────────────────────┐
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  STEP 3: LAYER 2 - Direction Filter                           
│  │ • Calculate MA21 slope on 5-min chart                              │ 
│  Check MA21 slope on entry timeframe (5M)                     
│  │ • Rising slope → LONG only allowed                                  │  │
│  Rising → LONG only | Declining → SHORT only | Flat → use MTF  │
│  │ • Declining slope → SHORT only allowed                              │  │
└─────────────────────────────────────────────────────────────────┘
│  │ • Flat slope Use MTF direction                                    │   │
                             
│  └─────────────────────────────────────────────────────────────────────┘  │
┌─────────────────────────────────────────────────────────────────┐
│                                                                          │
│  STEP 4: LAYER 3 - Market State Analysis                       
│  STEP 3: HARD FILTER CHECKS                                                │
│  Run 7 algorithms: Railroad, Creeper, Phase, BOS, etc.         
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  Calculate penalties and bonuses                               │
│  │ □ Is price within ±25 pts of MA21?          → NO = SKIP            │  │
└─────────────────────────────────────────────────────────────────┘
│  │ □ Is current hour allowed? (not 9,22,23)    → NO = SKIP            │  │
                              ↓
│  └─────────────────────────────────────────────────────────────────────┘  │
┌─────────────────────────────────────────────────────────────────┐
│                              ↓                                              │
│  STEP 5: LAYER 4 - Setup Quality Grading                       
│  STEP 4: MULTI-TIMEFRAME ANALYSIS                                         
│  Score 5 factors, apply penalties/bonuses                      
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  Assign grade: A+/A/B → TRADE | C/D/F → NO TRADE             
│  │ • Analyze trend direction in 5 timeframes                          │ 
└─────────────────────────────────────────────────────────────────┘
│  │ • Calculate weighted alignment score                               │ 
                             
│  │ • Output: 0.0 to 1.0 alignment score (30% of grade)                │  │
┌─────────────────────────────────────────────────────────────────┐
│  └─────────────────────────────────────────────────────────────────────┘  │
│  STEP 6: LAYER 5 - Entry Check                                 
│                              ↓                                              │
│  Is price within ±25 points of MA21?                           
│  STEP 5: MARKET STATE ANALYSIS                                            │
│  Select entry technique                                       
│  ┌─────────────────────────────────────────────────────────────────────┐  │
└─────────────────────────────────────────────────────────────────┘
│  │ • Railroad Trend Detection (+15 bonus)                              │  │
                              ↓
│  │ • Creeper Move Detection (-50 penalty)                              │ 
┌─────────────────────────────────────────────────────────────────┐
│  │ • Two-Day Trend Check (-30 if missing)                              │  │
│  STEP 7: Calculate Stop Loss                                   
│  │ • Trend Phase Classification (-25 if wrong)                        │  │
│  BOS-based → Swing-based → Default (40 pts minimum)            
│  │ • Institutional Fight Detection (0.7x multiplier)                  │  │
└─────────────────────────────────────────────────────────────────┘
│  └─────────────────────────────────────────────────────────────────────┘  │
                              ↓
│                              ↓                                              │
┌─────────────────────────────────────────────────────────────────┐
│  STEP 6: SETUP QUALITY GRADING                                            │
│  STEP 8: Calculate Target                                     
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  50% of distance to MA (minimum 1.5× risk)                     
│  │ • Calculate 5-factor weighted score                                  │  │
└─────────────────────────────────────────────────────────────────┘
│  │ • Apply penalties and bonuses                                       │ 
                              ↓
│  │ • Assign grade: A+, A, B, C, D, F                                   │  │
┌─────────────────────────────────────────────────────────────────┐
│  │ • Grade < B (score < 70) SKIP                                    │ 
│  STEP 9: Execute Trade                                         
│  └─────────────────────────────────────────────────────────────────────┘  │
│  Apply entry slippage (+1 pt), create trade record             
│                                                                          │
└─────────────────────────────────────────────────────────────────┘
│  STEP 7: SIGNAL OUTPUT                                                   
                              
│  ┌─────────────────────────────────────────────────────────────────────┐ 
┌─────────────────────────────────────────────────────────────────┐
│  │ • Direction: LONG or SHORT                                          │  │
│  STEP 10: Manage Trade                                         
│  │ • Entry Price: Current close                                        │ 
│  Monitor: Breakeven at +25 pts → Trail at +20 pts             
│  │ • Stop Loss: 40 points (or structure-based)                         │ 
Exit: Stop hit | Target hit | Timeout                         
│  │ • Take Profit: 60 points                                            │ 
└─────────────────────────────────────────────────────────────────┘
│  │ • Entry Technique: NEAR_MA, BOS_ENTRY, etc.                         │ 
│  │ • Grade: A+, A, or B                                                │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 8: TRADE EXECUTION                                                 
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ • Apply entry slippage (1 pt)                                       │ 
│  │ • Monitor for stop/target/timeout                                  │  │
│  │ • Update trailing stop when in profit                               │  │
│  │ • Execute exit with appropriate slippage                            │ 
│  └─────────────────────────────────────────────────────────────────────┘ 
                                                                           
└─────────────────────────────────────────────────────────────────────────────┘
</pre>
</pre>


----
----


= PART 13: BACKTEST RESULTS =
= PART 14: HARD vs SOFT FILTERS =


== Summary Statistics ==
== Understanding the Difference ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Filter Type !! Behavior !! Examples
|-
| '''Period''' || 19 months
|-
| '''Initial Capital''' || Rs 1,00,000
|-
| '''Final Value''' || Rs 26,48,101
|-
|-
| '''Total Profit''' || Rs 25,48,101
| '''HARD''' || Blocks trade completely || Direction filter, Hour filter, Grade C/D/F
|-
|-
| '''Total Return''' || '''2,548%'''
| '''SOFT''' || Affects quality score || MTF alignment, Market state penalties
|-
| '''Peak Value''' || Rs 28,35,039
|-
| '''Max Drawdown''' || -78.6%
|-
| '''Total Costs''' || Rs 5,93,160
|}
|}


== Trade Statistics ==
== Complete Filter List ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Filter !! Type !! Effect
|-
|-
| Total Trades || 7,534
| MA21 Direction || '''HARD''' || Wrong direction = NO TRADE
|-
|-
| Winners || 4,338 (57.6%)
| Hour Filter || '''HARD''' || Hours 9, 22, 23 = NO TRADE
|-
|-
| Losers || 3,196 (42.4%)
| Grade < B || '''HARD''' || C/D/F grades = NO TRADE
|-
|-
| Profit Factor || 1.20
| MTF Alignment || SOFT || Low alignment = reduced score (30% weight)
|-
|-
| Average Win || Rs 3,464
| Creeper Move || SOFT || -50 points penalty
|-
|-
| Average Loss || Rs 3,904
| No Two-Day Trend || SOFT || -30 points penalty
|-
|-
| Largest Win || Rs 26,799
| Institutional Fight || SOFT || 0.7× score multiplier
|-
|-
| Largest Loss || Rs 13,217
| Far from MA21 || SOFT || -40 points penalty
|-
| Avg Holding Time || 2.4 hours
|}
|}


== Exit Reason Breakdown ==
----
 
= APPENDIX A: CONFIGURATION VALUES =
 
== Entry Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Count !! % !! Notes
! Parameter !! Value !! Source File
|-
|-
| '''Stop''' || 5,444 || 72.3% || Includes trailing stop profits!
| entry_timeframe || 5-Minute || main.py:165
|-
|-
| '''Target''' || 1,716 || 22.8% || 100% winners
| ma_buffer_points || 25 points || signal_generation_trade_management.py:68
|-
|-
| '''Timeout''' || 374 || 5.0% || 8-hour limit
| blocked_hours || [9, 22, 23] || signal_generation_trade_management.py:137
|}
|}


<div style="background:#e6ffe6; border:1px solid #00cc00; padding:10px; margin:10px 0;">
== Stop/Target Configuration ==
'''Why are 72% stops but 57% winners?'''
 
Because of the '''trailing stop'''! Many "stop" exits are actually:
* Breakeven exits (+2 pts)
* Trailing stop exits (+10 to +50 pts)
 
The trailing stop LOCKS IN profits, then exits when price reverses.
</div>
 
== Direction Distribution ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Direction !! Count !! %
! Parameter !! Value !! Source File
|-
|-
| '''SHORT''' || 6,024 || 80%
| min_stop_distance || 40 points || signal_generation_trade_management.py:59
|-
|-
| '''LONG''' || 1,510 || 20%
| default_risk_reward || 1.5 || signal_generation_trade_management.py:62
|-
| bos_stop_buffer_points || 5 points || signal_generation_trade_management.py:81
|}
|}


'''Why 80% SHORT?''' The market had a predominantly declining MA21 during the backtest period. The system correctly adapted to bearish conditions.
== Dynamic Stop Configuration ==
 
== Setup Quality Distribution ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Grade !! Count !! %
! Parameter !! Value !! Source File
|-
| enable_trailing_stop || True || trade_execution_engine.py:57
|-
|-
| A+ || 3,457 || 45.9%
| trailing_stop_method || ATR_MULTIPLE || trade_execution_engine.py:58
|-
|-
| A || 551 || 7.3%
| atr_period || 14 bars || trade_execution_engine.py:61
|-
|-
| C || 3,526 || 46.8% (analyzed but NOT traded)
| atr_multiplier || 2.0 || trade_execution_engine.py:65
|}
 
----
 
= PART 14: KEY STRATEGY PRINCIPLES =
 
# '''MA21 Slope = Direction''' - The primary hard filter. Rising MA = LONG only, Declining MA = SHORT only.
 
# '''MA is a ZONE''' - Enter within ±25 pts of MA21, not just at exact value.
 
# '''Quality over Quantity''' - Only trade A+, A, B grades (score ≥ 70).
 
# '''Avoid Creeper Moves''' - -50 penalty ensures we skip low-quality price action.
 
# '''Trade the MIDDLE''' - Focus on middle phase of trends (bars 15-40).
 
# '''Dynamic Stop Management''' - Breakeven at 25 pts, trailing with ATR×2.
 
# '''1.5:1 Risk:Reward''' - Risk 40 pts to gain 60 pts.
 
# '''Time Discipline''' - Maximum 8-hour holding, no overnight.
 
# '''MTF as Soft Filter''' - Contributes to score (30%) but doesn't block alone.
 
# '''Trailing Explains Stops''' - 72% "stop" exits include profitable trailing stops.
 
----
 
= APPENDIX A: CONFIGURATION VALUES =
 
== Stop/Target Configuration ==
 
{| class="wikitable"
|-
|-
! Parameter !! Value !! Source
| trailing_stop_activation || 20 points || trade_execution_engine.py:60
|-
|-
| min_stop_distance || 40 points || signal_generation_trade_management.py
| enable_breakeven_stop || True || trade_execution_engine.py:67
|-
|-
| default_stop_distance || 40 points || signal_generation_trade_management.py
| breakeven_activation || 25 points || trade_execution_engine.py:70
|-
|-
| default_risk_reward || 1.5 || signal_generation_trade_management.py
| breakeven_buffer || 2 points || trade_execution_engine.py:71
|-
|-
| min_target || risk × 1.5 = 60 pts || signal_generation_trade_management.py
| minimum_trail_distance || 15 points || trade_execution_engine.py:370
|}
|}


== Trailing Stop Configuration ==
== Slippage Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value !! Source
! Parameter !! Value !! Source File
|-
| enable_trailing_stop || True || trade_execution_engine.py
|-
| trailing_stop_method || ATR_MULTIPLE || trade_execution_engine.py
|-
| atr_period || 14 bars || trade_execution_engine.py
|-
| atr_multiplier || 2.0 || trade_execution_engine.py
|-
| trailing_stop_activation || 20 points || trade_execution_engine.py
|-
|-
| enable_breakeven_stop || True || trade_execution_engine.py
| base_slippage_points || 1.0 point || trade_execution_engine.py:38
|-
|-
| breakeven_activation || 25 points || trade_execution_engine.py
| stop_loss_slippage || 2.0 points || trade_execution_engine.py:50
|-
|-
| breakeven_buffer || 2 points || trade_execution_engine.py
| take_profit_slippage || 0.5 points || trade_execution_engine.py:51
|}
|}


Line 1,159: Line 883:
{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value !! Source
! Parameter !! Value !! Source File
|-
|-
| timeframe_alignment_weight || 30% || setup_quality_detection.py
| timeframe_alignment_weight || 30% || setup_quality_detection.py:44
|-
|-
| trend_strength_weight || 20% || setup_quality_detection.py
| trend_strength_weight || 20% || setup_quality_detection.py:45
|-
|-
| key_level_proximity_weight || 20% || setup_quality_detection.py
| key_level_proximity_weight || 20% || setup_quality_detection.py:47
|-
|-
| entry_technique_weight || 15% || setup_quality_detection.py
| entry_technique_weight || 15% || setup_quality_detection.py:46
|-
|-
| risk_reward_weight || 15% || setup_quality_detection.py
| risk_reward_weight || 15% || setup_quality_detection.py:48
|-
| a_plus_min_score || 90 || setup_quality_detection.py:51
|-
| a_min_score || 80 || setup_quality_detection.py:52
|-
| b_min_score || 70 || setup_quality_detection.py:53
|}
|}


Line 1,180: Line 910:
! File !! Purpose
! File !! Purpose
|-
|-
| <code>trend_analysis_core.py</code> || MA slope calculation, trend direction, price-MA struggle
| <code>main.py</code> || Entry point, timeframe configuration
|-
| <code>trend_analysis_core.py</code> || MA calculation, slope detection, trend direction
|-
|-
| <code>multi_timeframe_analysis.py</code> || MTF alignment scoring across 5 timeframes
| <code>multi_timeframe_analysis.py</code> || MTF alignment scoring across 5 timeframes
Line 1,192: Line 924:
| <code>signal_generation_trade_management.py</code> || Entry/Exit logic, stop/target calculation
| <code>signal_generation_trade_management.py</code> || Entry/Exit logic, stop/target calculation
|-
|-
| <code>trade_execution_engine.py</code> || Breakeven, Trailing stop, Slippage, Timeout
| <code>trade_execution_engine.py</code> || Breakeven, Trailing stop, Slippage modeling
|-
|-
| <code>data_manager.py</code> || OHLCV data loading and management
| <code>data_manager.py</code> || OHLCV data loading and management
Line 1,199: Line 931:
----
----


''Document generated from code analysis - January 2026''
''Document generated from source code analysis - January 2026''


''All rules extracted directly from source code implementation''
''Strategy: Multi-Layer Confluence (MLC) v1.0''


[[Category:Trading Strategies]]
[[Category:Trading Strategies]]
[[Category:Systematic Trading]]
[[Category:MCX Crude Oil]]
[[Category:MCX Crude Oil]]
[[Category:MA21 Mean Reversion]]
[[Category:Backtesting]]

Revision as of 16:53, 5 January 2026

Multi_Timeframe Dynamic Trend Reversion (MTF_DTR)



PART 1: STRATEGY OVERVIEW

What Is This Strategy?

Multi-Layer Confluence (MLC) is a systematic intraday trading strategy that requires multiple analytical layers to align before taking a trade. Think of it as a layered cake - each layer must be present for a valid setup.

The Layered Architecture

┌─────────────────────────────────────────────────────────────┐
│                                                             │
│   LAYER 5: ENTRY TECHNIQUE (MA21 Zone)                     │  ← Final trigger
│   Price must be near 21-period MA (±25 points)              │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 4: SETUP QUALITY GRADING                           │  ← Quality gate
│   5-factor scoring: Only A+, A, B grades trade              │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 3: MARKET STATE ANALYSIS                           │  ← Context
│   7 algorithms detect: Railroad, Creeper, Phase, etc.       │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 2: DIRECTION FILTER (MA21 Slope)                   │  ← Hard filter
│   Rising MA = LONG only | Declining MA = SHORT only         │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 1: MULTI-TIMEFRAME ANALYSIS  ◄── THE FOUNDATION    │
│   5 timeframes must show trend alignment                    │
│   Daily → 4H → 1H → 15M → 5M                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Key Insight: A trade only happens when ALL layers align. MTF Analysis is the foundation - without trend alignment across timeframes, nothing else matters.

Instrument Details

Parameter Value
Instrument MCX Crude Oil Futures
Lot Size 100 barrels
Tick Value 1 point = Rs 100 per lot
Market Hours 9:00 AM - 11:30 PM IST
Strategy Hours 10:00 AM - 9:59 PM IST (blocks hours 9, 22, 23)

Backtest Results

Metric Value
Period 19 months
Total Trades 7,534
Win Rate 57.6%
Profit Factor 1.20
Initial Capital Rs 1.00 Lakhs
Final Value Rs 26.48 Lakhs
Total Return 2,548%

PART 2: THE EDGE (Why This Works)

Core Philosophy

The edge comes from requiring multiple independent confirmations before trading. Each layer filters out bad trades:

Layer What It Filters Out
MTF Analysis Counter-trend trades, choppy markets
Direction Filter Trades against the dominant trend
Market State Dangerous conditions (creeper moves, institutional fights)
Quality Grading Low-probability setups (C, D, F grades)
Entry Technique Chasing price far from value (MA21)

The Math

If each layer has 70% accuracy independently:

  • Single layer: 70% edge
  • 2 layers: 70% × 70% = 49% of trades pass, but higher quality
  • 5 layers: Only the best setups survive all filters

Result: Fewer trades, but each trade has multiple confluences supporting it.


PART 3: LAYER 1 - MULTI-TIMEFRAME ANALYSIS (The Foundation)

THIS IS THE FOUNDATION - Everything else builds on top of MTF alignment. If timeframes disagree, we don't trade.

The 5 Timeframes

Timeframe Role Weight
Daily (1D) Overall market bias Highest
4-Hour (4H) Primary trend direction High
1-Hour (1H) Trend confirmation Medium
15-Minute (15M) Entry timing context Lower
5-Minute (5M) Execution timeframe Lowest

What We Analyze Per Timeframe

For each of the 5 timeframes, the system calculates:

Analysis Description Source
MA21 Value 21-period Moving Average trend_analysis_core.py
MA21 Slope Rising/Flat/Declining trend_analysis_core.py
MA200 Value 200-period Moving Average trend_analysis_core.py
Price vs MA21 Above/Below/At the MA trend_analysis_core.py
Trend Direction UP/DOWN/NEUTRAL trend_analysis_core.py

MTF Alignment Score

For each timeframe:
  1. Determine trend direction (UP/DOWN/NEUTRAL)
  2. Check if aligned with trade direction
  3. Apply timeframe weight
  4. Sum weighted alignment scores

Example (LONG trade):
  Daily:  UP (aligned)     × 1.00 weight = 1.00
  4H:     UP (aligned)     × 0.86 weight = 0.86
  1H:     UP (aligned)     × 0.72 weight = 0.72
  15M:    DOWN (not aligned) × 0.58 weight = 0.00
  5M:     UP (aligned)     × 0.44 weight = 0.44
  ─────────────────────────────────────────────
  Total MTF Score: 3.02 / 3.60 = 83.9% aligned

Why MTF Matters

Scenario MTF Alignment Action
All 5 timeframes aligned 100% High conviction trade
4 of 5 aligned ~85% Trade with normal size
3 of 5 aligned ~70% Proceed with caution
2 or fewer aligned <60% Reduced quality score

PART 4: LAYER 2 - DIRECTION DETERMINATION

HARD FILTER - This is non-negotiable. MA21 slope determines the ONLY direction we can trade.

The Rule

MA21 Slope Allowed Direction Logic
Rising (↗) LONG only Trade with uptrend, never short
Declining (↘) SHORT only Trade with downtrend, never long
Flat (→) Use MTF direction Higher timeframes decide

Slope Calculation

Slope % = (MA21[current] - MA21[previous]) / MA21[previous] × 100

Thresholds:
  > +0.01%  → RISING (LONG only)
  < -0.01%  → DECLINING (SHORT only)
  ±0.01%   → FLAT (use MTF consensus)

Algorithm

<source lang="python"> def determine_trade_direction(ma21_slope, mtf_direction):

   """
   HARD FILTER - Direction alignment is mandatory.
   Source: trend_analysis_core.py
   """
   SLOPE_THRESHOLD = 0.0001  # 0.01%
   if ma21_slope > SLOPE_THRESHOLD:
       return LONG   # Rising MA = LONG only
   elif ma21_slope < -SLOPE_THRESHOLD:
       return SHORT  # Declining MA = SHORT only
   else:
       return mtf_direction  # Flat = defer to MTF

</source>

Why 80% of Trades Were SHORT

In the backtest period, MA21 was predominantly declining:

  • Market was in a sustained downtrend
  • Rising MA periods were shorter/fewer
  • This is expected behavior - strategy adapts to market conditions

PART 5: LAYER 3 - MARKET STATE ANALYSIS

The 7 Market State Algorithms

The system runs 7 independent algorithms to understand current market context:

# Algorithm What It Detects Impact
1 Railroad Tracks Strong momentum bars in sequence +15% bonus
2 Creeper Move Slow grinding trend (dangerous) -50% penalty
3 Two-Day Trend Trend visible on Daily for 2+ days Required for A+
4 Phase Analysis Accumulation/Distribution/Markup/Markdown Phase mismatch = -25%
5 Institutional Activity Big player accumulation/distribution Fight = 0.7× multiplier
6 Break of Structure (BOS) Key level breaks Affects stop placement
7 Volatility Regime High/Normal/Low volatility Adjusts expectations

Penalty System

Condition Penalty Rationale
Creeper Move Detected -50 points Slow trends often reverse suddenly
MA Struggle (price fighting MA) -30 points Indecision, likely to chop
No Two-Day Trend -30 points Trend not established enough
Phase Mismatch -25 points Trading against market phase
No Key Level Nearby -50 points No technical confluence
Institutional Fight ×0.70 multiplier Big players fighting each other

Bonus System

Condition Bonus Rationale
Railroad Tracks +15 points Strong momentum confirmation
At Key Level +10 points Technical confluence present
Clean Entry Setup +10 points Clear technical pattern

PART 6: LAYER 4 - SETUP QUALITY GRADING

The 5-Factor Scoring System

Every potential trade is scored on 5 factors:

Factor Weight What It Measures
Timeframe Alignment 30% How well all 5 timeframes agree
Trend Strength 20% Quality of the trend (Railroad vs Creeper)
Key Level Proximity 20% Is entry near significant S/R level?
Entry Quality 15% How clean is the entry technique?
Risk:Reward 15% Is the R:R ratio favorable?

Note: Weights sum to 100%. Timeframe Alignment has highest weight (30%) because MTF is the foundation.

Grade Thresholds

Grade Score Range Action Position Size
A+ 90-100 Trade with full conviction 2 lots
A 80-89 Trade with confidence 1 lot
B 70-79 Trade normally 1 lot
C 60-69 NO TRADE -
D 50-59 NO TRADE -
F <50 NO TRADE -

A+ Grade Special Requirements

To achieve A+ grade, ALL conditions must be true:

  • Final score ≥ 90
  • All 5 timeframes aligned with trade direction
  • Entry within ±25 points of MA21
  • Two-day trend present on Daily
  • No institutional fight detected

Score Calculation Example

Trade Setup: LONG on 5-min chart

Factor Scores (0-100 each):
  Timeframe Alignment: 85  × 0.30 = 25.5
  Trend Strength:      90  × 0.20 = 18.0
  Key Level Proximity: 70  × 0.20 = 14.0
  Entry Quality:       80  × 0.15 = 12.0
  Risk:Reward:         75  × 0.15 = 11.25
                              ──────────
  Base Score:                    80.75

Penalties Applied:
  - No Railroad Tracks: 0
  - No Creeper: 0
  - Has Two-Day: 0
                              ──────────
  Final Score: 80.75 → Grade: A

PART 7: LAYER 5 - ENTRY TECHNIQUE

The MA21 Zone Principle

"The MA is a ZONE, not a thin line"

Entry is allowed within ±25 points of MA21, not just at the exact MA value.

Why ±25 Points?

  • Price rarely touches MA exactly
  • Allows for normal market noise
  • Captures the "value zone" around the average
  • Based on typical Crude Oil volatility

Available Entry Techniques

Technique Direction Description
NEAR_MA Both Price within ±25 pts of MA21 (most common)
MA_BOUNCE_LONG Long Price touches MA21 and bounces up
MA_BOUNCE_SHORT Short Price touches MA21 and rejects down
GREEN_BAR_AFTER_PULLBACK Long Bullish candle after pullback to MA
RED_BAR_AFTER_RALLY Short Bearish candle after rally to MA
BOS_ENTRY_LONG Long Break of structure to upside
BOS_ENTRY_SHORT Short Break of structure to downside

Entry Selection Logic

<source lang="python"> def select_entry_technique(price, ma21, direction, market_state):

   """
   Select best entry technique based on conditions.
   Source: signal_generation_trade_management.py
   """
   ma_distance = abs(price - ma21)
   # Most common: price in MA zone
   if ma_distance <= 25:  # ±25 points
       return NEAR_MA
   # Break of structure detected
   if market_state.has_bos:
       return BOS_ENTRY_LONG if direction == LONG else BOS_ENTRY_SHORT
   # Pullback/Rally pattern
   if market_state.has_pullback:
       return GREEN_BAR_AFTER_PULLBACK if direction == LONG else RED_BAR_AFTER_RALLY
   return NEAR_MA  # Default

</source>


PART 8: STOP LOSS CALCULATION

Stop Loss Methods (Priority Order)

Priority Method Description
1 BOS-Based Stop Below/above break of structure level
2 Swing-Based Stop Below recent swing low (LONG) or above swing high (SHORT)
3 Default Stop Fixed 40 points from entry

Minimum Stop Distance

MINIMUM: 40 points - Stops closer than 40 points are automatically widened to 40.

This prevents:

  • Getting stopped out by normal noise
  • Excessive trading costs from tight stops
  • Whipsaws in volatile Crude Oil market

Stop Calculation Algorithm

<source lang="python"> def calculate_stop_loss(entry_price, direction, market_state):

   """
   Calculate stop loss with minimum enforcement.
   Source: signal_generation_trade_management.py
   """
   MIN_STOP_DISTANCE = 40.0  # points
   # Try BOS-based stop first
   if market_state.bos_level:
       stop = market_state.bos_level - 5  # 5pt buffer
   # Try swing-based stop
   elif market_state.swing_low and direction == LONG:
       stop = market_state.swing_low - 5
   # Default stop
   else:
       if direction == LONG:
           stop = entry_price - MIN_STOP_DISTANCE
       else:
           stop = entry_price + MIN_STOP_DISTANCE
   # ENFORCE MINIMUM
   actual_distance = abs(entry_price - stop)
   if actual_distance < MIN_STOP_DISTANCE:
       if direction == LONG:
           stop = entry_price - MIN_STOP_DISTANCE
       else:
           stop = entry_price + MIN_STOP_DISTANCE
   return stop

</source>


PART 9: TARGET CALCULATION

The 50% Rule

Target = 50% of distance to MA21

For mean reversion trades, we target halfway back to the moving average.

Why 50%?

  • Conservative target ensures higher hit rate
  • Based on "divide the move in half" principle
  • Captures partial reversion without being greedy
  • Works well with trailing stop to capture more

Minimum Target Rule

Minimum Target = Risk × 1.5

Example:
  Entry: 5700
  Stop: 5660 (40 points risk)

  50% to MA might give: 30 points
  But minimum is: 40 × 1.5 = 60 points

  Final Target: 5760 (60 points)

Target Calculation

<source lang="python"> def calculate_target(entry_price, stop_price, ma21, direction):

   """
   PDF-based target: 50% of distance to MA, with minimum.
   Source: signal_generation_trade_management.py
   """
   risk_distance = abs(entry_price - stop_price)
   min_target = risk_distance * 1.5  # Minimum 1.5:1 R:R
   # Calculate 50% move toward MA
   distance_to_ma = abs(entry_price - ma21)
   target_distance = distance_to_ma * 0.5
   # Enforce minimum
   target_distance = max(target_distance, min_target)
   if direction == LONG:
       return entry_price + target_distance
   else:
       return entry_price - target_distance

</source>


PART 10: DYNAMIC STOP MANAGEMENT

Two-Phase Protection

After entry, stops are managed dynamically in two phases:

Phase Trigger Action
Phase 1: Breakeven +25 points profit Move stop to entry + 2 points
Phase 2: Trailing +20 points profit Trail stop using ATR × 2

Phase 1: Breakeven Stop

Configuration:
  breakeven_activation = 25 points
  breakeven_buffer = 2 points

Example (LONG from 5700):
  Price reaches 5725 (+25 pts profit)
  → Stop moves from 5660 to 5702 (entry + 2)
  → Trade is now "risk-free"

Phase 2: Trailing Stop

Configuration:
  trailing_stop_activation = 20 points
  trailing_stop_method = ATR_MULTIPLE
  atr_period = 14 bars
  atr_multiplier = 2.0
  minimum_trail_distance = 15 points

Example (LONG from 5700, ATR = 12):
  Trailing Distance = 12 × 2 = 24 points

  Price at 5740:
  → Trail stop = 5740 - 24 = 5716

  Price at 5760:
  → Trail stop = 5760 - 24 = 5736 (moved UP)

  Price drops to 5736:
  → STOPPED OUT at 5736 (profit locked)

Why Both Phases?

Phase Purpose
Breakeven Eliminate risk quickly once trade moves in favor
Trailing Let winners run while protecting accumulated profit

PART 11: SLIPPAGE & COSTS

Realistic Slippage Model

Event Slippage Rationale
Entry +1.0 point Normal market fill
Stop Loss Exit +2.0 points Stops slip more in fast moves
Target Exit +0.5 points Limit orders have minimal slippage

Cost Structure

Cost Type Value
Commission Rs 20 per lot per side
STT 0.01% on sell side
Exchange Fees ~Rs 2 per lot
Stamp Duty State-dependent

Why Model Slippage?

  • Backtest results must reflect real trading
  • Prevents over-optimistic performance estimates
  • Stop loss slippage is higher because stops often trigger during fast moves
  • Total costs ~Rs 79 per round-trip lot

PART 12: EXIT RULES

Three Exit Conditions

Exit Type Condition % of Exits
Stop Loss Price hits stop (original or trailing) 72.3%
Target Price hits take profit level 22.8%
Timeout End of day (no overnight holds) 5.0%

Why 72% Stop Exits but 57% Win Rate?

This seems contradictory but makes sense:

  • Trailing stops lock in profits - many "stop exits" are actually winning trades
  • Breakeven stops trigger at +25 pts, trailing at +20 pts
  • A trade can be stopped out at +30 pts profit (counted as stop exit but is a WIN)

End-of-Day Exit

All positions closed before market close:
  - Market closes at 11:30 PM IST
  - 15-minute buffer before close
  - Prevents overnight gap risk

PART 13: PUTTING IT ALL TOGETHER

Trade Flow

┌─────────────────────────────────────────────────────────────────┐
│  STEP 1: Load data for all 5 timeframes                         │
│  Daily, 4H, 1H, 15M, 5M OHLCV data                             │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 2: LAYER 1 - MTF Analysis (Foundation)                    │
│  Calculate MA21, MA200, trend direction for each timeframe      │
│  Compute MTF alignment score                                    │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 3: LAYER 2 - Direction Filter                             │
│  Check MA21 slope on entry timeframe (5M)                       │
│  Rising → LONG only | Declining → SHORT only | Flat → use MTF   │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 4: LAYER 3 - Market State Analysis                        │
│  Run 7 algorithms: Railroad, Creeper, Phase, BOS, etc.          │
│  Calculate penalties and bonuses                                │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 5: LAYER 4 - Setup Quality Grading                        │
│  Score 5 factors, apply penalties/bonuses                       │
│  Assign grade: A+/A/B → TRADE | C/D/F → NO TRADE               │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 6: LAYER 5 - Entry Check                                  │
│  Is price within ±25 points of MA21?                            │
│  Select entry technique                                         │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 7: Calculate Stop Loss                                    │
│  BOS-based → Swing-based → Default (40 pts minimum)             │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 8: Calculate Target                                       │
│  50% of distance to MA (minimum 1.5× risk)                      │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 9: Execute Trade                                          │
│  Apply entry slippage (+1 pt), create trade record              │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 10: Manage Trade                                          │
│  Monitor: Breakeven at +25 pts → Trail at +20 pts               │
│  Exit: Stop hit | Target hit | Timeout                          │
└─────────────────────────────────────────────────────────────────┘

PART 14: HARD vs SOFT FILTERS

Understanding the Difference

Filter Type Behavior Examples
HARD Blocks trade completely Direction filter, Hour filter, Grade C/D/F
SOFT Affects quality score MTF alignment, Market state penalties

Complete Filter List

Filter Type Effect
MA21 Direction HARD Wrong direction = NO TRADE
Hour Filter HARD Hours 9, 22, 23 = NO TRADE
Grade < B HARD C/D/F grades = NO TRADE
MTF Alignment SOFT Low alignment = reduced score (30% weight)
Creeper Move SOFT -50 points penalty
No Two-Day Trend SOFT -30 points penalty
Institutional Fight SOFT 0.7× score multiplier
Far from MA21 SOFT -40 points penalty

APPENDIX A: CONFIGURATION VALUES

Entry Configuration

Parameter Value Source File
entry_timeframe 5-Minute main.py:165
ma_buffer_points 25 points signal_generation_trade_management.py:68
blocked_hours [9, 22, 23] signal_generation_trade_management.py:137

Stop/Target Configuration

Parameter Value Source File
min_stop_distance 40 points signal_generation_trade_management.py:59
default_risk_reward 1.5 signal_generation_trade_management.py:62
bos_stop_buffer_points 5 points signal_generation_trade_management.py:81

Dynamic Stop Configuration

Parameter Value Source File
enable_trailing_stop True trade_execution_engine.py:57
trailing_stop_method ATR_MULTIPLE trade_execution_engine.py:58
atr_period 14 bars trade_execution_engine.py:61
atr_multiplier 2.0 trade_execution_engine.py:65
trailing_stop_activation 20 points trade_execution_engine.py:60
enable_breakeven_stop True trade_execution_engine.py:67
breakeven_activation 25 points trade_execution_engine.py:70
breakeven_buffer 2 points trade_execution_engine.py:71
minimum_trail_distance 15 points trade_execution_engine.py:370

Slippage Configuration

Parameter Value Source File
base_slippage_points 1.0 point trade_execution_engine.py:38
stop_loss_slippage 2.0 points trade_execution_engine.py:50
take_profit_slippage 0.5 points trade_execution_engine.py:51

Grading Configuration

Parameter Value Source File
timeframe_alignment_weight 30% setup_quality_detection.py:44
trend_strength_weight 20% setup_quality_detection.py:45
key_level_proximity_weight 20% setup_quality_detection.py:47
entry_technique_weight 15% setup_quality_detection.py:46
risk_reward_weight 15% setup_quality_detection.py:48
a_plus_min_score 90 setup_quality_detection.py:51
a_min_score 80 setup_quality_detection.py:52
b_min_score 70 setup_quality_detection.py:53

APPENDIX B: SOURCE CODE REFERENCE

File Purpose
main.py Entry point, timeframe configuration
trend_analysis_core.py MA calculation, slope detection, trend direction
multi_timeframe_analysis.py MTF alignment scoring across 5 timeframes
market_state_analysis.py 7 market state detection algorithms
setup_quality_detection.py 5-factor grading system with penalties/bonuses
probability_zone_analysis.py Halves/Thirds, Three-Finger Spread, Crash Bar
signal_generation_trade_management.py Entry/Exit logic, stop/target calculation
trade_execution_engine.py Breakeven, Trailing stop, Slippage modeling
data_manager.py OHLCV data loading and management

Document generated from source code analysis - January 2026

Strategy: Multi-Layer Confluence (MLC) v1.0