Jump to content

Alpha Research: Difference between revisions

From PlusEV Wiki Page
No edit summary
No edit summary
 
(94 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= MA21 Mean Reversion Strategy =
= Multi_Timeframe Dynamic Trend (MTFDR) =
== Complete Trading System Documentation ==
=== MCX Crude Oil - Intraday Trading System ===
 
----
----


= PART 1: CORE CONCEPT =
= PART 1: STRATEGY OVERVIEW =


== The Big Idea ==
== What Is This Strategy? ==


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


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.
== Layered Architecture (Top-Down) ==


<blockquote>'''"The MA is a ZONE, not a thin line"''' - Entry allowed within '''±25 points''' of MA21</blockquote>
<pre>
 
┌─────────────────────────────────────────────────────────────┐
----
│                                                            │
 
│  LAYER 1: MULTI-TIMEFRAME ANALYSIS  - FOUNDATION LAYER    │
= PART 2: MULTI-TIMEFRAME (MTF) ANALYSIS =
│  5 timeframes analyzed for trend alignment                │ context
 
│  Daily → 4H → 1H → 15M → 5M                              │
{{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.}}
│                                                            │
├─────────────────────────────────────────────────────────────┤
│                                                            │
│  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>


== Timeframe Hierarchy ==
= PART 2: Core Concept (Why This Works) =


We analyze '''5 timeframes''' from highest to lowest:
The edge comes from '''requiring multiple independent confirmations''' before trading. Each layer filters out bad trades:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Timeframe !! Purpose !! What We Look For
! Layer !! What It Filters Out
|-
|-
| '''Daily (1D)''' || Context/Bias || Overall trend direction, key levels
| 1. MTF Analysis || Counter-trend trades, choppy markets
|-
|-
| '''4-Hour (4H)''' || Primary Trend || Main trend confirmation
| 2. Market State || Dangerous conditions (creeper moves, institutional fights)
|-
|-
| '''1-Hour (1H)''' || Confirmation || Trend alignment validation
| 3. Quality Grading || Scores the setup (used by hard filter)
|-
|-
| '''15-Min (15M)''' || Entry Timing || Final confirmation before entry
| 4. Hard Filters || Wrong direction, low grades (C/D/F), blocked hours
|-
|-
| '''5-Min (5M)''' || Execution || Precise entry and exit
| 5. Entry Technique || Chasing price far from value areas
|}
|}


== MTF Alignment Logic ==
== The Math ==


For each timeframe, we check:
If each layer has 70% accuracy independently:
# '''MA21 Slope''' - Is it rising or declining?
* Single layer: 70% edge
# '''Price Position''' - Is price above/below MA21?
* 2 layers: 70% × 70% = 49% of trades pass, but higher quality
# '''MA21 vs MA200''' - Short-term vs long-term trend alignment
* 5 layers: Only the '''best setups''' survive all filters


=== Weighted Scoring ===
'''Result:''' Fewer trades, but each trade has multiple confluences supporting it.


Each timeframe contributes to an '''alignment score''':
----
* Higher timeframes have more weight (Daily > 4H > 1H > 15M > 5M)
* Score ranges from 0.0 to 1.0
* Higher score = stronger alignment


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


<pre>
<div style="background:#e6ffe6; border:1px solid #00cc00; padding:10px; margin:10px 0;">
IF all timeframes agree → Strong signal
'''THIS IS THE FOUNDATION''' - Everything else builds on top of MTF alignment. If timeframes disagree, we don't trade.
IF most timeframes agree → Medium signal
</div>
IF timeframes conflict → No trade (wait for clarity)
</pre>
 
== Per-Timeframe Trend Analysis ==


For each timeframe, the '''Trend Analysis Core''' calculates:
== The 5 Timeframes ==
 
=== 1. Trend Direction ===
 
Based on MA21 slope:


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA21 Slope !! Direction !! Threshold
! Timeframe !! Role !! Weight
|-
|-
| Positive > 0.01% || UP || Bullish slope threshold
| '''Daily (1D)''' || Overall market bias || Highest
|-
|-
| Negative < -0.01% || DOWN || Bearish slope threshold
| '''4-Hour (4H)''' || Primary trend direction || High
|-
| Between ±0.01% || SIDEWAYS || No clear trend
|}
 
=== 2. MA Trending Status ===
 
Is the MA21 moving with significant momentum?
 
{| class="wikitable"
|-
|-
! MA Slope !! Status !! Threshold
| '''1-Hour (1H)''' || Trend confirmation || Medium
|-
|-
| > 0.05% || TRENDING || MA is clearly moving
| '''15-Minute (15M)''' || Entry timing context || Lower
|-
|-
| < 0.05% || FLAT || MA is consolidating
| '''5-Minute (5M)''' || Execution timeframe || Lowest
|}
|}


=== 3. Price-MA Struggle Detection ===
== What We Analyze Per Timeframe ==


Is price stuck near the MA without breaking away?
For each of 5 timeframes, our system calculates:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Condition !! Detection
! Analysis !! Description
|-
|-
| Price within 0.5% of MA21 for multiple bars || STRUGGLING
| '''MA21 Value''' || 21-period Moving Average
|-
|-
| Price clearly moving away from MA21 || CLEAR TREND
| '''MA21 Slope''' || Rising/Flat/Declining
|}
 
