Jump to content

Alpha Research: Difference between revisions

From PlusEV Wiki Page
No edit summary
No edit summary
Line 5: Line 5:
----
----


= PART 1: CORE CONCEPT =
= PART 1: STRATEGY OVERVIEW =
 
== What Is This Strategy? ==
 
'''MA21 Mean Reversion''' - A systematic intraday trading strategy that enters when price pulls back to the 21-period Moving Average during established trends.
 
== Instrument Details ==
 
{| class="wikitable"
|-
! Parameter !! Value
|-
| '''Instrument''' || MCX Crude Oil Futures
|-
| '''Lot Size''' || 100 barrels
|-
| '''Tick Value''' || 1 point = Rs 100 per lot
|-
| '''Trading Hours''' || 9:00 AM - 11:30 PM IST
|-
| '''Allowed Trading''' || 10:00 AM - 9:00 PM IST (block open/close)
|}
 
== Timeframes Used ==
 
{| class="wikitable"
|-
! Timeframe !! Purpose
|-
| '''5-Minute''' || Primary chart for signals and execution
|-
| '''1-Minute''' || Entry precision timing
|-
| '''15-Min, 1H, 4H, Daily''' || Multi-timeframe context (soft filter)
|}
 
== Backtest Results Summary ==
 
{| class="wikitable"
|-
! 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%'''
|-
| '''Max Drawdown''' || -78.6%
|}
 
----
 
= PART 2: THE EDGE (Core Concept) =


== The Big Idea ==
== The Big Idea ==
Line 13: Line 74:
When the market is trending, price naturally pulls back to the 21 MA before continuing. We enter at these pullback zones, trading WITH the trend direction.
When the market is trending, price naturally pulls back to the 21 MA before continuing. We enter at these pullback zones, trading WITH the trend direction.


<blockquote>'''"The MA is a ZONE, not a thin line"''' - Entry allowed within '''±25 points''' of MA21</blockquote>
== Why It Works ==
 
# '''Mean Reversion''' - Price tends to return to the average after moving away
# '''Trend Following''' - We only trade in the direction of the trend
# '''Value Entry''' - Entering on pullbacks gives better risk:reward
# '''Institutional Behavior''' - Big players accumulate at MA zones
 
== The "MA is a ZONE" Principle ==
 
<blockquote>
'''"The MA is a ZONE, not a thin line"'''
 
Entry is allowed within '''±25 points''' of MA21, not just at the exact MA value.
</blockquote>
 
'''Why ±25 points?'''
* Price rarely touches MA exactly
* Gives room for entry without chasing
* Accounts for spread and slippage
* MCX Crude typical range: 50-100 pts/day


----
----


= PART 2: MULTI-TIMEFRAME (MTF) ANALYSIS =
= PART 3: DIRECTION DETERMINATION (The Foundation) =


{{Note|'''IMPORTANT:''' MTF alignment is a '''SOFT FILTER''' (30% weight in grading score). It is NOT a hard rejection filter. A trade with poor MTF alignment can still pass if other factors compensate.}}
<div style="background:#ffcccc; border:2px solid #cc0000; padding:10px; margin:10px 0;">
'''THIS IS THE MOST IMPORTANT RULE'''


== Timeframe Hierarchy ==
The MA21 slope determines the ONLY direction you can trade. This is a '''HARD FILTER''' - no exceptions.
</div>


We analyze '''5 timeframes''' from highest to lowest:
== MA21 Slope = Trade Direction ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Timeframe !! Purpose !! What We Look For
! MA21 Slope !! Allowed Direction !! Logic
|-
|-
| '''Daily (1D)''' || Context/Bias || Overall trend direction, key levels
| '''Rising''' () || '''LONG only''' || Trade with uptrend, never short
|-
|-
| '''4-Hour (4H)''' || Primary Trend || Main trend confirmation
| '''Declining''' () || '''SHORT only''' || Trade with downtrend, never long
|-
|-
| '''1-Hour (1H)''' || Confirmation || Trend alignment validation
| '''Flat''' (→) || Use MTF direction || Let higher timeframes decide
|}
 
== How Slope Is Calculated ==
 
{| class="wikitable"
|-
! Slope Value !! Classification !! Threshold
|-
|-
| '''15-Min (15M)''' || Entry Timing || Final confirmation before entry
| > +0.01% || RISING || Bullish - LONG only
|-
|-
| '''5-Min (5M)''' || Execution || Precise entry and exit
| < -0.01% || DECLINING || Bearish - SHORT only
|-
| Between ±0.01% || FLAT || Use MTF consensus
|}
|}


== MTF Alignment Logic ==
== Why 80% of Trades Were SHORT ==


For each timeframe, we check:
In our 19-month backtest:
# '''MA21 Slope''' - Is it rising or declining?
* '''6,024 SHORT trades (80%)'''
# '''Price Position''' - Is price above/below MA21?
* '''1,510 LONG trades (20%)'''
# '''MA21 vs MA200''' - Short-term vs long-term trend alignment


=== Weighted Scoring ===
'''Reason:''' During the backtest period, MCX Crude Oil had a predominantly '''declining MA21''' slope. The system correctly identified this bearish bias and took mostly short trades.


Each timeframe contributes to an '''alignment score''':
This is NOT a flaw - it shows the system adapts to market conditions.
* Higher timeframes have more weight (Daily > 4H > 1H > 15M > 5M)
* Score ranges from 0.0 to 1.0
* Higher score = stronger alignment


=== Direction Determination ===
== Direction Determination Algorithm ==


<pre>
<source lang="python">
IF all timeframes agree → Strong signal
def determine_direction(ma21_slope, mtf_direction):
IF most timeframes agree → Medium signal
    """
IF timeframes conflict → No trade (wait for clarity)
    THE PRIMARY FILTER - Direction must align with MA21 slope.
</pre>
    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


== Per-Timeframe Trend Analysis ==
    else:  # Flat MA
        return mtf_direction  # Use multi-timeframe consensus
</source>


For each timeframe, the '''Trend Analysis Core''' calculates:
----


=== 1. Trend Direction ===
= PART 4: ENTRY CONDITIONS (Gate Checks) =


Based on MA21 slope:
== Overview: Hard vs Soft Filters ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA21 Slope !! Direction !! Threshold
! Filter Type !! Behavior !! Examples
|-
| Positive > 0.01% || UP || Bullish slope threshold
|-
|-
| Negative < -0.01% || DOWN || Bearish slope threshold
| '''HARD''' || Must pass ALL or NO TRADE || MA21 slope, hour filter, price in zone, grade
|-
|-
| Between ±0.01% || SIDEWAYS || No clear trend
| '''SOFT''' || Affects score but doesn't block || MTF alignment, market state, penalties
|}
|}


=== 2. MA Trending Status ===
== 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 ===
* Must achieve grade '''A+, A, or B''' (score ≥ 70)
* Grade C/D/F = not good enough quality
* '''Fail = NO TRADE'''
 
== SOFT FILTERS (Affect Score) ==


Is the MA21 moving with significant momentum?
These filters affect the quality score but don't block trades:


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA Slope !! Status !! Threshold
! Filter !! Effect !! Impact
|-
|-
| > 0.05% || TRENDING || MA is clearly moving
| MTF Alignment || 30% weight in grading || Low alignment = lower score
|-
|-
| < 0.05% || FLAT || MA is consolidating
| Creeper Move || -50 penalty || Can still pass if base high
|-
| Railroad Trend || +15 bonus || Quality boost
|-
| Price-MA Struggle || -30 penalty || Can still pass
|-
| Wrong Trend Phase || -25 penalty || Can still pass
|-
| Institutional Fight || 0.7x multiplier || Reduces but doesn't block
|}
|}


=== 3. Price-MA Struggle Detection ===
== Filter Flow Diagram ==
 
<pre>
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 =
 
<div style="background:#ffffcc; border:1px solid #ffcc00; 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.
</div>
 
== Timeframe Hierarchy ==


Is price stuck near the MA without breaking away?
We analyze '''5 timeframes''' from highest to lowest:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Condition !! Detection
! Timeframe !! Purpose !! Weight
|-
|-
| Price within 0.5% of MA21 for multiple bars || STRUGGLING
| '''Daily (1D)''' || Context/Bias || Highest weight
|-
|-
| Price clearly moving away from MA21 || CLEAR TREND
| '''4-Hour (4H)''' || Primary Trend || High weight
|-
| '''1-Hour (1H)''' || Confirmation || Medium weight
|-
| '''15-Min (15M)''' || Entry Timing || Lower weight
|-
| '''5-Min (5M)''' || Execution || Lowest weight
|}
|}


'''Trading Impact:''' Price-MA struggle = '''-30 penalty''' in grading
== Per-Timeframe Analysis ==


=== 4. Trend Confidence Calculation ===
For each timeframe, the '''Trend Analysis Core''' calculates:


Weighted score from three factors:
=== 1. Trend Direction ===


<pre>
{| class="wikitable"
Confidence = (MA_Slope × 40%) + (Price_Position × 30%) + (MA_Alignment × 30%)
|-
</pre>
! MA21 Slope !! Direction
|-
| > +0.01% || UP
|-
| < -0.01% || DOWN
|-
| Between ±0.01% || SIDEWAYS
|}
 
=== 2. MA Trending Status ===


{| class="wikitable"
{| class="wikitable"
|-
|-
! Factor !! Weight !! What It Measures
! MA Slope Magnitude !! Status
|-
| > 0.05% || TRENDING (MA is clearly moving)
|-
| < 0.05% || FLAT (MA is consolidating)
|}
 
=== 3. Price-MA Struggle Detection ===
 
{| class="wikitable"
|-
|-
| MA Slope || 40% || Steepness of MA21 angle
! Condition !! Detection !! Impact
|-
|-
| Price Position || 30% || Is price above/below MA21?
| Price within 0.5% of MA21 for multiple bars || STRUGGLING || -30 penalty
|-
|-
| MA Alignment || 30% || Does MA21 align with MA200?
| Price clearly moving away from MA21 || CLEAR TREND || No penalty
|}
|}


----
== Alignment Score Calculation ==
 
<pre>
For each timeframe:
  - Check if direction matches expected direction
  - Assign weight based on timeframe importance


= PART 3: SIGNAL GENERATION FLOW =
Alignment Score = Σ(Weight_i × Aligned_i) / Σ(Weight_i)


== Complete Flow Diagram ==
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


<pre>
   Score = (1.0 + 0.86 + 0.72 + 0 + 0.44) / (1.0 + 0.86 + 0.72 + 0.58 + 0.44)
┌─────────────────────────────────────────────────────────────────────────────┐
        = 3.02 / 3.60 = 0.84 (84% alignment)
│                        SIGNAL GENERATION PIPELINE                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                            │
│  STEP 1: DATA COLLECTION                                                    │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ Load OHLCV data for all 5 timeframes                                │  │
│  │ Calculate MA21 and MA200 for each timeframe                        │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 2: MULTI-TIMEFRAME ANALYSIS                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ Analyze trend direction in each timeframe                          │  │
│  │ Calculate weighted alignment score                                  │  
│  │ Determine primary direction (LONG/SHORT/NONE)                       │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 3: MARKET STATE ANALYSIS                                            │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ Detect: Railroad Trend, Creeper Move, Two-Day Trend                │  │
│  │ Classify: Trend Phase (EARLY/MIDDLE/LATE)                          │  │
│  │ Check: Institutional activity, BOS (Break of Structure)            │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 4: SETUP QUALITY GRADING                                            │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ Calculate 5-factor weighted score                                    │  │
│  │ Apply penalties (creeper -50, MA struggle -30, etc.)                │  │
│  │ Apply bonuses (railroad +15, key level +10)                        │  │
│  │ Assign grade: A+, A, B, C, D, F                                    │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 5: ENTRY FILTERS                                                    │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ □ Is price within ±25 pts of MA21?                                  │  │
│  │ □ Does direction align with MA21 slope?                            │  │
│  │ □ Is setup grade A+, A, or B?                                      │  │
│  │ □ Is current hour allowed? (not 9, 22, 23)                         │  │
│  │ □ Does probability zone allow this trade?                          │  │
│  │ ALL YES → Generate Signal | ANY NO → No Signal                      │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 6: SIGNAL OUTPUT                                                    │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ Direction: LONG or SHORT                                            │  │
│  │ Entry Price: Current close price                                    │  │
│  │ Stop Loss: 40 points (structure-based or default)                  │  │
│  │ Take Profit: 60 points (1.5:1 R:R)                                 │  │
│  │ Position Size: 1 lot                                                │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                                                                            │
└─────────────────────────────────────────────────────────────────────────────┘
</pre>
</pre>


----
----


= PART 4: MARKET STATE DETECTION =
= PART 6: MARKET STATE DETECTION =


== 7 Detection Algorithms ==
The system detects '''7 market state patterns''' that affect setup quality:


=== 1. Railroad Trend Detection ===
== 1. Railroad Trend Detection ==


'''What it is:''' Strong, consistent trend with minimal pullbacks.
'''What:''' Strong, consistent trend with minimal pullbacks.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Description
! Characteristic !! Threshold
|-
|-
| Bar Analysis || 5 most recent bars analyzed
| Bar Analysis || 5 most recent bars
|-
|-
| Strong Bars || 80%+ must close in same direction
| Strong Bars || 80%+ must close in same direction
|-
|-
| Consistency || Bars must be "strong" (body > 0.3% of price)
| Bar Body || > 0.3% of price
|}
|}


'''Trading Impact:''' +15 bonus to setup score (high quality trend)
'''Impact:''' '''+15 bonus''' to setup score


----
----


=== 2. Creeper Move Detection ===
== 2. Creeper Move Detection ==


'''What it is:''' Slow, grinding price action with small bars.
'''What:''' Slow, grinding price action with small bars.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Description
! Characteristic !! Threshold
|-
|-
| Bar Range || Average range < 0.5% of price
| Bar Range || Average < 0.5% of price
|-
|-
| Analysis Period || Last 7 bars
| Analysis Period || Last 7 bars
|-
| Pattern || Price moving slowly without clear impulse
|}
|}


'''Trading Impact:''' '''-50 penalty''' to setup score (avoid these setups)
'''Impact:''' '''-50 penalty''' to setup score (avoid these!)


----
----


=== 3. Two-Day Trend Analysis ===
== 3. Two-Day Trend Analysis ==


'''What it is:''' Trend must be visible on Daily timeframe for 2+ days.
'''What:''' Trend must be visible on Daily for 2+ days.


{| class="wikitable"
{| class="wikitable"
Line 241: Line 405:
! Requirement !! Description
! Requirement !! Description
|-
|-
| Daily Bars || At least 2 consecutive bars in same direction
| Daily Bars || 2+ consecutive bars in same direction
|-
|-
| Purpose || Filters out noise, ensures real trend
| Purpose || Filters noise, ensures real trend
|}
|}


'''Trading Impact:''' Missing two-day trend = '''-30 penalty'''
'''Impact:''' Missing = '''-30 penalty'''


----
----


=== 4. Trend Phase Classification ===
== 4. Trend Phase Classification ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Phase !! Bars into Trend !! Trading Approach
! Phase !! Bars into Trend !! Action !! Impact
|-
|-
| '''EARLY''' || 0-15 bars || Avoid (uncertain direction)
| '''EARLY''' || 0-15 bars || Avoid || -25 penalty
|-
|-
| '''MIDDLE''' || 15-40 bars || '''TARGET''' (best trades)
| '''MIDDLE''' || 15-40 bars || '''TARGET''' || No penalty
|-
|-
| '''LATE''' || 40+ bars || Avoid (exhaustion risk)
| '''LATE''' || 40+ bars || Avoid || -25 penalty
|}
|}
'''Trading Impact:''' Not being in MIDDLE phase = '''-25 penalty'''


----
----


=== 5. Institutional Fight Detection ===
== 5. Institutional Fight Detection ==


'''What it is:''' When big players are battling each other (choppy action).
'''What:''' Big players battling each other.


{| class="wikitable"
{| class="wikitable"
Line 275: Line 437:
! Indicator !! Sign
! Indicator !! Sign
|-
|-
| Volume || 1.5x+ average volume
| Volume || 1.5x+ average
|-
|-
| Price Action || Narrow range with high volume
| Price Action || Narrow range with high volume
|-
|-
| Wicks || Long wicks on candles (rejection)
| Wicks || Long wicks (rejection)
|}
|}


'''Trading Impact:''' 0.7x multiplier on final score (30% reduction)
'''Impact:''' '''0.7x multiplier''' on final score


----
----


=== 6. Break of Structure (BOS) ===
== 6. Break of Structure (BOS) ==


'''What it is:''' Price breaking a significant swing high/low.
'''What:''' Price breaking significant swing high/low.


{| class="wikitable"
{| class="wikitable"
Line 305: Line 467:
----
----


=== 7. Volatility Classification ===
== 7. Volatility Classification ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Volatility !! ATR % of Price !! Trading Adjustment
! Volatility !! ATR % of Price !! Adjustment
|-
|-
| HIGH || > 1.0% || Wider stops needed
| HIGH || > 1.0% || Wider stops needed
Line 315: Line 477:
| MEDIUM || 0.3% - 1.0% || Normal stops
| MEDIUM || 0.3% - 1.0% || Normal stops
|-
|-
| LOW || < 0.3% || Tighter stops possible
| LOW || < 0.3% || Tighter stops
|}
|}


----
----


= PART 5: SETUP QUALITY GRADING SYSTEM =
= PART 7: SETUP QUALITY GRADING =


== 5-Factor Weighted Scoring ==
== 5-Factor Weighted Scoring ==
Line 332: Line 494:
| '''Timeframe Alignment''' || 30% || How well all timeframes agree
| '''Timeframe Alignment''' || 30% || How well all timeframes agree
|-
|-
| '''Trend Strength''' || 20% || Quality of the trend (railroad vs creeper)
| '''Trend Strength''' || 20% || Quality of trend (railroad vs creeper)
|-
|-
| '''Key Level Proximity''' || 20% || Is entry near a significant level?
| '''Key Level Proximity''' || 20% || Is entry near significant level?
|-
|-
| '''Entry Quality''' || 15% || Clean entry technique, near MA
| '''Entry Quality''' || 15% || Clean entry technique, near MA
|-
|-
| '''Risk/Reward''' || 15% || How favorable is the R:R ratio
| '''Risk/Reward''' || 15% || How favorable is the R:R
|}
|}


Line 347: Line 509:
           + (Entry_score × 0.15) + (RR_score × 0.15)
           + (Entry_score × 0.15) + (RR_score × 0.15)


Final Score = Base Score + Bonuses - Penalties
Adjusted Score = Base Score + Bonuses - Penalties
 
If Institutional Fight: Final Score = Adjusted Score × 0.7
</pre>
</pre>


== Penalties (Negative Adjustments) ==
== Penalties ==


{| class="wikitable"
{| class="wikitable"
Line 369: Line 533:
|}
|}


== Bonuses (Positive Adjustments) ==
== Bonuses ==


{| class="wikitable"
{| class="wikitable"
Line 403: Line 567:
== A+ Special Requirements ==
== A+ Special Requirements ==


To get an A+ grade, ALL of these must be true:
To achieve A+ grade, ALL must be true:
* Score ≥ 90
* Score ≥ 90
* All timeframes aligned
* All timeframes aligned
* Entry near MA21 (within ±25 pts)
* Entry near MA21 (within ±25 pts)
* Two-day trend present
* Two-day trend present
* No institutional fight


----
----


= PART 6: ENTRY TECHNIQUES =
= PART 8: ENTRY TECHNIQUES =


== Available Entry Techniques ==
== Available Techniques ==


=== Universal (Both Directions) ===
=== Universal (Both Directions) ===
Line 424: Line 589:
|}
|}


=== Long-Specific (Bullish) ===
=== Long-Specific ===


{| class="wikitable"
{| class="wikitable"
Line 430: Line 595:
! Technique !! Description
! Technique !! Description
|-
|-
| GREEN_BAR_AFTER_PULLBACK || Green candle after price pulled back
| GREEN_BAR_AFTER_PULLBACK || Green candle after pullback
|-
|-
| MA_BOUNCE_LONG || Bounce off MA21 in uptrend
| MA_BOUNCE_LONG || Bounce off MA21 in uptrend
Line 436: Line 601:
| BOS_ENTRY_LONG || Entry after break of structure (upside)
| BOS_ENTRY_LONG || Entry after break of structure (upside)
|-
|-
| BREAKOUT_PULLBACK_LONG || Pullback after breakout, then continue
| BREAKOUT_PULLBACK_LONG || Pullback after breakout
|-
|-
| DISCOUNT_ZONE_LONG || Buy in lower zone of range
| DISCOUNT_ZONE_LONG || Buy in lower zone of range
|}
|}


=== Short-Specific (Bearish) ===
=== Short-Specific ===


{| class="wikitable"
{| class="wikitable"
Line 447: Line 612:
! Technique !! Description
! Technique !! Description
|-
|-
| RED_BAR_AFTER_RALLY || Red candle after price rallied
| RED_BAR_AFTER_RALLY || Red candle after rally
|-
|-
| MA_BOUNCE_SHORT || Rejection from MA21 in downtrend
| MA_BOUNCE_SHORT || Rejection from MA21 in downtrend
Line 453: Line 618:
| BOS_ENTRY_SHORT || Entry after break of structure (downside)
| BOS_ENTRY_SHORT || Entry after break of structure (downside)
|-
|-
| BREAKOUT_PULLBACK_SHORT || Pullback after breakdown, then continue
| BREAKOUT_PULLBACK_SHORT || Pullback after breakdown
|-
|-
| PREMIUM_ZONE_SHORT || Sell in upper zone of range
| PREMIUM_ZONE_SHORT || Sell in upper zone of range
|}
|}


== How Entry Technique is Selected ==
== Selection Logic ==


<pre>
<source lang="python">
IF price near MA21 zone:
def select_entry_technique(price, ma21, direction, has_bos, has_pullback):
     technique = NEAR_MA
    # Most common: price near MA zone
     if abs(price - ma21) <= 25:
        return NEAR_MA


ELIF break of structure detected:
    # Break of structure detected
    IF direction == LONG: technique = BOS_ENTRY_LONG
    elif has_bos:
    IF direction == SHORT: technique = BOS_ENTRY_SHORT
        if direction == LONG:
            return BOS_ENTRY_LONG
        else:
            return BOS_ENTRY_SHORT


ELIF pullback pattern detected:
    # Pullback pattern detected
    IF direction == LONG: technique = GREEN_BAR_AFTER_PULLBACK
    elif has_pullback:
    IF direction == SHORT: technique = RED_BAR_AFTER_RALLY
        if direction == LONG:
            return GREEN_BAR_AFTER_PULLBACK
        else:
            return RED_BAR_AFTER_RALLY


ELSE:
    # Default: MA bounce
     technique = MA_BOUNCE_LONG or MA_BOUNCE_SHORT
     else:
</pre>
        if direction == LONG:
            return MA_BOUNCE_LONG
        else:
            return MA_BOUNCE_SHORT
</source>


----
----


= PART 7: PROBABILITY ZONES =
= PART 9: PROBABILITY ZONES =


== Halves & Thirds Analysis ==
== Halves & Thirds Analysis ==
Line 486: Line 663:
{| class="wikitable"
{| class="wikitable"
|-
|-
! Zone !! Position in Range !! Continuation Probability
! Zone !! Position !! Continuation Probability
|-
|-
| '''Top Third''' || 67-100% || 80% (likely to make new high)
| '''Top Third''' || 67-100% || 80% chance of new high
|-
|-
| '''Top Half''' || 50-67% || 65%
| '''Top Half''' || 50-67% || 65% continuation
|-
|-
| '''Bottom Half''' || 33-50% || 35%
| '''Bottom Half''' || 33-50% || 35% continuation
|-
|-
| '''Bottom Third''' || 0-33% || 15% (85% likely to go lower)
| '''Bottom Third''' || 0-33% || 15% (85% likely lower)
|}
|}


== Zone-Based Trading Rules ==
== Zone-Based Trading Rules ==


=== In Trending Market ===
=== Trending Market ===


{| class="wikitable"
{| class="wikitable"
Line 505: Line 682:
! Zone !! LONG !! SHORT
! Zone !! LONG !! SHORT
|-
|-
| Top Third || Allowed (after pullback) || Blocked (with trend)
| Top Third || Allowed (after pullback) || Blocked
|-
|-
| Bottom Third || Blocked (against trend) || Allowed (after rally)
| Bottom Third || Blocked || Allowed (after rally)
|}
|}


=== In Sideways Market (Mean Reversion) ===
=== Sideways Market ===


{| class="wikitable"
{| class="wikitable"
Line 523: Line 700:
== Three-Finger Spread ==
== Three-Finger Spread ==


'''What it is:''' Large separation between Price, MA21, and MA200.
'''What:''' Large separation between Price, MA21, and MA200.


<pre>
<pre>
Three-Finger Spread = When:
Detection:
- Distance(Price to MA21) > 2% of price
- Distance(Price to MA21) > 2% of price
- AND Distance(MA21 to MA200) > 2% of price
- AND Distance(MA21 to MA200) > 2% of price
</pre>
</pre>


'''Trading Impact:''' When detected, expect profit-taking soon (bearish for longs, bullish for shorts)
'''Impact:''' Expect profit-taking soon (bearish for longs, bullish for shorts)


== Crash Bar Detection ==
== Crash Bar Detection ==


'''What it is:''' Abnormally large bar indicating structural break.
'''What:''' Abnormally large bar indicating structural break.


{| class="wikitable"
{| class="wikitable"
Line 546: Line 723:
|}
|}


'''Trading Impact:''' Crash bar in sideways + top zone → Override to SHORT (Crash SHORT detection)
'''Special Rule:''' Crash bar in sideways market + top zone → Override to SHORT


----
----


= PART 8: EXIT RULES =
= PART 10: EXIT MANAGEMENT =
 
== Overview ==
 
{| class="wikitable"
|-
! Exit Type !! Trigger !! Typical Result
|-
| '''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 ==
== Initial Stop Loss: 40 Points ==
Line 560: Line 750:
| '''Default''' || 40 points from entry
| '''Default''' || 40 points from entry
|-
|-
| '''Structure-Based''' || Below recent swing low (LONG) / Above recent swing high (SHORT)
| '''Structure-Based''' || Below swing low (LONG) / Above swing high (SHORT)
|-
|-
| '''MA-Based''' || MA21 value ± 25 points buffer
| '''MA-Based''' || MA21 value ± 25 points buffer
|-
|-
| '''Minimum Enforced''' || Always at least 40 points
| '''Minimum''' || Always at least 40 points
|}
|}


