Jump to content

Alpha Research: Difference between revisions

From PlusEV Wiki Page
No edit summary
No edit summary
 
(90 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= MA21 Mean Reversion Strategy =
= Multi_Timeframe Dynamic Trend (MTFDR) =
----
 
= PART 1: STRATEGY OVERVIEW =
= PART 1: STRATEGY OVERVIEW =


== What Is This Strategy? ==
== 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.
'''Multi_Timeframe Dynamic Trend(MTFDR)''' is a systematic intraday trading strategy that requires multiple analytical layers to align before taking a trade. Each layer must be present for a valid setup. Market behavior is probabilistic, not predictive. The goal is positioning with asymmetric probabilities, not prediction.
 
== Layered Architecture (Top-Down) ==
 
<pre>
┌─────────────────────────────────────────────────────────────┐
│                                                            │
│  LAYER 1: MULTI-TIMEFRAME ANALYSIS  - FOUNDATION LAYER    │
│  5 timeframes analyzed for trend alignment                │ context
│  Daily → 4H → 1H → 15M → 5M                              │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 2: MARKET STATE ANALYSIS                          │  ← regime/ market state conditions
│  7 algorithms: Railroad, Creeper, Phase, BOS, etc.         │
│  Calculates penalties and bonuses                          │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 3: SETUP QUALITY GRADING                          │  ←  set up scoring
│  5-factor weighted scoring → Assigns grade A+ to F        │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 4: FILTERS (Trade/No_Trade)                        │
│  • Direction: MA21 slope must match trade direction        │Filters
│  • Grade: Only A+, A, B grades can trade                  │
│  • Hours: Block hours ]WIP]                              │
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  LAYER 5: ENTRY TECHNIQUES                                │  ← Final trigger
│                                                            │
│                                                            │
└─────────────────────────────────────────────────────────────┘
</pre>
 
= PART 2: Core Concept (Why This Works) =


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


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Layer !! What It Filters Out
|-
| '''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)
| 1. MTF Analysis || Counter-trend trades, choppy markets
|}
 
== Timeframes Used ==
 
{| class="wikitable"
|-
|-
! Timeframe !! Purpose
| 2. Market State || Dangerous conditions (creeper moves, institutional fights)
|-
|-
| '''5-Minute''' || Primary chart for signals and execution
| 3. Quality Grading || Scores the setup (used by hard filter)
|-
|-
| '''1-Minute''' || Entry precision timing
| 4. Hard Filters || Wrong direction, low grades (C/D/F), blocked hours
|-
|-
| '''15-Min, 1H, 4H, Daily''' || Multi-timeframe context (soft filter)
| 5. Entry Technique || Chasing price far from value areas
|}
|}


= PART 2: THE EDGE (Core Concept) =
== The Math ==
 
== The Big Idea ==


'''Trade pullbacks to the 21-period Moving Average (MA21) during established trends.'''
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


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.
'''Result:''' Fewer trades, but each trade has multiple confluences supporting it.
 
== 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 3: DIRECTION DETERMINATION (The Foundation) =
= PART 3: LAYER 1 - MULTI-TIMEFRAME ANALYSIS (The Foundation) =


<div style="background:#ffcccc; border:2px solid #cc0000; padding:10px; margin:10px 0;">
<div style="background:#e6ffe6; border:1px solid #00cc00; padding:10px; margin:10px 0;">
'''THIS IS THE MOST IMPORTANT RULE'''
'''THIS IS THE FOUNDATION''' - Everything else builds on top of MTF alignment. If timeframes disagree, we don't trade.
 
The MA21 slope determines the ONLY direction you can trade. This is a '''HARD FILTER''' - no exceptions.
</div>
</div>


== MA21 Slope = Trade Direction ==
== The 5 Timeframes ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA21 Slope !! Allowed Direction !! Logic
! Timeframe !! Role !! Weight
|-
| '''Daily (1D)''' || Overall market bias || Highest
|-
| '''4-Hour (4H)''' || Primary trend direction || High
|-
|-
| '''Rising''' (↗) || '''LONG only''' || Trade with uptrend, never short
| '''1-Hour (1H)''' || Trend confirmation || Medium
|-
|-
| '''Declining''' (↘) || '''SHORT only''' || Trade with downtrend, never long
| '''15-Minute (15M)''' || Entry timing context || Lower
|-
|-
| '''Flat''' (→) || Use MTF direction || Let higher timeframes decide
| '''5-Minute (5M)''' || Execution timeframe || Lowest
|}
|}


== How Slope Is Calculated ==
== What We Analyze Per Timeframe ==
 
For each of 5 timeframes, our system calculates:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Slope Value !! Classification !! Threshold
! Analysis !! Description
|-
|-
| > +0.01% || RISING || Bullish - LONG only
| '''MA21 Value''' || 21-period Moving Average
|-
|-
| < -0.01% || DECLINING || Bearish - SHORT only
| '''MA21 Slope''' || Rising/Flat/Declining
|-
|-
| Between ±0.01% || FLAT || Use MTF consensus
| '''MA200 Value''' || 200-period Moving Average
|-
| '''Price vs MA21''' || Above/Below/At the MA
|-
| '''Trend Direction''' || UP/DOWN/NEUTRAL
|}
|}


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


In our 19-month backtest:
<pre>
* '''6,024 SHORT trades (80%)'''
For each timeframe:
* '''1,510 LONG trades (20%)'''
  1. Determine trend direction (UP/DOWN/NEUTRAL)
  2. Check if aligned with trade direction
  3. Apply timeframe weight
  4. Sum weighted alignment scores


'''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.
Example (LONG trade):
 
  Daily:  UP (aligned)    × 1.00 weight = 1.00
This is NOT a flaw - it shows the system adapts to market conditions.
  4H:    UP (aligned)    × 0.86 weight = 0.86
 
  1H:     UP (aligned)     × 0.72 weight = 0.72
== Direction Determination Algorithm ==
  15M:   DOWN (not aligned) × 0.58 weight = 0.00
 
  5M:    UP (aligned)     × 0.44 weight = 0.44
<source lang="python">
  ─────────────────────────────────────────────