'''Trading Impact:''' Price-MA struggle = '''-30 penalty''' in grading
 
=== 4. Trend Confidence Calculation ===
 
Weighted score from three factors:
 
<pre>
Confidence = (MA_Slope × 40%) + (Price_Position × 30%) + (MA_Alignment × 30%)
</pre>
 
{| class="wikitable"
|-
|-
! Factor !! Weight !! What It Measures
| '''MA200 Value''' || 200-period Moving Average
|-
|-
| MA Slope || 40% || Steepness of MA21 angle
| '''Price vs MA21''' || Above/Below/At the MA
|-
|-
| Price Position || 30% || Is price above/below MA21?
| '''Trend Direction''' || UP/DOWN/NEUTRAL
|-
| MA Alignment || 30% || Does MA21 align with MA200?
|}
|}


----
== MTF Alignment Score ==


= PART 3: SIGNAL GENERATION FLOW =
<pre>
 
For each timeframe:
== Complete Flow Diagram ==
  1. Determine trend direction (UP/DOWN/NEUTRAL)
  2. Check if aligned with trade direction
  3. Apply timeframe weight
  4. Sum weighted alignment scores


<pre>
Example (LONG trade):
┌─────────────────────────────────────────────────────────────────────────────┐
   DailyUP (aligned)     × 1.00 weight = 1.00
│                        SIGNAL GENERATION PIPELINE                        │
   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
│  STEP 1: DATA COLLECTION                                                    │
   5M:     UP (aligned)    × 0.44 weight = 0.44
│  ┌─────────────────────────────────────────────────────────────────────┐  │
   ─────────────────────────────────────────────
│  │ Load OHLCV data for all 5 timeframes                                │  │
   Total MTF Score: 3.02 / 3.60 = 83.9% aligned
│  │ 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>


----
== Why MTF Matters ==
 
= PART 4: MARKET STATE DETECTION =
 
== 7 Detection Algorithms ==
 
=== 1. Railroad Trend Detection ===
 
'''What it is:''' Strong, consistent trend with minimal pullbacks.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Description
! Scenario !! MTF Alignment !! Action
|-
| All 5 timeframes aligned || ~90% || '''High conviction trade A+ 2lots'''
|-
|-
| Bar Analysis || 5 most recent bars analyzed
| 4 of 5 aligned || ~80% || Trade with normal size A 1 lot
|-
|-
| Strong Bars || 80%+ must close in same direction
| 3 of 5 aligned || ~70% || Proceed with caution B 1 lot
|-
|-
| Consistency || Bars must be "strong" (body > 0.3% of price)
| 2 or fewer aligned || <60% || '''No Trade'''
|}
|}


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


----
= PART 4: LAYER 2 - MARKET STATE ANALYSIS =


=== 2. Creeper Move Detection ===
== The 7 Market State Algorithms ==


'''What it is:''' Slow, grinding price action with small bars.
Our system runs 7 independent algorithms to understand current market context:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Description
! # !! Algorithm !! What It Detects !! Impact
|-
|-
| Bar Range || Average range < 0.5% of price
| 1 || '''Railroad Tracks''' || Strong momentum bars in sequence || +15% bonus
|-
|-
| Analysis Period || Last 7 bars
| 2 || '''Creeper Move''' || Slow grinding trend (dangerous) || '''-50% penalty'''
|-
|-
| Pattern || Price moving slowly without clear impulse
| 3 || '''Two-Day Trend''' || Trend visible on Daily for 2+ days || Required for A+
|}
 
'''Trading Impact:''' '''-50 penalty''' to setup score (avoid these setups)
 
----
 
=== 3. Two-Day Trend Analysis ===
 
'''What it is:''' Trend must be visible on Daily timeframe for 2+ days.
 
{| class="wikitable"
|-
! Requirement !! Description
|-
| Daily Bars || At least 2 consecutive bars in same direction
|-
|-
| Purpose || Filters out noise, ensures real trend
| 4 || '''Phase Analysis''' || Accumulation/Distribution/Markup/Markdown || Phase mismatch = -25%
|}
 
'''Trading Impact:''' Missing two-day trend = '''-30 penalty'''
 
----
 
=== 4. Trend Phase Classification ===
 
{| class="wikitable"
|-
|-
! Phase !! Bars into Trend !! Trading Approach
| 5 || '''Institutional Activity''' || Big player accumulation/distribution || Fight = 0.7× multiplier
|-
|-
| '''EARLY''' || 0-15 bars || Avoid (uncertain direction)
| 6 || '''Break of Structure (BOS)''' || Key level breaks || Affects stop placement
|-
|-
| '''MIDDLE''' || 15-40 bars || '''TARGET''' (best trades)
| 7 || '''Volatility Regime''' || High/Normal/Low volatility || Adjusts expectations
|-
| '''LATE''' || 40+ bars || Avoid (exhaustion risk)
|}
|}


'''Trading Impact:''' Not being in MIDDLE phase = '''-25 penalty'''
== Penalty System ==
 
----
 
=== 5. Institutional Fight Detection ===
 
'''What it is:''' When big players are battling each other (choppy action).