=== Stop Loss by Entry Technique ===
=== Stop by Entry Technique ===


{| class="wikitable"
{| class="wikitable"
Line 579: Line 769:
| MA_BOUNCE || Below/above MA21 zone
| MA_BOUNCE || Below/above MA21 zone
|-
|-
| BREAKOUT_PULLBACK || Below/above pullback low/high (3-bar lookback)
| BREAKOUT_PULLBACK || Below/above pullback low/high
|}
|}


----
----


== DYNAMIC STOP MANAGEMENT (Two-Phase System) ==
== DYNAMIC STOP MANAGEMENT ==
 
<div style="background:#ccffcc; border:2px solid #00cc00; padding:10px; margin:10px 0;">
'''IMPORTANT:''' Stop loss is NOT static! It moves dynamically to lock in profits.


{{Note|'''IMPORTANT:''' Stop loss is NOT static! It moves dynamically to lock in profits.}}
This explains why '''72.3% of exits are "stop"''' but many are '''profitable trades'''!
</div>


=== Phase 1: Breakeven Stop (ENABLED) ===
=== Phase 1: Breakeven Stop ===


When trade reaches '''25 points profit''', stop moves to '''entry price + 2 pts'''.
'''Trigger:''' When trade reaches '''25 points profit'''


{| class="wikitable"
{| class="wikitable"
Line 600: Line 794:
| New Stop || Entry price + 2 pts buffer
| New Stop || Entry price + 2 pts buffer
|-
|-
| Purpose || Lock in small profit, eliminate loss
| Purpose || Eliminate loss, lock small profit
|}
|}