def determine_direction(ma21_slope, mtf_direction):
  Total MTF Score: 3.02 / 3.60 = 83.9% aligned
     """
</pre>
    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 ==
== Why MTF Matters ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Filter Type !! Behavior !! Examples
! Scenario !! MTF Alignment !! Action
|-
| All 5 timeframes aligned || ~90% || '''High conviction trade A+ 2lots'''
|-
| 4 of 5 aligned || ~80% || Trade with normal size A 1 lot
|-
|-
| '''HARD''' || Must pass ALL or NO TRADE || MA21 slope, hour filter, price in zone, grade
| 3 of 5 aligned || ~70% || Proceed with caution B 1 lot
|-
|-
| '''SOFT''' || Affects score but doesn't block || MTF alignment, market state, penalties
| 2 or fewer aligned || <60% || '''No Trade'''
|}
|}


== HARD FILTERS (Must Pass ALL) ==
----
 
These filters '''block trades entirely''' if any one fails:


=== 1. MA21 Slope Alignment ===
= PART 4: LAYER 2 - MARKET STATE ANALYSIS =
* Direction MUST match MA21 slope
* Rising MA = LONG only
* Declining MA = SHORT only
* '''Fail = NO TRADE'''


=== 2. Price in MA Zone ===
== The 7 Market State Algorithms ==
* Price must be within '''±25 points''' of MA21
* Too far above/below = not a pullback entry
* '''Fail = NO TRADE'''


=== 3. Hour Filter ===
Our system runs 7 independent algorithms to understand current market context:
* 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:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Filter !! Effect !! Impact
! # !! Algorithm !! What It Detects !! Impact
|-
| 1 || '''Railroad Tracks''' || Strong momentum bars in sequence || +15% bonus
|-
|-
| MTF Alignment || 30% weight in grading || Low alignment = lower score
| 2 || '''Creeper Move''' || Slow grinding trend (dangerous) || '''-50% penalty'''
|-
|-
| Creeper Move || -50 penalty || Can still pass if base high
| 3 || '''Two-Day Trend''' || Trend visible on Daily for 2+ days || Required for A+
|-
|-
| Railroad Trend || +15 bonus || Quality boost
| 4 || '''Phase Analysis''' || Accumulation/Distribution/Markup/Markdown || Phase mismatch = -25%
|-
|-
| Price-MA Struggle || -30 penalty || Can still pass
| 5 || '''Institutional Activity''' || Big player accumulation/distribution || Fight = 0.7× multiplier
|-
|-
| Wrong Trend Phase || -25 penalty || Can still pass
| 6 || '''Break of Structure (BOS)''' || Key level breaks || Affects stop placement
|-
|-
| Institutional Fight || 0.7x multiplier || Reduces but doesn't block
| 7 || '''Volatility Regime''' || High/Normal/Low volatility || Adjusts expectations
|}
|}


== Filter Flow Diagram ==
== Penalty System ==
 
<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 ==
 
We analyze '''5 timeframes''' from highest to lowest:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Timeframe !! Purpose !! Weight
! Condition !! Penalty !! Rationale
|-
|-
| '''Daily (1D)''' || Context/Bias || Highest weight
| Creeper Move Detected || '''-50 points''' || Slow trends often reverse suddenly
|-
|-
| '''4-Hour (4H)''' || Primary Trend || High weight
| MA Struggle (price fighting MA) || -30 points || Indecision, likely to chop
|-
|-
| '''1-Hour (1H)''' || Confirmation || Medium weight
| No Two-Day Trend || -30 points || Trend not established enough
|-
|-
| '''15-Min (15M)''' || Entry Timing || Lower weight
| Phase Mismatch || -25 points || Trading against market phase
|-
|-
| '''5-Min (5M)''' || Execution || Lowest weight
| No Key Level Nearby || -50 points || No technical confluence
|-
| Institutional Fight || '''×0.70 multiplier''' || Big players fighting each other
|}
|}


== Per-Timeframe Analysis ==
== Bonus System ==
 
For each timeframe, the '''Trend Analysis Core''' calculates:
 
=== 1. Trend Direction ===


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA21 Slope !! Direction
! Condition !! Bonus !! Rationale
|-
|-
| > +0.01% || UP
| Railroad Tracks || '''+15 points''' || Strong momentum confirmation
|-
|-
| < -0.01% || DOWN
| At Key Level || +10 points || Technical confluence present
|-
|-
| Between ±0.01% || SIDEWAYS
| Clean Entry Setup || +10 points || Clear technical pattern
|}
|}


=== 2. MA Trending Status ===
== Probability Zone Analysis ==
 
=== The Asymmetric Probability Edge ===
 
When odds are low on one outcome, '''the opposite side usually carries high odds''':
* If new high probability drops to 15%, then '''85% odds favor reversal'''
* We position ourselves on high-probability side where price position within recent range determines continuation probability:
* Every large move is divided into '''halves and thirds''', creating probability zones.
=== Odds of Continuation After Pullback ===
<pre>
┌─────────────────────────────────────────────────────┐
│  SWING HIGH                                        │
├─────────────────────────────────────────────────────┤
│  TOP THIRD        →  ~80% chance of new high        │ 
├─────────────────────────────────────────────────────┤
│  TOP HALF        →  ~66% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM HALF      →  ~33% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM THIRD    →  ~15% chance of new high        │ 
├─────────────────────────────────────────────────────┤
│  SWING LOW                                          │
└─────────────────────────────────────────────────────┘
</pre>


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA Slope Magnitude !! Status
! Zone !! Position !! Continuation Probability !! Action
|-
|-
| > 0.05% || TRENDING (MA is clearly moving)
| '''Top Third''' || >66.6% of range || '''80%''' likely to continue higher || Favor LONG
|-
|-
| < 0.05% || FLAT (MA is consolidating)
| '''Top Half''' || >50% of range || '''65%''' continuation || Moderate LONG bias
|}
 
=== 3. Price-MA Struggle Detection ===
 
{| class="wikitable"
|-
! Condition !! Detection !! Impact
|-
|-
| Price within 0.5% of MA21 for multiple bars || STRUGGLING || -30 penalty
| '''Bottom Half''' || <50% of range || '''35%''' continuation higher || Moderate SHORT bias
|-
|-
| Price clearly moving away from MA21 || CLEAR TREND || No penalty
| '''Bottom Third''' || <33.3% of range || '''15%''' continuation ('''85% reversal''') || Favor SHORT
|}
|}


== Alignment Score Calculation ==
=== 3-Finger Spread ===
 
Measures separation between Price, 21 MA, and 200 MA:


<pre>
<pre>
For each timeframe:
Three-Finger Spread Detection:
   - Check if direction matches expected direction
   - Large spread between Price/21MA/200MA
   - Assign weight based on timeframe importance
  - Indicates profit-taking pressure imminent
   - Minimum spread threshold: 2% of price


Alignment Score = Σ(Weight_i × Aligned_i) / Σ(Weight_i)
Structure Types:
 
   UPTREND:   Price > 21 MA > 200 MA (bullish stack)
Example:
   DOWNTREND: Price < 21 MA < 200 MA (bearish stack)
  Daily: UP (aligned) × 1.0 weight = 1.0
   SIDEWAYSNo clear MA separation
   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)
</pre>
</pre>


----
=== Crash Bar Detection ===
 
= PART 6: MARKET STATE DETECTION =


The system detects '''7 market state patterns''' that affect setup quality:
Identifies structural breaks via unusually large bars:
 
== 1. Railroad Trend Detection ==
 
'''What:''' Strong, consistent trend with minimal pullbacks.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Threshold
! Parameter !! Value !! Meaning
|-
|-
| Bar Analysis || 5 most recent bars
| crash_bar_multiplier || 2.0 || Bar must be 2× average size
|-
|-
| Strong Bars || 80%+ must close in same direction
| crash_bar_lookback || 10 bars || Average calculated over 10 bars
|-
|-
| Bar Body || > 0.3% of price
| crash_bar_close_threshold || 30% || Close within 30% of bar extreme
|}
|}


'''Impact:''' '''+15 bonus''' to setup score
=== Pullback Classification ===
 
----
 
== 2. Creeper Move Detection ==
 
'''What:''' Slow, grinding price action with small bars.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Threshold
! Type !! Characteristics !! Action
|-
|-
| Bar Range || Average < 0.5% of price
| '''Healthy Pullback''' || 45° drift, holds above halfway point || Good entry opportunity
|-
|-
| Analysis Period || Last 7 bars
| '''Collapse''' || Vertical drop (>60% retracement) || Avoid entry, wait for structure
|-
| '''Bounce''' || Recovery after crash bar || Short opportunity
|}
|}


'''Impact:''' '''-50 penalty''' to setup score (avoid these!)
=== Signal Filtering ===


----
Probability zones filter signals:


== 3. Two-Day Trend Analysis ==
# Zone-based filtering (soft filter - affects score, doesn't block)


'''What:''' Trend must be visible on Daily for 2+ days.
if zone_position < 33.3%: # Bottom third
    # Block LONG signals (only 15% chance of continuation)
    # Allow SHORT signals


{| class="wikitable"
if zone_position > 66.7%:  # Top third
|-
    # Allow LONG signals (80% continuation)
! Requirement !! Description
    # Block SHORT signals
|-
| Daily Bars || 2+ consecutive bars in same direction
|-
| Purpose || Filters noise, ensures real trend
|}


'''Impact:''' Missing = '''-30 penalty'''
= PART 5: LAYER 3 - SETUP QUALITY GRADING =


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


== 4. Trend Phase Classification ==
Every potential trade is scored on 5 factors:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Phase !! Bars into Trend !! Action !! Impact
! Factor !! Weight !! What It Measures
|-
|-
| '''EARLY''' || 0-15 bars || Avoid || -25 penalty
| '''Timeframe Alignment''' || '''30%''' || How well all 5 timeframes agree
|-
|-
| '''MIDDLE''' || 15-40 bars || '''TARGET''' || No penalty
| '''Trend Strength''' || '''20%''' || Quality of the trend (Railroad vs Creeper)
|-
|-
| '''LATE''' || 40+ bars || Avoid || -25 penalty
| '''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?
|}
|}


----
<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>


== 5. Institutional Fight Detection ==
== Grade Thresholds ==
 
'''What:''' Big players battling each other.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Indicator !! Sign
! Grade !! Score Range !! Action !! Position Size
|-
|-
| Volume || 1.5x+ average
| '''A+''' || 90-100 || Trade with full conviction || 2 lots
|-
|-
| Price Action || Narrow range with high volume
| '''A''' || 80-89 || Trade with confidence || 1 lot
|-
|-
| Wicks || Long wicks (rejection)
| '''B''' || 70-79 || Trade normally || 1 lot
|-
| '''C''' || 60-69 || '''NO TRADE''' || -
|-
| '''D''' || 50-59 || '''NO TRADE''' || -
|-
| '''F''' || <50 || '''NO TRADE''' || -
|}
|}


'''Impact:''' '''0.7x multiplier''' on final score
== 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


== 6. Break of Structure (BOS) ==
== Score Calculation Example ==


'''What:''' Price breaking significant swing high/low.
<pre>
 
Trade Setup: LONG on 5-min chart
{| class="wikitable"
|-
! 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
|}


----
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


== 7. Volatility Classification ==
Penalties Applied:
 
  - No Railroad Tracks: 0
{| class="wikitable"
  - No Creeper: 0
|-
  - Has Two-Day: 0
! Volatility !! ATR % of Price !! Adjustment
                              ──────────
|-
  Final Score: 80.75 → Grade: A
| HIGH || > 1.0% || Wider stops needed
</pre>
|-
| MEDIUM || 0.3% - 1.0% || Normal stops
|-
| LOW || < 0.3% || Tighter stops
|}


----
----


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


== 5-Factor Weighted Scoring ==
<div style="background:#ffe6e6; border:1px solid #ff0000; padding:10px; margin:10px 0;">
'''HARD FILTERS''' block trades completely. If ANY hard filter fails, NO TRADE happens regardless of how good the setup looks.
</div>


Every potential trade is scored on 5 factors:
== 3 Hard Filters ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Factor !! Weight !! What It Measures
! Filter !! Rule !! Effect
|-
| '''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?
| '''1. Direction Filter''' || MA21 slope must match trade direction || Wrong direction = BLOCKED
|-
|-
| '''Entry Quality''' || 15% || Clean entry technique, near MA
| '''2. Grade Filter''' || Only A+, A, B grades allowed || C/D/F grades = BLOCKED
|-
|-
| '''Risk/Reward''' || 15% || How favorable is the R:R
| '''3. Hour Filter''' || Block hours [WIP] || Blocked hours = BLOCKED
|}
|}


== Score Calculation ==
== Filter 1: Direction (MA21 Slope) ==
 
<pre>
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
! MA21 Slope !! Allowed Direction !! Logic
|-
| 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
| '''Rising''' (↗) || LONG only || Trade with uptrend, never short
|-
|-
| Far from Key Level || '''-50''' || No confluence
| '''Declining''' (↘) || SHORT only || Trade with downtrend, never long
|-
|-
| Far from MA || '''-40''' || Not a pullback entry
| '''Flat''' (→) || Use MTF direction || Higher timeframes decide
|}
|}


== Bonuses ==
== Filter 2: Grade ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Condition !! Bonus !! Reason
! Grade !! Action
|-
|-
| Railroad Trend || '''+15''' || High quality trend
| A+, A, B || '''PASS''' - Proceed to entry
|-
|-
| At Key Level || '''+10''' || Confluence present
| C, D, F || '''BLOCKED''' - No trade
|-
| Clean Entry || '''+10''' || Clear technical setup
|}
|}


== Grade Thresholds ==
== Filter 3: Hour [work in progress examples] ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Grade !! Min Score !! Action
! Hour !! Status !! Reason
|-
|-
| '''A+''' || 90+ || Trade with full conviction
| 9 (9:00-9:59 AM) || '''BLOCKED''' || Market open volatility
|-
|-
| '''A''' || 80-89 || Trade with confidence
| 10-21 (10:00 AM - 9:59 PM) || '''ALLOWED''' || Normal trading hours
|-
|-
| '''B''' || 70-79 || Trade normally
| 22 (10:00-10:59 PM) || '''BLOCKED''' || Near market close
|-
|-
| '''C''' || 60-69 || '''NO TRADE'''
| 23 (11:00-11:59 PM) || '''BLOCKED''' || Market close
|-
| '''D''' || 50-59 || '''NO TRADE'''
|-
| '''F''' || <50 || '''NO TRADE'''
|}
|}


== A+ Special Requirements ==
= PART 7: LAYER 5 - ENTRY TECHNIQUE =


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


----
<blockquote>
'''"The MA is a ZONE, not a thin line or exact value"'''


= PART 8: ENTRY TECHNIQUES =
Entry is allowed within '''±25 points''' of MA21, not just at the exact MA value.
</blockquote>


== Available Techniques ==
== Why ±25 Points? ==


=== Universal (Both Directions) ===
* Price rarely touches MA exactly
* Allows for normal market noise
 
== Entry Techniques ==


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


=== Short-Specific ===
= PART 8: STOP LOSS CALCULATION =
 
== Stop Loss Methods (Priority Order) ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Technique !! Description
! Priority !! Method !! Description
|-
|-
| RED_BAR_AFTER_RALLY || Red candle after rally
| 1 || '''BOS-Based Stop''' || Below/above break of structure level
|-
|-
| MA_BOUNCE_SHORT || Rejection from MA21 in downtrend
| 2 || '''Swing-Based Stop''' || Below recent swing low (LONG) or above swing high (SHORT)
|-
|-
| BOS_ENTRY_SHORT || Entry after break of structure (downside)
| 3 || '''Default Stop''' || Fixed 40 points from entry
|-
| BREAKOUT_PULLBACK_SHORT || Pullback after breakdown
|-
| PREMIUM_ZONE_SHORT || Sell in upper zone of range
|}
|}


== Selection Logic ==
== Minimum Stop Distance ==
 
<div style="background:#ffffcc; border:1px solid #ffcc00; padding:10px; margin:10px 0;">
'''MINIMUM: 40 points'''
</div>
 
This prevents:
* Getting stopped out by normal noise
* Excessive trading costs from tight stops
* Whipsaws in market manipulations, this varies depending on markets, nature of that trade
 
= PART 9: TARGET CALCULATION =
 
== The 50% Rule ==
 
<div style="background:#e6f3ff; border:1px solid #3399ff; padding:10px; margin:10px 0;">
'''Target = 50% of distance to MA21'''


<source lang="python">
For mean reversion trades, we target halfway back to moving average.
def select_entry_technique(price, ma21, direction, has_bos, has_pullback):
</div>
    # Most common: price near MA zone
    if abs(price - ma21) <= 25:
        return NEAR_MA


    # Break of structure detected
== Why 50%? ==
    elif has_bos:
        if direction == LONG:
            return BOS_ENTRY_LONG
        else:
            return BOS_ENTRY_SHORT


    # Pullback pattern detected
* Conservative target ensures higher hit rate
    elif has_pullback:
* Based on "divide the move in half" principle
        if direction == LONG:
* Captures partial reversion without being greedy
            return GREEN_BAR_AFTER_PULLBACK
* Works well with trailing stop to capture more
        else:
            return RED_BAR_AFTER_RALLY


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


----
<pre>
Minimum Target = Risk × 1.5


= PART 9: PROBABILITY ZONES =
Example:
  Entry: 5700
  Stop: 5660 (40 points risk)


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


Based on price position within recent swing range:
  Final Target: 5760 (60 points)
</pre>


{| class="wikitable"
= PART 10: DYNAMIC STOP MANAGEMENT =
|-
! 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 ==
== Two-Phase Protection ==


=== Trending Market ===
After entry, stops are managed dynamically in two phases:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Zone !! LONG !! SHORT
! Phase !! Trigger !! Action
|-
|-
| Top Third || Allowed (after pullback) || Blocked
| '''Phase 1: Breakeven''' || +25 points profit || Move stop to entry + 2 points
|-
|-
| Bottom Third || Blocked || Allowed (after rally)
| '''Phase 2: Trailing''' || +20 points profit || Trail stop using ATR × 2
|}
|}


=== Sideways Market ===
== Phase 1: Breakeven Stop ==


{| class="wikitable"
<pre>
|-
Configuration:
! Zone !! LONG !! SHORT
  breakeven_activation = 25 points
|-
  breakeven_buffer = 2 points
| Top Third || Blocked (overextended) || Allowed
|-
| Bottom Third || Allowed || Blocked
|}


== Three-Finger Spread ==
Example (LONG from 5700):
  Price reaches 5725 (+25 pts profit)
  → Stop moves from 5660 to 5702 (entry + 2)
  → Trade is now "risk-free"
</pre>


'''What:''' Large separation between Price, MA21, and MA200.
== Phase 2: Trailing Stop ==


<pre>
<pre>
Detection:
Configuration:
- Distance(Price to MA21) > 2% of price
  trailing_stop_activation = 20 points
- AND Distance(MA21 to MA200) > 2% of price
  trailing_stop_method = ATR_MULTIPLE
</pre>
  atr_period = 14 bars
  atr_multiplier = 2.0
  minimum_trail_distance = 15 points


'''Impact:''' Expect profit-taking soon (bearish for longs, bullish for shorts)
Example (LONG from 5700, ATR = 12):
  Trailing Distance = 12 × 2 = 24 points


== Crash Bar Detection ==
  Price at 5740:
  → Trail stop = 5740 - 24 = 5716


'''What:''' Abnormally large bar indicating structural break.
  Price at 5760:
  → Trail stop = 5760 - 24 = 5736 (moved UP)
 
  Price drops to 5736:
  → STOPPED OUT at 5736 (profit locked)
</pre>
 
== Why Both Phases? ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Threshold
! Phase !! Purpose
|-
|-
| Bar Size || 2x average bar size
| Breakeven || Eliminate risk quickly once trade moves in favor
|-
|-
| Close Position || Within 30% of extreme
| Trailing || Let winners run while protecting accumulated profit
|}
|}
'''Special Rule:''' Crash bar in sideways market + top zone → Override to SHORT


----
----


= PART 10: EXIT MANAGEMENT =
= PART 11: SLIPPAGE & COSTS =


== Overview ==
== Slippage Model ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Trigger !! Typical Result
! Event !! Slippage !! Rationale
|-
|-
| '''Stop Loss''' || Price hits stop (static or trailing) || Loss or locked profit
| '''Entry''' || +1.0 point || Normal market fill
|-
|-
| '''Take Profit''' || Price hits target || Winner (always)
| '''Stop Loss Exit''' || +2.0 points || Stops slip more in fast moves
|-
|-
| '''Timeout''' || 8 hours elapsed || Exit at market
| '''Target Exit''' || +0.5 points || Limit orders have minimal slippage
|}
|}


== Initial Stop Loss: 40 Points ==
== Cost Structure ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Method !! Description
! Cost Type !! Value
|-
|-
| '''Default''' || 40 points from entry
| Commission || Rs 20 per lot per side
|-
|-
| '''Structure-Based''' || Below swing low (LONG) / Above swing high (SHORT)
| STT || 0.01% on sell side
|-
|-
| '''MA-Based''' || MA21 value ± 25 points buffer
| Exchange Fees || ~Rs 2 per lot
|-
|-
| '''Minimum''' || Always at least 40 points
| Stamp Duty || State-dependent
|}
|}


=== Stop by Entry Technique ===
== Why Model Slippage? ==


{| class="wikitable"
* Backtest results must reflect real trading
|-
* Prevents over-optimistic performance estimates
! Technique !! Stop Placement
* Stop loss slippage is higher because stops often trigger during fast moves
|-
* Total costs ~Rs 136  per round-trip lot for Crudeoil 1 lot, Nifty 158
| 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 ==
= PART 12: EXIT RULES =
 
<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.


This explains why '''72.3% of exits are "stop"''' but many are '''profitable trades'''!
== 3 Exit Conditions ==
</div>
 
=== Phase 1: Breakeven Stop ===
 
'''Trigger:''' When trade reaches '''25 points profit'''


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Exit Type !! Condition
|-
|-
| Activation || 25 points in profit
| '''Stop Loss''' || Price hits stop (original or trailing)
|-
|-
| New Stop || Entry price + 2 pts buffer
| '''Target''' || Price hits take profit level
|-
|-
| Purpose || Eliminate loss, lock small profit
| '''Timeout''' || End of day (no overnight holds)
|}
|}


'''Example (LONG at 5500):'''
= PART 13: PUTTING IT ALL TOGETHER =
 
== Trade Flow ==


<pre>
<pre>
Entry: 5500
┌─────────────────────────────────────────────────────────────────┐
Original Stop: 5460 (40 pts risk)
│  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 - Market State Analysis                        │
│  Run 7 algorithms: Railroad, Creeper, Phase, BOS, etc.          │
│  Calculate penalties and bonuses                                │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 4: LAYER 3 - Setup Quality Grading                        │
│  Score 5 factors, apply penalties/bonuses                      │
│  Assign grade: A+ / A / B / C / D / F                          │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 5: LAYER 4 - HARD FILTERS (The Gate)  ◄── PASS/FAIL      │
│  • Direction: MA21 slope matches trade direction?              │
│  • Grade: Is grade A+, A, or B?                                │
│  • Hour: Is current hour allowed (not 9, 22, 23)?              │
│  ANY FAIL → NO TRADE                                            │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 6: LAYER 5 - Entry Technique                              │
│  Is price within ±25 points of MA21?                            │
│  Select entry technique (NEAR_MA, BOS_ENTRY, etc.)              │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  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                          │
└─────────────────────────────────────────────────────────────────┘
</pre>


Price reaches 5525 (+25 pts profit):
----
→ 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) ===
= PART 14: HARD vs SOFT FILTERS =


'''Trigger:''' When trade reaches '''20 points profit'''
== Understanding the Difference ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Filter Type !! Behavior !! Examples
|-
| Method || ATR_MULTIPLE (adapts to volatility)
|-
| ATR Period || 14 bars
|-
|-
| ATR Multiplier || 2.0
| '''HARD''' || Blocks trade completely || Direction filter, Hour filter, Grade C/D/F
|-
|-
| Trailing Distance || ATR × 2 (dynamic)
| '''SOFT''' || Affects quality score || MTF alignment, Market state penalties
|-
| Minimum Distance || 15 points
|-
| Activation || 20 points in profit
|}
|}


'''How It Works:'''
== Complete Filter List ==
 
<pre>
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.
</pre>
 
=== Complete Stop Movement Example ===
 
<pre>
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
─────────────────────────────────────────────────
</pre>
 
----
 
== Take Profit: 60 Points ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Calculation !! Value
! Filter !! Type !! Effect
|-
|-
| '''Primary''' || 50% of distance to MA21
| MA21 Direction || '''HARD''' || Wrong direction = NO TRADE
|-
|-
| '''Minimum''' || Risk × 1.5 = 40 × 1.5 = 60 pts
| Hour Filter || '''HARD''' || Hours 9, 22, 23 = NO TRADE
|-
|-
| '''Final''' || MAX(50% to MA, 60 pts) = Usually 60 pts
| Grade < B || '''HARD''' || C/D/F grades = NO TRADE
|}
 
'''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 ==
 
{| class="wikitable"
|-
|-
! Exit Type !! Slippage
| MTF Alignment || SOFT || Low alignment = reduced score (30% weight)
|-
|-
| Entry (base) || +1.0 points
| Creeper Move || SOFT || -50 points penalty
|-
|-
| Stop Loss exit || +2.0 points (worse fill)
| No Two-Day Trend || SOFT || -30 points penalty
|-
|-
| Take Profit exit || +0.5 points (limit order)
| Institutional Fight || SOFT || 0.7× score multiplier
|-
|-
| Market Impact || Up to 2.0 points (capped)
| Far from MA21 || SOFT || -40 points penalty
|}
|}


----
----


= PART 11: RISK MANAGEMENT =
= APPENDIX A: CONFIGURATION VALUES =


== Position Sizing ==
== MTF Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Parameter !! Value !! Source File !! Description
|-
|-
| Position Size || 1 lot (100 barrels)
| context_timeframe || DAILY || main.py:162 || Highest timeframe for overall bias
|-
|-
| Risk per Trade || 40 pts × Rs 100 = Rs 4,000
| primary_timeframe || 1-HOUR || main.py:163 || Primary trend direction
|-
|-
| Reward per Trade || 60 pts × Rs 100 = Rs 6,000
| confirmation_timeframe || 15-MIN || main.py:164 || Entry timing confirmation
|-
| Max Concurrent || 1 trade at a time
|}
 
== Cost Structure ==
 
{| class="wikitable"
|-
|-
! Cost Type !! Value
| entry_timeframe || 5-MIN || main.py:165 || Execution timeframe
|-
|-
| Brokerage || Rs 20 per lot per leg (Dhan)
| require_all_timeframes_aligned || '''False''' || main.py:166 || Allow partial alignment
|-
|-
| CTT || 0.01% on sell side
| min_alignment_score || '''0.70 (70%)''' || main.py:167 || Minimum MTF alignment score
|-
|-
| Total Round-trip || ~Rs 95 per trade
| wait_for_15min_alignment || '''True''' || main.py:168 || Wait for 15M confirmation
|-
|-
| Total Costs (7,534 trades) || Rs 5.93 Lakhs
| min_15min_confirmation_bars || '''2 bars''' || main.py:169 || Bars needed for 15M confirmation
|}
|}


== Risk Metrics ==
== Entry Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Parameter !! Value !! Source File
|-
| entry_timeframe || 5-Minute || main.py:165
|-
|-
| Risk per Trade || Rs 4,000 (4% of initial capital)
| ma_buffer_points || 25 points || signal_generation_trade_management.py:68
|-
|-
| Risk:Reward || 1:1.5 (40:60)
| blocked_hours || [9, 22, 23] || signal_generation_trade_management.py:137
|-
|-
| Required Win Rate || 40% to break even
| enable_hour_filter || True || signal_generation_trade_management.py:89
|-
|-
| Actual Win Rate || 57.6% (profitable)
| enable_ma_direction_filter || True || signal_generation_trade_management.py:97
|}
|}


----
== Stop/Target Configuration ==
 
= PART 12: SIGNAL GENERATION FLOW =
 
== 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 =
 
== Summary Statistics ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Parameter !! Value !! Source File
|-
|-
| '''Period''' || 19 months
| min_stop_distance || 40 points || signal_generation_trade_management.py:59
|-
|-
| '''Initial Capital''' || Rs 1,00,000
| default_risk_reward || 1.5 || signal_generation_trade_management.py:62
|-
|-
| '''Final Value''' || Rs 26,48,101
| bos_stop_buffer_points || 5 points || signal_generation_trade_management.py:81
|-
| '''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 ==
== Dynamic Stop Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Parameter !! Value !! Source File
|-
|-
| Total Trades || 7,534
| enable_trailing_stop || True || trade_execution_engine.py:58
|-
|-
| Winners || 4,338 (57.6%)
| trailing_stop_method || ATR_MULTIPLE || trade_execution_engine.py:63
|-
|-
| Losers || 3,196 (42.4%)
| atr_period || 14 bars || trade_execution_engine.py:64
|-
|-
| Profit Factor || 1.20
| atr_multiplier || 2.0 || trade_execution_engine.py:65
|-
|-
| Average Win || Rs 3,464
| trailing_stop_activation || 20 points || trade_execution_engine.py:60
|-
|-
| Average Loss || Rs 3,904
| enable_breakeven_stop || True || trade_execution_engine.py:69
|-
|-
| Largest Win || Rs 26,799
| breakeven_activation || 25 points || trade_execution_engine.py:70
|-
|-
| Largest Loss || Rs 13,217
| breakeven_buffer || 2 points || trade_execution_engine.py:71
|-
|-
| Avg Holding Time || 2.4 hours
| minimum_trail_distance || 15 points || trade_execution_engine.py:370
|}
|}


== Exit Reason Breakdown ==
== Slippage Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Count !! % !! Notes
! Parameter !! Value !! Source File
|-
|-
| '''Stop''' || 5,444 || 72.3% || Includes trailing stop profits!
| base_slippage_points || 1.0 point || trade_execution_engine.py:38
|-
|-
| '''Target''' || 1,716 || 22.8% || 100% winners
| volatility_slippage_factor || 0.5 || trade_execution_engine.py:39
|-
|-
| '''Timeout''' || 374 || 5.0% || 8-hour limit
| market_impact_factor || 0.1 || trade_execution_engine.py:40
|}
 
<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 ==
 
{| class="wikitable"
|-
|-
! Direction !! Count !! %
| max_market_impact_slippage || 2.0 points || trade_execution_engine.py:43
|-
|-
| '''SHORT''' || 6,024 || 80%
| stop_loss_slippage || 2.0 points || trade_execution_engine.py:50
|-
|-
| '''LONG''' || 1,510 || 20%
| take_profit_slippage || 0.5 points || trade_execution_engine.py:51
|}
|}


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


{| class="wikitable"
{| class="wikitable"
|-
|-
! Grade !! Count !! %
! Parameter !! Value !! Source File !! Description
|-
|-
| A+ || 3,457 || 45.9%
| max_holding_period_minutes || '''480 (8 hours)''' || trade_execution_engine.py:46 || Maximum time a trade can stay open
|-
|-
| A || 551 || 7.3%
| min_holding_period_minutes || '''5 minutes''' || trade_execution_engine.py:47 || Minimum holding before exit
|-
|-
| C || 3,526 || 46.8% (analyzed but NOT traded)
| max_position_size || '''200 lots''' || trade_execution_engine.py:54 || Maximum lots per single trade
|}
 
----
 
= 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
|-
| min_stop_distance || 40 points || signal_generation_trade_management.py
|-
|-
| default_stop_distance || 40 points || signal_generation_trade_management.py
| max_concurrent_trades || '''3''' || trade_execution_engine.py:55 || Maximum simultaneous open trades
|-
|-
| default_risk_reward || 1.5 || signal_generation_trade_management.py
| market_close_buffer_minutes || '''15 minutes''' || trade_execution_engine.py:75 || Close trades before market close
|-
|-
| min_target || risk × 1.5 = 60 pts || signal_generation_trade_management.py
| avoid_news_minutes || 30 minutes || trade_execution_engine.py:74 || Buffer around news events
|}
|}


== Trailing Stop Configuration ==
== Cost Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value !! Source
! Parameter !! Value !! Source File !! Description
|-
|-
| enable_trailing_stop || True || trade_execution_engine.py
| commission_per_lot || '''Rs 20/lot/leg''' || signal_generation_trade_management.py:49 || Dhan broker commission
|-
|-
| trailing_stop_method || ATR_MULTIPLE || trade_execution_engine.py
| transaction_tax_rate || '''0.005% per leg''' || signal_generation_trade_management.py:55 || CTT (0.01% round-trip)
|-
|-
| atr_period || 14 bars || trade_execution_engine.py
| lot_size_multiplier || '''100 barrels''' || signal_generation_trade_management.py:56 || MCX Crude lot size
|-
|-
| atr_multiplier || 2.0 || trade_execution_engine.py
| initial_capital || '''Rs 1,00,000''' || main.py:1131 || Starting capital for backtest
|-
| 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
|}
|}


Line 1,185: Line 892:
{| 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
|}
|}


----
== Probability Zone Configuration ==
 
= APPENDIX B: SOURCE CODE REFERENCE =


{| class="wikitable"
{| class="wikitable"
|-
|-
! File !! Purpose
! Parameter !! Value !! Source File
|-
|-
| <code>trend_analysis_core.py</code> || MA slope calculation, trend direction, price-MA struggle
| enable_probability_zone_filter || True || signal_generation_trade_management.py:104
|-
|-
| <code>multi_timeframe_analysis.py</code> || MTF alignment scoring across 5 timeframes
| probability_zone_swing_lookback || 20 bars || signal_generation_trade_management.py:105
|-
|-
| <code>market_state_analysis.py</code> || 7 market state detection algorithms
| probability_zone_min_range || 20 points || signal_generation_trade_management.py:106
|-
|-
| <code>setup_quality_detection.py</code> || 5-factor grading system with penalties/bonuses
| top_third_threshold || 66.7% || probability_zone_analysis.py:125
|-
|-
| <code>probability_zone_analysis.py</code> || Halves/Thirds, Three-Finger Spread, Crash Bar
| top_third_probability || 80% || probability_zone_analysis.py:131
|-
|-
| <code>signal_generation_trade_management.py</code> || Entry/Exit logic, stop/target calculation
| bottom_third_probability || 15% || probability_zone_analysis.py:134
|-
|-
| <code>trade_execution_engine.py</code> || Breakeven, Trailing stop, Slippage, Timeout
| crash_bar_multiplier || 2.0 || probability_zone_analysis.py:145
|-
|-
| <code>data_manager.py</code> || OHLCV data loading and management
| 3_finger_min_spread_pct || 2% || probability_zone_analysis.py:141
 
|}
|}


----
----
''Document generated from code analysis - January 2026''
''All rules extracted directly from source code implementation''
[[Category:Trading Strategies]]
[[Category:MCX Crude Oil]]
[[Category:MA21 Mean Reversion]]
[[Category:Backtesting]]

Latest revision as of 06:40, 6 January 2026

Multi_Timeframe Dynamic Trend (MTFDR)

[edit]

PART 1: STRATEGY OVERVIEW

[edit]

What Is This Strategy?

[edit]

Multi_Timeframe Dynamic Trend(MTFDR) is a systematic intraday trading strategy that requires multiple analytical layers to align before taking a trade. Each layer must be present for a valid setup. Market behavior is probabilistic, not predictive. The goal is positioning with asymmetric probabilities, not prediction.

Layered Architecture (Top-Down)

[edit]
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│   LAYER 1: MULTI-TIMEFRAME ANALYSIS  - FOUNDATION LAYER    │
│   5 timeframes analyzed for trend alignment                 │ context
│   Daily → 4H → 1H → 15M → 5M                               │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 2: MARKET STATE ANALYSIS                           │  ← regime/ market state conditions 
│   7 algorithms: Railroad, Creeper, Phase, BOS, etc.         │
│   Calculates penalties and bonuses                          │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 3: SETUP QUALITY GRADING                           │  ←  set up scoring
│   5-factor weighted scoring → Assigns grade A+ to F         │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 4: FILTERS (Trade/No_Trade)                        │
│   • Direction: MA21 slope must match trade direction        │Filters
│   • Grade: Only A+, A, B grades can trade                   │
│   • Hours: Block hours ]WIP]                               │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   LAYER 5: ENTRY TECHNIQUES                                │  ← Final trigger
│                                                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

PART 2: Core Concept (Why This Works)

[edit]

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

Layer What It Filters Out
1. MTF Analysis Counter-trend trades, choppy markets
2. Market State Dangerous conditions (creeper moves, institutional fights)
3. Quality Grading Scores the setup (used by hard filter)
4. Hard Filters Wrong direction, low grades (C/D/F), blocked hours
5. Entry Technique Chasing price far from value areas

The Math

[edit]

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)

[edit]

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

The 5 Timeframes

[edit]
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

[edit]

For each of 5 timeframes, our system calculates:

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

MTF Alignment Score

[edit]
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

[edit]
Scenario MTF Alignment Action
All 5 timeframes aligned ~90% High conviction trade A+ 2lots
4 of 5 aligned ~80% Trade with normal size A 1 lot
3 of 5 aligned ~70% Proceed with caution B 1 lot
2 or fewer aligned <60% No Trade

PART 4: LAYER 2 - MARKET STATE ANALYSIS

[edit]

The 7 Market State Algorithms

[edit]

Our 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

[edit]
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

[edit]
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

Probability Zone Analysis

[edit]

The Asymmetric Probability Edge

[edit]

When odds are low on one outcome, the opposite side usually carries high odds:

  • If new high probability drops to 15%, then 85% odds favor reversal
  • We position ourselves on high-probability side where price position within recent range determines continuation probability:
  • Every large move is divided into halves and thirds, creating probability zones.

Odds of Continuation After Pullback

[edit]
┌─────────────────────────────────────────────────────┐
│  SWING HIGH                                         │
├─────────────────────────────────────────────────────┤
│  TOP THIRD        →  ~80% chance of new high        │  
├─────────────────────────────────────────────────────┤
│  TOP HALF         →  ~66% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM HALF      →  ~33% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM THIRD     →  ~15% chance of new high        │  
├─────────────────────────────────────────────────────┤
│  SWING LOW                                          │
└─────────────────────────────────────────────────────┘
Zone Position Continuation Probability Action
Top Third >66.6% of range 80% likely to continue higher Favor LONG
Top Half >50% of range 65% continuation Moderate LONG bias
Bottom Half <50% of range 35% continuation higher Moderate SHORT bias
Bottom Third <33.3% of range 15% continuation (85% reversal) Favor SHORT

3-Finger Spread

[edit]

Measures separation between Price, 21 MA, and 200 MA:

Three-Finger Spread Detection:
  - Large spread between Price/21MA/200MA
  - Indicates profit-taking pressure imminent
  - Minimum spread threshold: 2% of price

Structure Types:
  UPTREND:    Price > 21 MA > 200 MA (bullish stack)
  DOWNTREND:  Price < 21 MA < 200 MA (bearish stack)
  SIDEWAYS:   No clear MA separation

Crash Bar Detection

[edit]

Identifies structural breaks via unusually large bars:

Parameter Value Meaning
crash_bar_multiplier 2.0 Bar must be 2× average size
crash_bar_lookback 10 bars Average calculated over 10 bars
crash_bar_close_threshold 30% Close within 30% of bar extreme

Pullback Classification

[edit]
Type Characteristics Action
Healthy Pullback 45° drift, holds above halfway point Good entry opportunity
Collapse Vertical drop (>60% retracement) Avoid entry, wait for structure
Bounce Recovery after crash bar Short opportunity

Signal Filtering

[edit]

Probability zones filter signals:

  1. Zone-based filtering (soft filter - affects score, doesn't block)

if zone_position < 33.3%: # Bottom third

   # Block LONG signals (only 15% chance of continuation)
   # Allow SHORT signals

if zone_position > 66.7%: # Top third

   # Allow LONG signals (80% continuation)
   # Block SHORT signals

PART 5: LAYER 3 - SETUP QUALITY GRADING

[edit]

The 5-Factor Scoring System

[edit]

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

[edit]
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

[edit]

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

[edit]
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 6: HARD LAYER 4 - FILTERS

[edit]

HARD FILTERS block trades completely. If ANY hard filter fails, NO TRADE happens regardless of how good the setup looks.

3 Hard Filters

[edit]
Filter Rule Effect
1. Direction Filter MA21 slope must match trade direction Wrong direction = BLOCKED
2. Grade Filter Only A+, A, B grades allowed C/D/F grades = BLOCKED
3. Hour Filter Block hours [WIP] Blocked hours = BLOCKED

Filter 1: Direction (MA21 Slope)

[edit]
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

Filter 2: Grade

[edit]
Grade Action
A+, A, B PASS - Proceed to entry
C, D, F BLOCKED - No trade

Filter 3: Hour [work in progress examples]

[edit]
Hour Status Reason
9 (9:00-9:59 AM) BLOCKED Market open volatility
10-21 (10:00 AM - 9:59 PM) ALLOWED Normal trading hours
22 (10:00-10:59 PM) BLOCKED Near market close
23 (11:00-11:59 PM) BLOCKED Market close

PART 7: LAYER 5 - ENTRY TECHNIQUE

[edit]

MA21 Zone Principle

[edit]

"The MA is a ZONE, not a thin line or exact value"

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

Why ±25 Points?

[edit]
  • Price rarely touches MA exactly
  • Allows for normal market noise

Entry Techniques

[edit]
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

PART 8: STOP LOSS CALCULATION

[edit]

Stop Loss Methods (Priority Order)

[edit]
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

[edit]

MINIMUM: 40 points

This prevents:

  • Getting stopped out by normal noise
  • Excessive trading costs from tight stops
  • Whipsaws in market manipulations, this varies depending on markets, nature of that trade

PART 9: TARGET CALCULATION

[edit]

The 50% Rule

[edit]

Target = 50% of distance to MA21

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

Why 50%?

[edit]
  • 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

[edit]
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)

PART 10: DYNAMIC STOP MANAGEMENT

[edit]

Two-Phase Protection

[edit]

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

[edit]
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

[edit]
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?

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

PART 11: SLIPPAGE & COSTS

[edit]

Slippage Model

[edit]
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

[edit]
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?

[edit]
  • 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 136 per round-trip lot for Crudeoil 1 lot, Nifty 158

PART 12: EXIT RULES

[edit]

3 Exit Conditions

[edit]
Exit Type Condition
Stop Loss Price hits stop (original or trailing)
Target Price hits take profit level
Timeout End of day (no overnight holds)

PART 13: PUTTING IT ALL TOGETHER

[edit]

Trade Flow

[edit]
┌─────────────────────────────────────────────────────────────────┐
│  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 - Market State Analysis                        │
│  Run 7 algorithms: Railroad, Creeper, Phase, BOS, etc.          │
│  Calculate penalties and bonuses                                │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 4: LAYER 3 - Setup Quality Grading                        │
│  Score 5 factors, apply penalties/bonuses                       │
│  Assign grade: A+ / A / B / C / D / F                           │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 5: LAYER 4 - HARD FILTERS (The Gate)  ◄── PASS/FAIL      │
│  • Direction: MA21 slope matches trade direction?               │
│  • Grade: Is grade A+, A, or B?                                 │
│  • Hour: Is current hour allowed (not 9, 22, 23)?               │
│  ANY FAIL → NO TRADE                                            │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  STEP 6: LAYER 5 - Entry Technique                              │
│  Is price within ±25 points of MA21?                            │
│  Select entry technique (NEAR_MA, BOS_ENTRY, etc.)              │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  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

[edit]

Understanding the Difference

[edit]
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

[edit]
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

[edit]

MTF Configuration

[edit]
Parameter Value Source File Description
context_timeframe DAILY main.py:162 Highest timeframe for overall bias
primary_timeframe 1-HOUR main.py:163 Primary trend direction
confirmation_timeframe 15-MIN main.py:164 Entry timing confirmation
entry_timeframe 5-MIN main.py:165 Execution timeframe
require_all_timeframes_aligned False main.py:166 Allow partial alignment
min_alignment_score 0.70 (70%) main.py:167 Minimum MTF alignment score
wait_for_15min_alignment True main.py:168 Wait for 15M confirmation
min_15min_confirmation_bars 2 bars main.py:169 Bars needed for 15M confirmation

Entry Configuration

[edit]
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
enable_hour_filter True signal_generation_trade_management.py:89
enable_ma_direction_filter True signal_generation_trade_management.py:97

Stop/Target Configuration

[edit]
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

[edit]
Parameter Value Source File
enable_trailing_stop True trade_execution_engine.py:58
trailing_stop_method ATR_MULTIPLE trade_execution_engine.py:63
atr_period 14 bars trade_execution_engine.py:64
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:69
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

[edit]
Parameter Value Source File
base_slippage_points 1.0 point trade_execution_engine.py:38
volatility_slippage_factor 0.5 trade_execution_engine.py:39
market_impact_factor 0.1 trade_execution_engine.py:40
max_market_impact_slippage 2.0 points trade_execution_engine.py:43
stop_loss_slippage 2.0 points trade_execution_engine.py:50
take_profit_slippage 0.5 points trade_execution_engine.py:51

Trade Execution Limits

[edit]
Parameter Value Source File Description
max_holding_period_minutes 480 (8 hours) trade_execution_engine.py:46 Maximum time a trade can stay open
min_holding_period_minutes 5 minutes trade_execution_engine.py:47 Minimum holding before exit
max_position_size 200 lots trade_execution_engine.py:54 Maximum lots per single trade
max_concurrent_trades 3 trade_execution_engine.py:55 Maximum simultaneous open trades
market_close_buffer_minutes 15 minutes trade_execution_engine.py:75 Close trades before market close
avoid_news_minutes 30 minutes trade_execution_engine.py:74 Buffer around news events

Cost Configuration

[edit]
Parameter Value Source File Description
commission_per_lot Rs 20/lot/leg signal_generation_trade_management.py:49 Dhan broker commission
transaction_tax_rate 0.005% per leg signal_generation_trade_management.py:55 CTT (0.01% round-trip)
lot_size_multiplier 100 barrels signal_generation_trade_management.py:56 MCX Crude lot size
initial_capital Rs 1,00,000 main.py:1131 Starting capital for backtest

Grading Configuration

[edit]
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

Probability Zone Configuration

[edit]
Parameter Value Source File
enable_probability_zone_filter True signal_generation_trade_management.py:104
probability_zone_swing_lookback 20 bars signal_generation_trade_management.py:105
probability_zone_min_range 20 points signal_generation_trade_management.py:106
top_third_threshold 66.7% probability_zone_analysis.py:125
top_third_probability 80% probability_zone_analysis.py:131
bottom_third_probability 15% probability_zone_analysis.py:134
crash_bar_multiplier 2.0 probability_zone_analysis.py:145
3_finger_min_spread_pct 2% probability_zone_analysis.py:141