{| class="wikitable"
{| class="wikitable"
|-
|-
! Indicator !! Sign
! Condition !! Penalty !! Rationale
|-
|-
| Volume || 1.5x+ average volume
| Creeper Move Detected || '''-50 points''' || Slow trends often reverse suddenly
|-
|-
| Price Action || Narrow range with high volume
| MA Struggle (price fighting MA) || -30 points || Indecision, likely to chop
|-
|-
| Wicks || Long wicks on candles (rejection)
| No Two-Day Trend || -30 points || Trend not established enough
|}
 
'''Trading Impact:''' 0.7x multiplier on final score (30% reduction)
 
----
 
=== 6. Break of Structure (BOS) ===
 
'''What it is:''' Price breaking a significant swing high/low.
 
{| class="wikitable"
|-
|-
! BOS Type !! Description
| Phase Mismatch || -25 points || Trading against market phase
|-
|-
| SWING_HIGH_BREAK || Price breaks above prior swing high
| No Key Level Nearby || -50 points || No technical confluence
|-
|-
| SWING_LOW_BREAK || Price breaks below prior swing low
| Institutional Fight || '''×0.70 multiplier''' || Big players fighting each other
|-
| PDH_BREAK || Previous Day High break
|-
| PDL_BREAK || Previous Day Low break
|}
|}


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


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


----
== Probability Zone Analysis ==


= PART 5: SETUP QUALITY GRADING SYSTEM =
=== The Asymmetric Probability Edge ===