Line 608: Line 802:
Entry: 5500
Entry: 5500
Original Stop: 5460 (40 pts risk)
Original Stop: 5460 (40 pts risk)
Price reaches 5525 (25 pts profit)
 
→ Stop moves to 5502 (entry + 2 buffer)
Price reaches 5525 (+25 pts profit):
→ Worst case now = +2 pts profit (not -40 loss!)
→ Stop moves from 5460 to 5502 (entry + 2 buffer)
→ Worst case now = +2 pts profit (NOT -40 loss!)
</pre>
</pre>


=== Phase 2: Trailing Stop - ATR Based (ENABLED) ===
=== Phase 2: Trailing Stop (ATR-Based) ===


After '''20 points profit''', stop trails behind price using ATR (Average True Range).
'''Trigger:''' When trade reaches '''20 points profit'''


{| class="wikitable"
{| class="wikitable"
Line 634: Line 829:
|}
|}


'''How ATR Trailing Works:'''
'''How It Works:'''


<pre>
<pre>
IF current ATR = 12 points:
Current ATR = 12 points
  Trailing Distance = 12 × 2 = 24 pts
Trailing Distance = 12 × 2 = 24 pts


IF price moves to 5540 (LONG from 5500):
Price at 5540 (LONG from 5500):
  New Stop = 5540 - 24 = 5516