== 5-Factor Weighted Scoring ==
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'''
Every potential trade is scored on 5 factors:
* 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"
|-
|-
! Factor !! Weight !! What It Measures
! Zone !! Position !! Continuation Probability !! Action
|-
| '''Timeframe Alignment''' || 30% || How well all timeframes agree
|-
|-
| '''Trend Strength''' || 20% || Quality of the trend (railroad vs creeper)
| '''Top Third''' || >66.6% of range || '''80%''' likely to continue higher || Favor LONG
|-
|-
| '''Key Level Proximity''' || 20% || Is entry near a significant level?
| '''Top Half''' || >50% of range || '''65%''' continuation || Moderate LONG bias
|-
|-
| '''Entry Quality''' || 15% || Clean entry technique, near MA
| '''Bottom Half''' || <50% of range || '''35%''' continuation higher || Moderate SHORT bias
|-
|-
| '''Risk/Reward''' || 15% || How favorable is the R:R ratio
| '''Bottom Third''' || <33.3% of range || '''15%''' continuation ('''85% reversal''') || Favor SHORT
|}
|}


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


<pre>
<pre>
Base Score = (TF_score × 0.30) + (Trend_score × 0.20) + (KeyLevel_score × 0.20)
Three-Finger Spread Detection:
          + (Entry_score × 0.15) + (RR_score × 0.15)
  - Large spread between Price/21MA/200MA
  - Indicates profit-taking pressure imminent
  - Minimum spread threshold: 2% of price


Final Score = Base Score + Bonuses - Penalties
Structure Types:
  UPTREND:    Price > 21 MA > 200 MA (bullish stack)
  DOWNTREND:  Price < 21 MA < 200 MA (bearish stack)
  SIDEWAYS:  No clear MA separation
</pre>
</pre>


== Penalties (Negative Adjustments) ==
=== Crash Bar Detection ===
 
{| class="wikitable"
|-
! 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 (Positive Adjustments) ==
Identifies structural breaks via unusually large bars:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Condition !! Bonus !! Reason
! Parameter !! Value !! Meaning
|-
|-
| Railroad Trend || '''+15''' || High quality trend
| crash_bar_multiplier || 2.0 || Bar must be 2× average size
|-
|-
| At Key Level || '''+10''' || Confluence present
| crash_bar_lookback || 10 bars || Average calculated over 10 bars
|-
|-
| Clean Entry || '''+10''' || Clear technical setup
| crash_bar_close_threshold || 30% || Close within 30% of bar extreme
|}
|}


== Grade Thresholds ==
=== Pullback Classification ===


{| class="wikitable"
{| class="wikitable"
|-
|-
! Grade !! Min Score !! Action
! Type !! Characteristics !! Action
|-
|-
| '''A+''' || 90+ || Trade with full conviction
| '''Healthy Pullback''' || 45° drift, holds above halfway point || Good entry opportunity
|-
|-
| '''A''' || 80-89 || Trade with confidence
| '''Collapse''' || Vertical drop (>60% retracement) || Avoid entry, wait for structure
|-
|-
| '''B''' || 70-79 || Trade normally
| '''Bounce''' || Recovery after crash bar || Short opportunity
|-
| '''C''' || 60-69 || '''NO TRADE'''
|-
| '''D''' || 50-59 || '''NO TRADE'''
|-
| '''F''' || <50 || '''NO TRADE'''
|}
|}


== A+ Special Requirements ==
=== Signal Filtering ===


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


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


= PART 6: ENTRY TECHNIQUES =
if zone_position < 33.3%: # Bottom third
    # Block LONG signals (only 15% chance of continuation)
    # Allow SHORT signals


== Available Entry Techniques ==
if zone_position > 66.7%:  # Top third
    # Allow LONG signals (80% continuation)
    # Block SHORT signals


=== Universal (Both Directions) ===
= PART 5: LAYER 3 - SETUP QUALITY GRADING =


{| class="wikitable"
== The 5-Factor Scoring System ==
|-
! Technique !! Description
|-
| '''NEAR_MA''' || Entry when price is near MA21 zone (±25 pts)
|}


=== Long-Specific (Bullish) ===
Every potential trade is scored on 5 factors:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Technique !! Description
! Factor !! Weight !! What It Measures
|-
|-
| GREEN_BAR_AFTER_PULLBACK || Green candle after price pulled back
| '''Timeframe Alignment''' || '''30%''' || How well all 5 timeframes agree
|-
|-
| MA_BOUNCE_LONG || Bounce off MA21 in uptrend
| '''Trend Strength''' || '''20%''' || Quality of the trend (Railroad vs Creeper)
|-
|-
| BOS_ENTRY_LONG || Entry after break of structure (upside)
| '''Key Level Proximity''' || '''20%''' || Is entry near significant S/R level?
|-
|-
| BREAKOUT_PULLBACK_LONG || Pullback after breakout, then continue
| '''Entry Quality''' || '''15%''' || How clean is the entry technique?
|-
|-
| DISCOUNT_ZONE_LONG || Buy in lower zone of range
| '''Risk:Reward''' || '''15%''' || Is the R:R ratio favorable?
|}
|}


=== Short-Specific (Bearish) ===
<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>
 
== Grade Thresholds ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Technique !! Description
! Grade !! Score Range !! Action !! Position Size
|-
|-
| RED_BAR_AFTER_RALLY || Red candle after price rallied
| '''A+''' || 90-100 || Trade with full conviction || 2 lots
|-
|-
| MA_BOUNCE_SHORT || Rejection from MA21 in downtrend
| '''A''' || 80-89 || Trade with confidence || 1 lot
|-
|-
| BOS_ENTRY_SHORT || Entry after break of structure (downside)
| '''B''' || 70-79 || Trade normally || 1 lot
|-
|-
| BREAKOUT_PULLBACK_SHORT || Pullback after breakdown, then continue
| '''C''' || 60-69 || '''NO TRADE''' || -
|-
|-
| PREMIUM_ZONE_SHORT || Sell in upper zone of range
| '''D''' || 50-59 || '''NO TRADE''' || -
|-
| '''F''' || <50 || '''NO TRADE''' || -
|}
|}


== How Entry Technique is Selected ==
== A+ Grade Special Requirements ==
 
To achieve A+ grade, ALL conditions must be true:
* Final score ≥ 90
* All 5 timeframes aligned with trade direction
* Entry within ±25 points of MA21
* Two-day trend present on Daily
* No institutional fight detected
 
== Score Calculation Example ==


<pre>
<pre>
IF price near MA21 zone:
Trade Setup: LONG on 5-min chart
    technique = NEAR_MA
 
ELIF break of structure detected:
    IF direction == LONG: technique = BOS_ENTRY_LONG
    IF direction == SHORT: technique = BOS_ENTRY_SHORT


ELIF pullback pattern detected:
Factor Scores (0-100 each):
    IF direction == LONG: technique = GREEN_BAR_AFTER_PULLBACK
  Timeframe Alignment: 85  × 0.30 = 25.5
    IF direction == SHORT: technique = RED_BAR_AFTER_RALLY
  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


ELSE:
Penalties Applied:
    technique = MA_BOUNCE_LONG or MA_BOUNCE_SHORT
  - No Railroad Tracks: 0
  - No Creeper: 0
  - Has Two-Day: 0
                              ──────────
  Final Score: 80.75 → Grade: A
</pre>
</pre>


----
----


= PART 7: PROBABILITY ZONES =
= PART 6: HARD LAYER 4 - FILTERS=


== Halves & Thirds Analysis ==
<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>


Based on price position within recent swing range:
== 3 Hard Filters ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Zone !! Position in Range !! Continuation Probability
! Filter !! Rule !! Effect
|-
| '''Top Third''' || 67-100% || 80% (likely to make new high)
|-
|-
| '''Top Half''' || 50-67% || 65%
| '''1. Direction Filter''' || MA21 slope must match trade direction || Wrong direction = BLOCKED
|-
|-
| '''Bottom Half''' || 33-50% || 35%
| '''2. Grade Filter''' || Only A+, A, B grades allowed || C/D/F grades = BLOCKED
|-
|-
| '''Bottom Third''' || 0-33% || 15% (85% likely to go lower)
| '''3. Hour Filter''' || Block hours [WIP] || Blocked hours = BLOCKED
|}
|}


== Zone-Based Trading Rules ==
== Filter 1: Direction (MA21 Slope) ==
 
=== In Trending Market ===


{| class="wikitable"
{| class="wikitable"
|-
|-
! Zone !! LONG !! SHORT
! MA21 Slope !! Allowed Direction !! Logic
|-
|-
| Top Third || Allowed (after pullback) || Blocked (with trend)
| '''Rising''' (↗) || LONG only || Trade with uptrend, never short
|-
|-
| Bottom Third || Blocked (against trend) || Allowed (after rally)
| '''Declining''' (↘) || SHORT only || Trade with downtrend, never long
|-
| '''Flat''' () || Use MTF direction || Higher timeframes decide
|}
|}


=== In Sideways Market (Mean Reversion) ===
== Filter 2: Grade ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Zone !! LONG !! SHORT
! Grade !! Action
|-
|-
| Top Third || Blocked (overextended) || Allowed
| A+, A, B || '''PASS''' - Proceed to entry
|-
|-
| Bottom Third || Allowed || Blocked
| C, D, F || '''BLOCKED''' - No trade
|}
|}


== Three-Finger Spread ==
== Filter 3: Hour [work in progress examples] ==
 
'''What it is:''' Large separation between Price, MA21, and MA200.
 
<pre>
Three-Finger Spread = When:
- Distance(Price to MA21) > 2% of price
- AND Distance(MA21 to MA200) > 2% of price
</pre>
 
'''Trading Impact:''' When detected, expect profit-taking soon (bearish for longs, bullish for shorts)
 
== Crash Bar Detection ==
 
'''What it is:''' Abnormally large bar indicating structural break.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Characteristic !! Threshold
! Hour !! Status !! Reason
|-
| 9 (9:00-9:59 AM) || '''BLOCKED''' || Market open volatility
|-
|-
| Bar Size || 2x average bar size
| 10-21 (10:00 AM - 9:59 PM) || '''ALLOWED''' || Normal trading hours
|-
|-
| Close Position || Within 30% of extreme
| 22 (10:00-10:59 PM) || '''BLOCKED''' || Near market close
|-
| 23 (11:00-11:59 PM) || '''BLOCKED''' || Market close
|}
|}


'''Trading Impact:''' Crash bar in sideways + top zone → Override to SHORT (Crash SHORT detection)
= PART 7: LAYER 5 - ENTRY TECHNIQUE =


----
== MA21 Zone Principle ==
 
<blockquote>
'''"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.
</blockquote>
 