New Stop = 5540 - 24 = 5516
  (Stop can only move UP, never back down)


IF volatility increases, ATR = 20:
Price at 5560:
  Trailing Distance = 20 × 2 = 40 pts (wider stop)
→ New Stop = 5560 - 24 = 5536 (moved UP)
  This prevents getting stopped out in volatile moves
 
Price reverses to 5536:
→ EXIT at 5536 = +36 pts PROFIT
→ Shows as "stop" exit but is profitable!
 
Key Rule: Stop can only move in profitable direction, NEVER back.
</pre>
</pre>


=== Stop Movement Flow (LONG Example) ===
=== Complete Stop Movement Example ===


<pre>
<pre>
Entry: 5500, Original Stop: 5460
LONG Entry: 5500
Original Stop: 5460 (-40 pts risk)
Target: 5560 (+60 pts)


Price hits 5520 (+20 pts):
Trade Progress:
├── Trailing activates
─────────────────────────────────────────────────
├── ATR = 15 pts → Trail distance = 30 pts
Price   Profit  Action                Stop Now
└── New stop = 5520 - 30 = 5490
─────────────────────────────────────────────────
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!          ---


Price hits 5525 (+25 pts):
OR if price reverses:
├── Breakeven activates
5540    +40      Trail at 5510        5510
└── Stop moves to max(5490, 5502) = 5502
5520    +20      Stop unchanged        5510
 
5510    +10      STOP HIT              EXIT +10 profit
Price hits 5560 (+60 pts):
─────────────────────────────────────────────────
├── Trail: 5560 - 30 = 5530
└── Stop is now 5530 (locked +30 pts profit!)
 
Price reverses to 5530:
└── EXIT via STOP at 5530 = +30 pts profit
    (Shows as "stop" exit but is profitable!)
</pre>
</pre>
{{Note|'''This explains why 72.3% of exits are "stop" but many are profitable trades!'''}}


----
----


== Take Profit: 60 Points (1.5:1 R:R) ==
== Take Profit: 60 Points ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Calculation !! Logic
! Calculation !! Value
|-
|-
| '''Primary''' || 50% of distance to MA21
| '''Primary''' || 50% of distance to MA21
Line 686: Line 885:
| '''Minimum''' || Risk × 1.5 = 40 × 1.5 = 60 pts
| '''Minimum''' || Risk × 1.5 = 40 × 1.5 = 60 pts
|-
|-
| '''Final Target''' || MAX(50% to MA, 60 pts) = Usually 60 pts
| '''Final''' || MAX(50% to MA, 60 pts) = Usually 60 pts
|}
|}


'''Why 60 pts:''' Since we enter NEAR the MA (within 25 pts), 50% of that distance is small. The minimum of 60 pts ensures favorable R:R.
'''Risk:Reward = 1.5:1'''
* Risk 40 pts to gain 60 pts
* Risk Rs 4,000 to gain Rs 6,000


----
----


== Timeout: 8 Hours Maximum ==
== Timeout: 8 Hours ==


* If trade doesn't hit stop or target within 8 hours
* If trade doesn't hit stop or target within 8 hours
* Exit at current market price
* Exit at current market price
* Prevents overnight holding
* Prevents overnight holding
* Used in 5% of trades (374 out of 7,534)


----
----