== Why ±25 Points? ==


= PART 8: EXIT RULES =
* Price rarely touches MA exactly
* Allows for normal market noise


== Initial Stop Loss: 40 Points ==
== Entry Techniques ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Method !! Description
! 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
|-
|-
| '''Default''' || 40 points from entry
| GREEN_BAR_AFTER_PULLBACK || Long || Bullish candle after pullback to MA
|-
|-
| '''Structure-Based''' || Below recent swing low (LONG) / Above recent swing high (SHORT)
| RED_BAR_AFTER_RALLY || Short || Bearish candle after rally to MA
|-
|-
| '''MA-Based''' || MA21 value ± 25 points buffer
| BOS_ENTRY_LONG || Long || Break of structure to upside
|-
|-
| '''Minimum Enforced''' || Always at least 40 points
| BOS_ENTRY_SHORT || Short || Break of structure to downside
|}
|}


=== Stop Loss by Entry Technique ===
= PART 8: STOP LOSS CALCULATION =
 
== Stop Loss Methods (Priority Order) ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Technique !! Stop Placement
! Priority !! Method !! Description
|-
| NEAR_MA || 40 pts default
|-
|-
| BOS_ENTRY || Below/above structure (10-bar lookback + 5pt buffer)
| 1 || '''BOS-Based Stop''' || Below/above break of structure level
|-
|-
| MA_BOUNCE || Below/above MA21 zone
| 2 || '''Swing-Based Stop''' || Below recent swing low (LONG) or above swing high (SHORT)
|-
|-
| BREAKOUT_PULLBACK || Below/above pullback low/high (3-bar lookback)
| 3 || '''Default Stop''' || Fixed 40 points from entry
|}
|}


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


== DYNAMIC STOP MANAGEMENT (Two-Phase System) ==
== The 50% Rule ==


{{Note|'''IMPORTANT:''' Stop loss is NOT static! It moves dynamically to lock in profits.}}
<div style="background:#e6f3ff; border:1px solid #3399ff; padding:10px; margin:10px 0;">
'''Target = 50% of distance to MA21'''


=== Phase 1: Breakeven Stop (ENABLED) ===
For mean reversion trades, we target halfway back to moving average.
</div>


When trade reaches '''25 points profit''', stop moves to '''entry price + 2 pts'''.
== Why 50%? ==


{| class="wikitable"
* Conservative target ensures higher hit rate
|-
* Based on "divide the move in half" principle
! Parameter !! Value
* Captures partial reversion without being greedy
|-
* Works well with trailing stop to capture more
| Activation || 25 points in profit
|-
| New Stop || Entry price + 2 pts buffer
|-
| Purpose || Lock in small profit, eliminate loss
|}


'''Example (LONG at 5500):'''
== Minimum Target Rule ==


<pre>
<pre>
Entry: 5500
Minimum Target = Risk × 1.5
Original Stop: 5460 (40 pts risk)
 
Price reaches 5525 (25 pts profit)
Example:
→ Stop moves to 5502 (entry + 2 buffer)
  Entry: 5700
→ Worst case now = +2 pts profit (not -40 loss!)
  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)
</pre>
</pre>


=== Phase 2: Trailing Stop - ATR Based (ENABLED) ===
= PART 10: DYNAMIC STOP MANAGEMENT =