== Slippage Modeling ==
== Slippage Modeling ==
Realistic execution costs are modeled:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Slippage Added
! Exit Type !! Slippage
|-
|-
| Entry (base) || 1.0 points
| Entry (base) || +1.0 points
|-
|-
| Stop Loss exit || +2.0 points (worse fill in fast move)
| Stop Loss exit || +2.0 points (worse fill)
|-
|-
| Take Profit exit || +0.5 points (better fill, limit order)
| Take Profit exit || +0.5 points (limit order)
|-
|-
| Market Impact || Up to 2.0 points (capped)
| Market Impact || Up to 2.0 points (capped)
|}
|}
'''Example:'''
* Entry at 5500 → Actual fill: 5501 (+1 pt slippage)
* Stop at 5460 → Actual fill: 5458 (-2 pts slippage for LONG)
* Target at 5560 → Actual fill: 5559.5 (-0.5 pts slippage)


----
----


= PART 9: HOUR FILTER =
= PART 11: RISK MANAGEMENT =


== Blocked Trading Hours ==
== Position Sizing ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Hour !! IST Time !! Reason
! Parameter !! Value
|-
|-
| 9 || 9:00-10:00 AM || Market open volatility
| Position Size || 1 lot (100 barrels)
|-
| 22 || 10:00-11:00 PM || Late session
|-
| 23 || 11:00-11:30 PM || Market close
|}
 
== Allowed Trading Hours ==
 
Trading allowed: '''10 AM to 9 PM IST''' (Hours 10-21)
 
----
 
= PART 10: DIRECTION DETERMINATION =
 
== MA21 Slope Alignment (Hard Filter) ==
 
The primary direction filter:
 
{| class="wikitable"
|-
|-
! MA21 Slope !! Allowed Direction !! Logic
| Risk per Trade || 40 pts × Rs 100 = Rs 4,000
|-
| '''Rising''' (↗) || LONG only || Trade with uptrend
|-
|-
| '''Declining''' (↘) || SHORT only || Trade with downtrend
| Reward per Trade || 60 pts × Rs 100 = Rs 6,000
|-
|-
| '''Flat''' (→) || Use MTF direction || Let higher timeframes decide
| Max Concurrent || 1 trade at a time
|}
|}


== Direction Determination Algorithm ==
== Cost Structure ==
 
<source lang="python">
def determine_direction(ma21_slope, mtf_direction):
    if ma21_slope == "rising":
        return LONG  # Only longs in uptrend
 
    elif ma21_slope == "declining":
        return SHORT  # Only shorts in downtrend
 
    else:  # Flat
        return mtf_direction  # Use multi-timeframe consensus
</source>
 
----
 
= PART 11: RISK MANAGEMENT =
 
== Position Sizing ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Cost Type !! Value
|-
|-
| Position Size || 1 lot (100 barrels)
| Brokerage || Rs 20 per lot per leg (Dhan)
|-
|-
| Risk per Trade || 40 pts × 100 = Rs 4,000
| CTT || 0.01% on sell side
|-
|-
| Reward per Trade || 60 pts × 100 = Rs 6,000
| Total Round-trip || ~Rs 95 per trade
|-
|-
| Max Concurrent Trades || 1
| Total Costs (7,534 trades) || Rs 5.93 Lakhs
|}
|}


== Cost Structure ==
== Risk Metrics ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Cost Type !! Value
! Metric !! Value
|-
| Risk per Trade || Rs 4,000 (4% of initial capital)
|-
|-
| Brokerage || Rs 20 per lot per leg (Dhan)
| Risk:Reward || 1:1.5 (40:60)
|-
|-
| CTT || 0.01% on sell side
| Required Win Rate || 40% to break even
|-
|-
| Total Round-trip || ~Rs 95 per trade
| Actual Win Rate || 57.6% (profitable)
|}
|}


----
----


= PART 12: EQUITY CURVE =
= PART 12: SIGNAL GENERATION FLOW =


[[File:equity_curve.png|800px|center|Equity Curve]]
== Complete Pipeline ==
 
<pre>
┌─────────────────────────────────────────────────────────────────────────────┐
│                        SIGNAL GENERATION PIPELINE                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                            │
│  STEP 1: DATA COLLECTION                                                    │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ • Load OHLCV data for all 5 timeframes                              │  │
│  │ • Calculate MA21 and MA200 for each timeframe                      │  │
│  │ • Calculate ATR for volatility measurement                          │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 2: DIRECTION DETERMINATION (HARD FILTER #1)                          │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ • Calculate MA21 slope on 5-min chart                              │  │
│  │ • Rising slope → LONG only allowed                                  │  │
│  │ • Declining slope → SHORT only allowed                              │  │
│  │ • Flat slope → Use MTF direction                                    │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 3: HARD FILTER CHECKS                                                │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ □ Is price within ±25 pts of MA21?          → NO = SKIP            │  │
│  │ □ Is current hour allowed? (not 9,22,23)    → NO = SKIP            │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 4: MULTI-TIMEFRAME ANALYSIS                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ • Analyze trend direction in 5 timeframes                          │  │
│  │ • Calculate weighted alignment score                                │  │
│  │ • Output: 0.0 to 1.0 alignment score (30% of grade)                │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 5: MARKET STATE ANALYSIS                                            │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ • Railroad Trend Detection (+15 bonus)                              │  │
│  │ • Creeper Move Detection (-50 penalty)                              │  │
│  │ • Two-Day Trend Check (-30 if missing)                              │  │
│  │ • Trend Phase Classification (-25 if wrong)                        │  │
│  │ • Institutional Fight Detection (0.7x multiplier)                  │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 6: SETUP QUALITY GRADING                                            │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ • Calculate 5-factor weighted score                                  │  │
│  │ • Apply penalties and bonuses                                      │  │
│  │ • Assign grade: A+, A, B, C, D, F                                  │  │
│  │ • Grade < B (score < 70) → SKIP                                    │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                              ↓                                              │
│  STEP 7: SIGNAL OUTPUT                                                    │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │ • Direction: LONG or SHORT                                          │  │
│  │ • Entry Price: Current close                                        │  │
│  │ • Stop Loss: 40 points (or structure-based)                        │  │
│  │ • 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>


----
----


= PART 13: BACKTEST RESULTS (19 Months) =
= PART 13: BACKTEST RESULTS =


== Summary Statistics ==
== Summary Statistics ==
Line 825: Line 1,054:
! Metric !! Value
! Metric !! Value
|-
|-
| Initial Capital || Rs 1.00 Lakhs
| '''Period''' || 19 months
|-
| '''Initial Capital''' || Rs 1,00,000
|-
| '''Final Value''' || Rs 26,48,101
|-
|-
| Final Value || Rs 26.48 Lakhs
| '''Total Profit''' || Rs 25,48,101
|-
|-
| Total Profit || Rs 25.48 Lakhs
| '''Total Return''' || '''2,548%'''
|-
|-
| Total Return || '''2,548%'''
| '''Peak Value''' || Rs 28,35,039
|-
|-
| Peak Value || Rs 28.35 Lakhs
| '''Max Drawdown''' || -78.6%
|-
|-
| Max Drawdown || -78.6%
| '''Total Costs''' || Rs 5,93,160
|}
|}