After '''20 points profit''', stop trails behind price using ATR (Average True Range).
== Two-Phase Protection ==
 
After entry, stops are managed dynamically in two phases:


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


'''How ATR Trailing Works:'''
== Phase 1: Breakeven Stop ==


<pre>
<pre>
IF current ATR = 12 points:
Configuration:
  Trailing Distance = 12 × 2 = 24 pts
  breakeven_activation = 25 points
 
  breakeven_buffer = 2 points
IF price moves to 5540 (LONG from 5500):
  New Stop = 5540 - 24 = 5516
  (Stop can only move UP, never back down)


IF volatility increases, ATR = 20:
Example (LONG from 5700):
  Trailing Distance = 20 × 2 = 40 pts (wider stop)
  Price reaches 5725 (+25 pts profit)
  This prevents getting stopped out in volatile moves
  → Stop moves from 5660 to 5702 (entry + 2)
  → Trade is now "risk-free"
</pre>
</pre>


=== Stop Movement Flow (LONG Example) ===
== Phase 2: Trailing Stop ==


<pre>
<pre>
Entry: 5500, Original Stop: 5460
Configuration:
  trailing_stop_activation = 20 points
  trailing_stop_method = ATR_MULTIPLE
  atr_period = 14 bars
  atr_multiplier = 2.0
  minimum_trail_distance = 15 points


Price hits 5520 (+20 pts):
Example (LONG from 5700, ATR = 12):
├── Trailing activates
  Trailing Distance = 12 × 2 = 24 points
├── ATR = 15 pts → Trail distance = 30 pts
└── New stop = 5520 - 30 = 5490


Price hits 5525 (+25 pts):
  Price at 5740:
├── Breakeven activates
  → Trail stop = 5740 - 24 = 5716
└── Stop moves to max(5490, 5502) = 5502


Price hits 5560 (+60 pts):
  Price at 5760:
├── Trail: 5560 - 30 = 5530
  → Trail stop = 5760 - 24 = 5736 (moved UP)
└── Stop is now 5530 (locked +30 pts profit!)


Price reverses to 5530:
  Price drops to 5736:
└── EXIT via STOP at 5530 = +30 pts profit
  → STOPPED OUT at 5736 (profit locked)
    (Shows as "stop" exit but is profitable!)
</pre>
</pre>


{{Note|'''This explains why 72.3% of exits are "stop" but many are profitable trades!'''}}
== Why Both Phases? ==
 
----
 