Line 846: Line 1,079:
| Total Trades || 7,534
| Total Trades || 7,534
|-
|-
| Win Rate || 57.6%
| Winners || 4,338 (57.6%)
|-
| Losers || 3,196 (42.4%)
|-
|-
| Profit Factor || 1.20
| Profit Factor || 1.20
Line 865: Line 1,100:
{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Count !! % !! Note
! Exit Type !! Count !! % !! Notes
|-
|-
| Stop || 5,444 || 72.3% || Includes trailing stop profits
| '''Stop''' || 5,444 || 72.3% || Includes trailing stop profits!
|-
|-
| Target || 1,716 || 22.8% || 100% winners
| '''Target''' || 1,716 || 22.8% || 100% winners
|-
|-
| Timeout || 374 || 5.0% || 8-hour limit
| '''Timeout''' || 374 || 5.0% || 8-hour limit
|}
|}
<div style="background:#e6ffe6; border:1px solid #00cc00; padding:10px; margin:10px 0;">
'''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 ==
== Direction Distribution ==
Line 880: Line 1,125:
! Direction !! Count !! %
! Direction !! Count !! %
|-
|-
| SHORT || 6,024 || 80%
| '''SHORT''' || 6,024 || 80%
|-
|-
| LONG || 1,510 || 20%
| '''LONG''' || 1,510 || 20%
|}
|}
'''Why 80% SHORT?''' The market had a predominantly declining MA21 during the backtest period. The system correctly adapted to bearish conditions.


== Setup Quality Distribution ==
== Setup Quality Distribution ==
Line 895: Line 1,142:
| A || 551 || 7.3%
| A || 551 || 7.3%
|-
|-
| C || 3,526 || 46.8%
| C || 3,526 || 46.8% (analyzed but NOT traded)
|}
|}


''Note: C-grade trades were analyzed but NOT executed per strategy rules''
----
 
= 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.


= PART 14: HARD vs SOFT FILTERS =
# '''Trailing Explains Stops''' - 72% "stop" exits include profitable trailing stops.


Understanding which rules reject trades outright vs which just affect scoring:
----


== HARD FILTERS (Trade Rejected if Failed) ==
= APPENDIX A: CONFIGURATION VALUES =


These filters '''block trades entirely''' - no exceptions:
== Stop/Target Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Filter !! Rule !! Effect
! Parameter !! Value !! Source
|-
|-
| '''MA21 Slope Alignment''' || Direction must match MA21 slope || Rising MA = LONG only, Declining MA = SHORT only
| min_stop_distance || 40 points || signal_generation_trade_management.py
|-
|-
| '''Setup Grade''' || Must be A+, A, or B || C/D/F grades = NO TRADE
| default_stop_distance || 40 points || signal_generation_trade_management.py
|-
|-
| '''Hour Filter''' || Hours 9, 22, 23 blocked || Market open/close = NO TRADE
| default_risk_reward || 1.5 || signal_generation_trade_management.py
|-
|-
| '''Price in MA Zone''' || Must be within ±25 pts of MA21 || Too far from MA = NO TRADE
| min_target || risk × 1.5 = 60 pts || signal_generation_trade_management.py
|}
|}


== SOFT FILTERS (Affect Score, Don't Block) ==
== Trailing Stop Configuration ==
 
These filters '''affect the quality score''' but don't block trades:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Filter !! Effect on Score !! Can Still Pass?
! Parameter !! Value !! Source
|-
|-
| '''MTF Alignment''' || 30% weight in grading || Yes, if other factors strong
| enable_trailing_stop || True || trade_execution_engine.py
|-
|-
| '''Creeper Move''' || -50 penalty || Yes, if base score high enough
| trailing_stop_method || ATR_MULTIPLE || trade_execution_engine.py
|-
|-
| '''Railroad Trend''' || +15 bonus || N/A (bonus not required)
| atr_period || 14 bars || trade_execution_engine.py
|-
|-
| '''Price-MA Struggle''' || -30 penalty || Yes, if other factors compensate
| atr_multiplier || 2.0 || trade_execution_engine.py
|-
|-
| '''Wrong Trend Phase''' || -25 penalty || Yes, if other factors compensate
| trailing_stop_activation || 20 points || trade_execution_engine.py
|-
|-
| '''Key Level Proximity''' || 20% weight in grading || Yes, affects grade not rejection
| enable_breakeven_stop || True || trade_execution_engine.py
|-
|-
| '''Institutional Fight''' || 0.7x multiplier || Yes, reduces but doesn't block
| breakeven_activation || 25 points || trade_execution_engine.py
|-
| breakeven_buffer || 2 points || trade_execution_engine.py
|}
|}


== Filter Flow ==
== Grading Configuration ==


<pre>
{| class="wikitable"
ENTRY CANDIDATE
|-
      │
! Parameter !! Value !! Source
      ▼
|-
┌─────────────────────────────────────────┐
| timeframe_alignment_weight || 30% || setup_quality_detection.py
│  HARD FILTERS (any fail = NO TRADE)    │
|-
│  • MA21 slope alignment                │
| trend_strength_weight || 20% || setup_quality_detection.py
│  • Hour filter                          │
|-
│  • Price in MA zone                    │
| key_level_proximity_weight || 20% || setup_quality_detection.py
└─────────────────────────────────────────┘
|-
      │ ALL PASS
| entry_technique_weight || 15% || setup_quality_detection.py
      ▼
|-
┌─────────────────────────────────────────┐
| risk_reward_weight || 15% || setup_quality_detection.py
│  SOFT FILTERS (calculate score)        │
|}
│  • MTF alignment (30% weight)          │
│  • Trend strength (20% weight)          │
│  • Key level proximity (20% weight)    │
│  • Entry quality (15% weight)          │
│  • Risk/Reward (15% weight)            │
│  ± Penalties and Bonuses                │
└─────────────────────────────────────────┘
      │
      ▼
┌─────────────────────────────────────────┐
│  FINAL GRADE CHECK (HARD FILTER)        │
│  Score ≥ 70 = B or better = TRADE      │
│  Score < 70 = C or worse = NO TRADE    │
└─────────────────────────────────────────┘
</pre>
 
----
 
= PART 15: KEY STRATEGY PRINCIPLES =
 
# '''Trade WITH the trend''' - MA21 slope determines direction, never fight it
# '''Enter at value''' - Only when price is near MA21 zone (±25 pts)
# '''Quality over quantity''' - Only A+, A, B grade setups are traded
# '''Avoid creeper moves''' - -50 penalty ensures we skip poor quality price action
# '''Trade the MIDDLE''' - Focus on middle phase of trends, avoid early/late
# '''Dynamic stop management''' - Breakeven at 25 pts, trailing with ATR
# '''Time discipline''' - Maximum 8 hour holding period
# '''No overnight risk''' - All positions closed intraday
# '''Probability zones''' - Trade high probability zones only
# '''MTF as soft filter''' - Contributes to score, doesn't block alone


----
----


= APPENDIX: SOURCE CODE REFERENCE =
= APPENDIX B: SOURCE CODE REFERENCE =


{| class="wikitable"
{| class="wikitable"
Line 1,001: Line 1,236:
! File !! Purpose
! File !! Purpose
|-
|-
| <code>trend_analysis_core.py</code> || MA slope, trend direction, price-MA struggle
| <code>trend_analysis_core.py</code> || MA slope calculation, trend direction, price-MA struggle
|-
|-
| <code>multi_timeframe_analysis.py</code> || MTF alignment scoring (5 timeframes)
| <code>multi_timeframe_analysis.py</code> || MTF alignment scoring across 5 timeframes
|-
|-
| <code>market_state_analysis.py</code> || Market state detection (7 algorithms)
| <code>market_state_analysis.py</code> || 7 market state detection algorithms
|-
|-
| <code>setup_quality_detection.py</code> || 5-factor grading system
| <code>setup_quality_detection.py</code> || 5-factor grading system with penalties/bonuses
|-
|-
| <code>probability_zone_analysis.py</code> || Zone-based filtering, Three-Finger Spread
| <code>probability_zone_analysis.py</code> || Halves/Thirds, Three-Finger Spread, Crash Bar
|-
|-
| <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, Timeout
|-
| <code>data_manager.py</code> || OHLCV data loading and management
|}
|}


Line 1,024: Line 1,261:
[[Category:Trading Strategies]]
[[Category:Trading Strategies]]
[[Category:MCX Crude Oil]]
[[Category:MCX Crude Oil]]
[[Category:MA21 Mean Reversion]]
[[Category:Backtesting]]
[[Category:Backtesting]]

Revision as of 15:25, 5 January 2026

MA21 Mean Reversion Strategy

Complete Trading System Documentation

MCX Crude Oil - Intraday Trading System


PART 1: STRATEGY OVERVIEW

What Is This Strategy?

MA21 Mean Reversion - A systematic intraday trading strategy that enters when price pulls back to the 21-period Moving Average during established trends.

Instrument Details

Parameter Value
Instrument MCX Crude Oil Futures
Lot Size 100 barrels
Tick Value 1 point = Rs 100 per lot
Trading Hours 9:00 AM - 11:30 PM IST
Allowed Trading 10:00 AM - 9:00 PM IST (block open/close)

Timeframes Used

Timeframe Purpose
5-Minute Primary chart for signals and execution
1-Minute Entry precision timing
15-Min, 1H, 4H, Daily Multi-timeframe context (soft filter)

Backtest Results Summary

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%
Max Drawdown -78.6%

PART 2: THE EDGE (Core Concept)

The Big Idea

Trade pullbacks to the 21-period Moving Average (MA21) during established trends.

When the market is trending, price naturally pulls back to the 21 MA before continuing. We enter at these pullback zones, trading WITH the trend direction.

Why It Works

  1. Mean Reversion - Price tends to return to the average after moving away
  2. Trend Following - We only trade in the direction of the trend
  3. Value Entry - Entering on pullbacks gives better risk:reward
  4. Institutional Behavior - Big players accumulate at MA zones

The "MA is a 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
  • Gives room for entry without chasing
  • Accounts for spread and slippage
  • MCX Crude typical range: 50-100 pts/day

PART 3: DIRECTION DETERMINATION (The Foundation)

THIS IS THE MOST IMPORTANT RULE

The MA21 slope determines the ONLY direction you can trade. This is a HARD FILTER - no exceptions.

MA21 Slope = Trade Direction

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 Let higher timeframes decide

How Slope Is Calculated

Slope Value Classification Threshold
> +0.01% RISING Bullish - LONG only
< -0.01% DECLINING Bearish - SHORT only
Between ±0.01% FLAT Use MTF consensus

Why 80% of Trades Were SHORT

In our 19-month backtest:

  • 6,024 SHORT trades (80%)
  • 1,510 LONG trades (20%)

Reason: During the backtest period, MCX Crude Oil had a predominantly declining MA21 slope. The system correctly identified this bearish bias and took mostly short trades.

This is NOT a flaw - it shows the system adapts to market conditions.

Direction Determination Algorithm

<source lang="python"> 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

</source>


PART 4: ENTRY CONDITIONS (Gate Checks)

Overview: Hard vs Soft Filters

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

  • Must achieve grade A+, A, or B (score ≥ 70)
  • Grade C/D/F = not good enough quality
  • Fail = NO TRADE

SOFT FILTERS (Affect Score)

These filters affect the quality score but don't block trades:

Filter Effect Impact
MTF Alignment 30% weight in grading Low alignment = lower score
Creeper Move -50 penalty Can still pass if base high
Railroad Trend +15 bonus Quality boost
Price-MA Struggle -30 penalty Can still pass
Wrong Trend Phase -25 penalty Can still pass
Institutional Fight 0.7x multiplier Reduces but doesn't block

Filter Flow Diagram

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

PART 5: MULTI-TIMEFRAME (MTF) ANALYSIS

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.

Timeframe Hierarchy

We analyze 5 timeframes from highest to lowest:

Timeframe Purpose Weight
Daily (1D) Context/Bias Highest weight
4-Hour (4H) Primary Trend High weight
1-Hour (1H) Confirmation Medium weight
15-Min (15M) Entry Timing Lower weight
5-Min (5M) Execution Lowest weight

Per-Timeframe Analysis

For each timeframe, the Trend Analysis Core calculates:

1. Trend Direction

MA21 Slope Direction
> +0.01% UP
< -0.01% DOWN
Between ±0.01% SIDEWAYS
MA Slope Magnitude Status
> 0.05% TRENDING (MA is clearly moving)
< 0.05% FLAT (MA is consolidating)

3. Price-MA Struggle Detection

Condition Detection Impact
Price within 0.5% of MA21 for multiple bars STRUGGLING -30 penalty
Price clearly moving away from MA21 CLEAR TREND No penalty

Alignment Score Calculation

For each timeframe:
  - Check if direction matches expected direction
  - Assign weight based on timeframe importance

Alignment Score = Σ(Weight_i × Aligned_i) / Σ(Weight_i)

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)
        = 3.02 / 3.60 = 0.84 (84% alignment)

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.

Characteristic Threshold
Bar Analysis 5 most recent bars
Strong Bars 80%+ must close in same direction
Bar Body > 0.3% of price

Impact: +15 bonus to setup score


2. Creeper Move Detection

What: Slow, grinding price action with small bars.

Characteristic Threshold
Bar Range Average < 0.5% of price
Analysis Period Last 7 bars

Impact: -50 penalty to setup score (avoid these!)


3. Two-Day Trend Analysis

What: Trend must be visible on Daily for 2+ days.

Requirement Description
Daily Bars 2+ consecutive bars in same direction
Purpose Filters noise, ensures real trend

Impact: Missing = -30 penalty


4. Trend Phase Classification

Phase Bars into Trend Action Impact
EARLY 0-15 bars Avoid -25 penalty
MIDDLE 15-40 bars TARGET No penalty
LATE 40+ bars Avoid -25 penalty

5. Institutional Fight Detection

What: Big players battling each other.

Indicator Sign
Volume 1.5x+ average
Price Action Narrow range with high volume
Wicks Long wicks (rejection)

Impact: 0.7x multiplier on final score


6. Break of Structure (BOS)

What: Price breaking significant swing high/low.

BOS Type Description
SWING_HIGH_BREAK Price breaks above prior swing high
SWING_LOW_BREAK Price breaks below prior swing low
PDH_BREAK Previous Day High break
PDL_BREAK Previous Day Low break

7. Volatility Classification

Volatility ATR % of Price Adjustment
HIGH > 1.0% Wider stops needed
MEDIUM 0.3% - 1.0% Normal stops
LOW < 0.3% Tighter stops

PART 7: SETUP QUALITY GRADING

5-Factor Weighted Scoring

Every potential trade is scored on 5 factors:

Factor Weight What It Measures
Timeframe Alignment 30% How well all timeframes agree
Trend Strength 20% Quality of trend (railroad vs creeper)
Key Level Proximity 20% Is entry near significant level?
Entry Quality 15% Clean entry technique, near MA
Risk/Reward 15% How favorable is the R:R

Score Calculation

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

Penalties

Condition Penalty Reason
Creeper Move -50 Poor quality price action
MA Struggle -30 Price fighting the MA
No Two-Day Trend -30 Trend not established
Wrong Trend Phase -25 Not in MIDDLE phase
Far from Key Level -50 No confluence
Far from MA -40 Not a pullback entry

Bonuses

Condition Bonus Reason
Railroad Trend +15 High quality trend
At Key Level +10 Confluence present
Clean Entry +10 Clear technical setup

Grade Thresholds

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

To achieve A+ grade, ALL must be true:

  • Score ≥ 90
  • All timeframes aligned
  • Entry near MA21 (within ±25 pts)
  • Two-day trend present
  • No institutional fight

PART 8: ENTRY TECHNIQUES

Available Techniques

Universal (Both Directions)

Technique Description
NEAR_MA Entry when price is near MA21 zone (±25 pts)

Long-Specific

Technique Description
GREEN_BAR_AFTER_PULLBACK Green candle after pullback
MA_BOUNCE_LONG Bounce off MA21 in uptrend
BOS_ENTRY_LONG Entry after break of structure (upside)
BREAKOUT_PULLBACK_LONG Pullback after breakout
DISCOUNT_ZONE_LONG Buy in lower zone of range

Short-Specific

Technique Description
RED_BAR_AFTER_RALLY Red candle after rally
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

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

   # Most common: price near MA zone
   if abs(price - ma21) <= 25:
       return NEAR_MA
   # Break of structure detected
   elif has_bos:
       if direction == LONG:
           return BOS_ENTRY_LONG
       else:
           return BOS_ENTRY_SHORT
   # Pullback pattern detected
   elif has_pullback:
       if direction == LONG:
           return GREEN_BAR_AFTER_PULLBACK
       else:
           return RED_BAR_AFTER_RALLY
   # Default: MA bounce
   else:
       if direction == LONG:
           return MA_BOUNCE_LONG
       else:
           return MA_BOUNCE_SHORT

</source>


PART 9: PROBABILITY ZONES

Halves & Thirds Analysis

Based on price position within recent swing range:

Zone Position Continuation Probability
Top Third 67-100% 80% chance of new high
Top Half 50-67% 65% continuation
Bottom Half 33-50% 35% continuation
Bottom Third 0-33% 15% (85% likely lower)

Zone-Based Trading Rules

Zone LONG SHORT
Top Third Allowed (after pullback) Blocked
Bottom Third Blocked Allowed (after rally)

Sideways Market

Zone LONG SHORT
Top Third Blocked (overextended) Allowed
Bottom Third Allowed Blocked

Three-Finger Spread

What: Large separation between Price, MA21, and MA200.

Detection:
- Distance(Price to MA21) > 2% of price
- AND Distance(MA21 to MA200) > 2% of price

Impact: Expect profit-taking soon (bearish for longs, bullish for shorts)

Crash Bar Detection

What: Abnormally large bar indicating structural break.

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


PART 10: EXIT MANAGEMENT

Overview

Exit Type Trigger Typical Result
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

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

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

DYNAMIC STOP MANAGEMENT

IMPORTANT: Stop loss is NOT static! It moves dynamically to lock in profits.

This explains why 72.3% of exits are "stop" but many are profitable trades!

Phase 1: Breakeven Stop

Trigger: When trade reaches 25 points profit

Parameter Value
Activation 25 points in profit
New Stop Entry price + 2 pts buffer
Purpose Eliminate loss, lock small profit

Example (LONG at 5500):

Entry: 5500
Original Stop: 5460 (40 pts risk)

Price reaches 5525 (+25 pts profit):
→ Stop moves from 5460 to 5502 (entry + 2 buffer)
→ Worst case now = +2 pts profit (NOT -40 loss!)

Phase 2: Trailing Stop (ATR-Based)

Trigger: When trade reaches 20 points profit

Parameter Value
Method ATR_MULTIPLE (adapts to volatility)
ATR Period 14 bars
ATR Multiplier 2.0
Trailing Distance ATR × 2 (dynamic)
Minimum Distance 15 points
Activation 20 points in profit

How It Works:

Current ATR = 12 points
Trailing Distance = 12 × 2 = 24 pts

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:
→ EXIT at 5536 = +36 pts PROFIT
→ Shows as "stop" exit but is profitable!

Key Rule: Stop can only move in profitable direction, NEVER back.

Complete Stop Movement Example

LONG Entry: 5500
Original Stop: 5460 (-40 pts risk)
Target: 5560 (+60 pts)

Trade Progress:
─────────────────────────────────────────────────
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:
5540     +40      Trail at 5510         5510
5520     +20      Stop unchanged        5510
5510     +10      STOP HIT              EXIT +10 profit
─────────────────────────────────────────────────

Take Profit: 60 Points

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

Exit Type Slippage
Entry (base) +1.0 points
Stop Loss exit +2.0 points (worse fill)
Take Profit exit +0.5 points (limit order)
Market Impact Up to 2.0 points (capped)

PART 11: RISK MANAGEMENT

Position Sizing

Parameter Value
Position Size 1 lot (100 barrels)
Risk per Trade 40 pts × Rs 100 = Rs 4,000
Reward per Trade 60 pts × Rs 100 = Rs 6,000
Max Concurrent 1 trade at a time

Cost Structure

Cost Type Value
Brokerage Rs 20 per lot per leg (Dhan)
CTT 0.01% on sell side
Total Round-trip ~Rs 95 per trade
Total Costs (7,534 trades) Rs 5.93 Lakhs

Risk Metrics

Metric Value
Risk per Trade Rs 4,000 (4% of initial capital)
Risk:Reward 1:1.5 (40:60)
Required Win Rate 40% to break even
Actual Win Rate 57.6% (profitable)

PART 12: SIGNAL GENERATION FLOW

Complete Pipeline

┌─────────────────────────────────────────────────────────────────────────────┐
│                         SIGNAL GENERATION PIPELINE                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  STEP 1: DATA COLLECTION                                                    │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │ • Load OHLCV data for all 5 timeframes                              │   │
│  │ • Calculate MA21 and MA200 for each timeframe                       │   │
│  │ • Calculate ATR for volatility measurement                          │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                              ↓                                              │
│  STEP 2: DIRECTION DETERMINATION (HARD FILTER #1)                          │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │ • Calculate MA21 slope on 5-min chart                               │   │
│  │ • Rising slope → LONG only allowed                                  │   │
│  │ • Declining slope → SHORT only allowed                              │   │
│  │ • Flat slope → Use MTF direction                                    │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                              ↓                                              │
│  STEP 3: HARD FILTER CHECKS                                                │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │ □ Is price within ±25 pts of MA21?          → NO = SKIP             │   │
│  │ □ Is current hour allowed? (not 9,22,23)    → NO = SKIP             │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                              ↓                                              │
│  STEP 4: MULTI-TIMEFRAME ANALYSIS                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │ • Analyze trend direction in 5 timeframes                           │   │
│  │ • Calculate weighted alignment score                                │   │
│  │ • Output: 0.0 to 1.0 alignment score (30% of grade)                │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                              ↓                                              │
│  STEP 5: MARKET STATE ANALYSIS                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │ • Railroad Trend Detection (+15 bonus)                              │   │
│  │ • Creeper Move Detection (-50 penalty)                              │   │
│  │ • Two-Day Trend Check (-30 if missing)                              │   │
│  │ • Trend Phase Classification (-25 if wrong)                         │   │
│  │ • Institutional Fight Detection (0.7x multiplier)                   │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                              ↓                                              │
│  STEP 6: SETUP QUALITY GRADING                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │ • Calculate 5-factor weighted score                                  │   │
│  │ • Apply penalties and bonuses                                       │   │
│  │ • Assign grade: A+, A, B, C, D, F                                   │   │
│  │ • Grade < B (score < 70) → SKIP                                     │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                              ↓                                              │
│  STEP 7: SIGNAL OUTPUT                                                     │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │ • Direction: LONG or SHORT                                          │   │
│  │ • Entry Price: Current close                                        │   │
│  │ • Stop Loss: 40 points (or structure-based)                         │   │
│  │ • 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                            │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

PART 13: BACKTEST RESULTS

Summary Statistics

Metric Value
Period 19 months
Initial Capital Rs 1,00,000
Final Value Rs 26,48,101
Total Profit Rs 25,48,101
Total Return 2,548%
Peak Value Rs 28,35,039
Max Drawdown -78.6%
Total Costs Rs 5,93,160

Trade Statistics

Metric Value
Total Trades 7,534
Winners 4,338 (57.6%)
Losers 3,196 (42.4%)
Profit Factor 1.20
Average Win Rs 3,464
Average Loss Rs 3,904
Largest Win Rs 26,799
Largest Loss Rs 13,217
Avg Holding Time 2.4 hours

Exit Reason Breakdown

Exit Type Count % Notes
Stop 5,444 72.3% Includes trailing stop profits!
Target 1,716 22.8% 100% winners
Timeout 374 5.0% 8-hour limit

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.

Direction Distribution

Direction Count %
SHORT 6,024 80%
LONG 1,510 20%

Why 80% SHORT? The market had a predominantly declining MA21 during the backtest period. The system correctly adapted to bearish conditions.

Setup Quality Distribution

Grade Count %
A+ 3,457 45.9%
A 551 7.3%
C 3,526 46.8% (analyzed but NOT traded)

PART 14: KEY STRATEGY PRINCIPLES

  1. MA21 Slope = Direction - The primary hard filter. Rising MA = LONG only, Declining MA = SHORT only.
  1. MA is a ZONE - Enter within ±25 pts of MA21, not just at exact value.
  1. Quality over Quantity - Only trade A+, A, B grades (score ≥ 70).
  1. Avoid Creeper Moves - -50 penalty ensures we skip low-quality price action.
  1. Trade the MIDDLE - Focus on middle phase of trends (bars 15-40).
  1. Dynamic Stop Management - Breakeven at 25 pts, trailing with ATR×2.
  1. 1.5:1 Risk:Reward - Risk 40 pts to gain 60 pts.
  1. Time Discipline - Maximum 8-hour holding, no overnight.
  1. MTF as Soft Filter - Contributes to score (30%) but doesn't block alone.
  1. Trailing Explains Stops - 72% "stop" exits include profitable trailing stops.

APPENDIX A: CONFIGURATION VALUES

Stop/Target Configuration

Parameter Value Source
min_stop_distance 40 points signal_generation_trade_management.py
default_stop_distance 40 points signal_generation_trade_management.py
default_risk_reward 1.5 signal_generation_trade_management.py
min_target risk × 1.5 = 60 pts signal_generation_trade_management.py

Trailing Stop Configuration

Parameter Value Source
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
breakeven_activation 25 points trade_execution_engine.py
breakeven_buffer 2 points trade_execution_engine.py

Grading Configuration

Parameter Value Source
timeframe_alignment_weight 30% setup_quality_detection.py
trend_strength_weight 20% setup_quality_detection.py
key_level_proximity_weight 20% setup_quality_detection.py
entry_technique_weight 15% setup_quality_detection.py
risk_reward_weight 15% setup_quality_detection.py

APPENDIX B: SOURCE CODE REFERENCE

File Purpose
trend_analysis_core.py MA slope calculation, trend direction, price-MA struggle
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, Timeout
data_manager.py OHLCV data loading and management

Document generated from code analysis - January 2026

All rules extracted directly from source code implementation