== Take Profit: 60 Points (1.5:1 R:R) ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Calculation !! Logic
! Phase !! Purpose
|-
| '''Primary''' || 50% of distance to MA21
|-
|-
| '''Minimum''' || Risk × 1.5 = 40 × 1.5 = 60 pts
| Breakeven || Eliminate risk quickly once trade moves in favor
|-
|-
| '''Final Target''' || MAX(50% to MA, 60 pts) = Usually 60 pts
| Trailing || Let winners run while protecting accumulated profit
|}
|}
'''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.


----
----


== Timeout: 8 Hours Maximum ==
= PART 11: SLIPPAGE & COSTS =


* If trade doesn't hit stop or target within 8 hours
== Slippage Model ==
* Exit at current market price
* Prevents overnight holding
 
----
 
== Slippage Modeling ==
 
Realistic execution costs are modeled:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Slippage Added
! Event !! Slippage !! Rationale
|-
|-
| Entry (base) || 1.0 points
| '''Entry''' || +1.0 point || Normal market fill
|-
|-
| Stop Loss exit || +2.0 points (worse fill in fast move)
| '''Stop Loss Exit''' || +2.0 points || Stops slip more in fast moves
|-
|-
| Take Profit exit || +0.5 points (better fill, limit order)
| '''Target Exit''' || +0.5 points || Limit orders have minimal slippage
|-
| Market Impact || Up to 2.0 points (capped)
|}
|}


'''Example:'''
== Cost Structure ==
* 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 =
 
== Blocked Trading Hours ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Hour !! IST Time !! Reason
! Cost Type !! Value
|-
| Commission || Rs 20 per lot per side
|-
|-
| 9 || 9:00-10:00 AM || Market open volatility
| STT || 0.01% on sell side
|-
|-
| 22 || 10:00-11:00 PM || Late session
| Exchange Fees || ~Rs 2 per lot
|-
|-
| 23 || 11:00-11:30 PM || Market close
| Stamp Duty || State-dependent
|}
|}


== Allowed Trading Hours ==
== Why Model Slippage? ==


Trading allowed: '''10 AM to 9 PM IST''' (Hours 10-21)
* 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 10: DIRECTION DETERMINATION =
= PART 12: EXIT RULES =
 
== MA21 Slope Alignment (Hard Filter) ==


The primary direction filter:
== 3 Exit Conditions ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! MA21 Slope !! Allowed Direction !! Logic
! Exit Type !! Condition
|-
|-
| '''Rising''' () || LONG only || Trade with uptrend
| '''Stop Loss''' || Price hits stop (original or trailing)
|-
|-
| '''Declining''' (↘) || SHORT only || Trade with downtrend
| '''Target''' || Price hits take profit level
|-
|-
| '''Flat''' () || Use MTF direction || Let higher timeframes decide
| '''Timeout''' || End of day (no overnight holds)
|}
|}


== Direction Determination Algorithm ==
= PART 13: PUTTING IT ALL TOGETHER =


<source lang="python">
== Trade Flow ==
def determine_direction(ma21_slope, mtf_direction):
    if ma21_slope == "rising":
        return LONG  # Only longs in uptrend


    elif ma21_slope == "declining":
<pre>
        return SHORT # Only shorts in downtrend
┌─────────────────────────────────────────────────────────────────┐
 
│  STEP 1: Load data for all 5 timeframes                        │
    else# Flat
│  Daily, 4H, 1H, 15M, 5M OHLCV data                            │
        return mtf_direction # Use multi-timeframe consensus
└─────────────────────────────────────────────────────────────────┘
</source>
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  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>


----
----


= PART 11: RISK MANAGEMENT =
= PART 14: HARD vs SOFT FILTERS =


== Position Sizing ==
== Understanding the Difference ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter !! Value
! Filter Type !! Behavior !! Examples
|-
|-
| Position Size || 1 lot (100 barrels)
| '''HARD''' || Blocks trade completely || Direction filter, Hour filter, Grade C/D/F
|-
|-
| Risk per Trade || 40 pts × 100 = Rs 4,000
| '''SOFT''' || Affects quality score || MTF alignment, Market state penalties
|-
| Reward per Trade || 60 pts × 100 = Rs 6,000
|-
| Max Concurrent Trades || 1
|}
|}


== Cost Structure ==
== Complete Filter List ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Cost Type !! Value
! 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
|-
|-
| Brokerage || Rs 20 per lot per leg (Dhan)
| No Two-Day Trend || SOFT || -30 points penalty
|-
|-
| CTT || 0.01% on sell side
| Institutional Fight || SOFT || 0.7× score multiplier
|-
|-
| Total Round-trip || ~Rs 95 per trade
| Far from MA21 || SOFT || -40 points penalty
|}
|}


----
----


= PART 12: EQUITY CURVE =
= APPENDIX A: CONFIGURATION VALUES =
 
[[File:equity_curve.png|800px|center|Equity Curve]]
 
----


= PART 13: BACKTEST RESULTS (19 Months) =
== MTF Configuration ==
 
== Summary Statistics ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Parameter !! Value !! Source File !! Description
|-
|-
| Initial Capital || Rs 1.00 Lakhs
| context_timeframe || DAILY || main.py:162 || Highest timeframe for overall bias
|-
|-
| Final Value || Rs 26.48 Lakhs
| primary_timeframe || 1-HOUR || main.py:163 || Primary trend direction
|-
|-
| Total Profit || Rs 25.48 Lakhs
| confirmation_timeframe || 15-MIN || main.py:164 || Entry timing confirmation
|-
|-
| Total Return || '''2,548%'''
| entry_timeframe || 5-MIN || main.py:165 || Execution timeframe
|-
|-
| Peak Value || Rs 28.35 Lakhs
| require_all_timeframes_aligned || '''False''' || main.py:166 || Allow partial alignment
|-
|-
| Max Drawdown || -78.6%
| 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
|}
|}


== Trade Statistics ==
== Entry Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Metric !! Value
! Parameter !! Value !! Source File
|-
|-
| Total Trades || 7,534
| entry_timeframe || 5-Minute || main.py:165
|-
|-
| Win Rate || 57.6%
| ma_buffer_points || 25 points || signal_generation_trade_management.py:68
|-
|-
| Profit Factor || 1.20
| blocked_hours || [9, 22, 23] || signal_generation_trade_management.py:137
|-
|-
| Average Win || Rs 3,464
| enable_hour_filter || True || signal_generation_trade_management.py:89
|-
|-
| Average Loss || Rs 3,904
| enable_ma_direction_filter || True || signal_generation_trade_management.py:97
|}
 
== Stop/Target Configuration ==
 
{| class="wikitable"
|-
|-
| Largest Win || Rs 26,799
! Parameter !! Value !! Source File
|-
|-
| Largest Loss || Rs 13,217
| min_stop_distance || 40 points || signal_generation_trade_management.py:59
|-
|-
| Avg Holding Time || 2.4 hours
| default_risk_reward || 1.5 || signal_generation_trade_management.py:62
|-
| bos_stop_buffer_points || 5 points || signal_generation_trade_management.py:81
|}
|}


== Exit Reason Breakdown ==
== Dynamic Stop Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Exit Type !! Count !! % !! Note
! 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
|-
|-
| Stop || 5,444 || 72.3% || Includes trailing stop profits
| enable_breakeven_stop || True || trade_execution_engine.py:69
|-
|-
| Target || 1,716 || 22.8% || 100% winners
| breakeven_activation || 25 points || trade_execution_engine.py:70
|-
|-
| Timeout || 374 || 5.0% || 8-hour limit
| breakeven_buffer || 2 points || trade_execution_engine.py:71
|-
| minimum_trail_distance || 15 points || trade_execution_engine.py:370
|}
|}


== Direction Distribution ==
== Slippage Configuration ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Direction !! Count !! %
! 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
|-
|-
| 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
|}
|}


== Setup Quality Distribution ==
== Trade Execution Limits ==


{| class="wikitable"
{| class="wikitable"
|-
|-
! Grade !! Count !! %
! 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
|-
|-
| A+ || 3,457 || 45.9%
| max_concurrent_trades || '''3''' || trade_execution_engine.py:55 || Maximum simultaneous open trades
|-
|-
| A || 551 || 7.3%
| market_close_buffer_minutes || '''15 minutes''' || trade_execution_engine.py:75 || Close trades before market close
|-
|-
| C || 3,526 || 46.8%
| avoid_news_minutes || 30 minutes || trade_execution_engine.py:74 || Buffer around news events
|}
|}


''Note: C-grade trades were analyzed but NOT executed per strategy rules''
== Cost Configuration ==
 
----
 
= PART 14: HARD vs SOFT FILTERS =
 
Understanding which rules reject trades outright vs which just affect scoring:
 
== HARD FILTERS (Trade Rejected if Failed) ==
 
These filters '''block trades entirely''' - no exceptions:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Filter !! Rule !! Effect
! Parameter !! Value !! Source File !! Description
|-
|-
| '''MA21 Slope Alignment''' || Direction must match MA21 slope || Rising MA = LONG only, Declining MA = SHORT only
| commission_per_lot || '''Rs 20/lot/leg''' || signal_generation_trade_management.py:49 || Dhan broker commission
|-
|-
| '''Setup Grade''' || Must be A+, A, or B || C/D/F grades = NO TRADE
| transaction_tax_rate || '''0.005% per leg''' || signal_generation_trade_management.py:55 || CTT (0.01% round-trip)
|-
|-
| '''Hour Filter''' || Hours 9, 22, 23 blocked || Market open/close = NO TRADE
| lot_size_multiplier || '''100 barrels''' || signal_generation_trade_management.py:56 || MCX Crude lot size
|-
|-
| '''Price in MA Zone''' || Must be within ±25 pts of MA21 || Too far from MA = NO TRADE
| initial_capital || '''Rs 1,00,000''' || main.py:1131 || Starting capital for backtest
|}
|}


== SOFT FILTERS (Affect Score, Don't Block) ==
== Grading 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 File
|-
|-
| '''MTF Alignment''' || 30% weight in grading || Yes, if other factors strong
| timeframe_alignment_weight || 30% || setup_quality_detection.py:44
|-
|-
| '''Creeper Move''' || -50 penalty || Yes, if base score high enough
| trend_strength_weight || 20% || setup_quality_detection.py:45
|-
|-
| '''Railroad Trend''' || +15 bonus || N/A (bonus not required)
| key_level_proximity_weight || 20% || setup_quality_detection.py:47
|-
|-
| '''Price-MA Struggle''' || -30 penalty || Yes, if other factors compensate
| entry_technique_weight || 15% || setup_quality_detection.py:46
|-
|-
| '''Wrong Trend Phase''' || -25 penalty || Yes, if other factors compensate
| risk_reward_weight || 15% || setup_quality_detection.py:48
|-
|-
| '''Key Level Proximity''' || 20% weight in grading || Yes, affects grade not rejection
| a_plus_min_score || 90 || setup_quality_detection.py:51
|-
|-
| '''Institutional Fight''' || 0.7x multiplier || Yes, reduces but doesn't block
| a_min_score || 80 || setup_quality_detection.py:52
|-
| b_min_score || 70 || setup_quality_detection.py:53
|}
|}


== Filter Flow ==
== Probability Zone Configuration ==
 
<pre>
ENTRY CANDIDATE
      │
      ▼
┌─────────────────────────────────────────┐
│  HARD FILTERS (any fail = NO TRADE)    │
│  • MA21 slope alignment                │
│  • Hour filter                          │
│  • Price in MA zone                    │
└─────────────────────────────────────────┘
      │ ALL PASS
      ▼
┌─────────────────────────────────────────┐
│  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 =


{| class="wikitable"
{| class="wikitable"
|-
|-
! File !! Purpose
! Parameter !! Value !! Source File
|-
| enable_probability_zone_filter || True || signal_generation_trade_management.py:104
|-
|-
| <code>trend_analysis_core.py</code> || MA slope, trend direction, price-MA struggle
| probability_zone_swing_lookback || 20 bars || signal_generation_trade_management.py:105
|-
|-
| <code>multi_timeframe_analysis.py</code> || MTF alignment scoring (5 timeframes)
| probability_zone_min_range || 20 points || signal_generation_trade_management.py:106
|-
|-
| <code>market_state_analysis.py</code> || Market state detection (7 algorithms)
| top_third_threshold || 66.7% || probability_zone_analysis.py:125
|-
|-
| <code>setup_quality_detection.py</code> || 5-factor grading system
| top_third_probability || 80% || probability_zone_analysis.py:131
|-
|-
| <code>probability_zone_analysis.py</code> || Zone-based filtering, Three-Finger Spread
| bottom_third_probability || 15% || probability_zone_analysis.py:134
|-
|-
| <code>signal_generation_trade_management.py</code> || Entry/Exit logic, stop/target calculation
| crash_bar_multiplier || 2.0 || probability_zone_analysis.py:145
|-
|-
| <code>trade_execution_engine.py</code> || Breakeven, Trailing stop, Slippage, Timeout
| 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: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