Jump to content

Alpha Research: Difference between revisions

From PlusEV Wiki Page
No edit summary
No edit summary
 
(104 intermediate revisions by 7 users not shown)
Line 1: Line 1:
# Alpha Research: MCX Crude Oil MA21 Strategy
= Multi_Timeframe Dynamic Trend (MTFDR) =
----


**Single Source of Truth for the PlusEV Trading System**
= PART 1: STRATEGY OVERVIEW =


---
== What Is This Strategy? ==


## Quick Reference: Backtest Proof
'''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.


| Metric | Value | Notes |
== Layered Architecture (Top-Down) ==
|--------|-------|-------|
| **Total P&L** | Rs +25,48,101 | 19-month validation period |
| **Win Rate** | 57.6% | Above 55% threshold |
| **Profit Factor** | 1.20 | Risk-adjusted returns |
| **Total Trades** | 7,534 | Statistical significance |
| **Initial Capital** | Rs 1,00,000 | Starting portfolio |
| **Final Capital** | Rs 26,48,101 | 2548% return |


**Branch**: `rikk_mtf_backtest001` | **Commit**: `68dae212`
<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>


> "In trading systems, empirical results > theoretical understanding. If the backtest shows it works, we ship it."
= PART 2: Core Concept (Why This Works) =


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


# Part 1: Core Trading Philosophy
{| class="wikitable"
|-
! 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
|}


## 1.1 Foundational Principles
== The Math ==


```
If each layer has 70% accuracy independently:
Simple systems outperform complex ones.
* Single layer: 70% edge
Market behavior is probabilistic, not predictive.
* 2 layers: 70% × 70% = 49% of trades pass, but higher quality
The goal is positioning with asymmetric probabilities, not prediction.
* 5 layers: Only the '''best setups''' survive all filters
```


### The Asymmetric Probability Edge
'''Result:''' Fewer trades, but each trade has multiple confluences supporting it.


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 the high-probability side


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


## 1.2 Probability Zones (Halves & Thirds)
<div style="background:#e6ffe6; border:1px solid #00cc00; padding:10px; margin:10px 0;">
'''THIS IS THE FOUNDATION''' - Everything else builds on top of MTF alignment. If timeframes disagree, we don't trade.
</div>


Every large move is divided into **halves and thirds**, creating probability zones.
== The 5 Timeframes ==


### Odds of Continuation After Pullback
{| class="wikitable"
|-
! 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 ==
┌─────────────────────────────────────────────────────┐
│  SWING HIGH                                        │
├─────────────────────────────────────────────────────┤
│  TOP THIRD        →  ~80% chance of new high        │  ← IDEAL SHORT ZONE
├─────────────────────────────────────────────────────┤
│  TOP HALF        →  ~65% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM HALF      →  ~35% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM THIRD    →  ~15% chance of new high        │  ← IDEAL LONG ZONE
├─────────────────────────────────────────────────────┤
│  SWING LOW                                          │
└─────────────────────────────────────────────────────┘
```
 
### Code Implementation
```python
# File: signal_generation_trade_management.py:99-109
enable_probability_zone_filter: bool = True
probability_zone_swing_lookback: int = 20    # Bars to find swing H/L
probability_zone_min_range: float = 20.0    # Min range for valid zone
```
 
---
 
## 1.3 The Crash Play (Core Strategy)
 
### What is a Crash Bar?
- **Much larger** than recent bars
- **Fast, violent, elongated** movement
- Indicates a **structural break**
 
### The Crash Play Logic
 
```
1. Identify crash bar (bar > 2x average size)
2. Divide it into halves and thirds
3. Watch for bounce INTO these zones
4. Enter when:
  - Color change confirms (red overtakes green), OR
  - Price reaches upper zones
```


### Key Statistics
For each of 5 timeframes, our system calculates:
- After a crash, bounces have only **~15% odds** of reclaiming highs
- **~85% odds** favor continuation lower
- **Bounces after crashes are statistically SHORT opportunities**


### Code Implementation
{| class="wikitable"
```python
|-
# File: signal_generation_trade_management.py:108
! Analysis !! Description
crash_bar_multiplier: float = 2.0  # Bar must be 2x average for crash detection
|-
```
| '''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 ==


## 1.4 Pullback vs Collapse (Critical Distinction)
<pre>
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


### Healthy Pullback (Tradeable)
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
</pre>


| Characteristic | Description |
== Why MTF Matters ==
|----------------|-------------|
| Angle | 45-degree drifting decline, NOT vertical |
| Bars | No violent or oversized red bars |
| Depth | Holds **above halfway point** of prior run |
| Confirmation | Color change (green overtakes red) |


**Interpretation**: Pullbacks are rests, not reversals. Odds favor continuation.
{| class="wikitable"
|-
! 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'''
|}


### Collapse (NOT Tradeable)
----


| Characteristic | Description |
= PART 4: LAYER 2 - MARKET STATE ANALYSIS =
|----------------|-------------|
| Angle | Vertical, elongated, violent first drop |
| Depth | Breaks deeply into or below prior run |
| Momentum | Abrupt and forceful |


**Interpretation**: Indicates institutional selling. Bounces are sucker plays.
== The 7 Market State Algorithms ==


---
Our system runs 7 independent algorithms to understand current market context:


## 1.5 Identifying Market Tops (4 Characteristics)
{| class="wikitable"
|-
! # !! 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
|}


Major tops usually exhibit **at least 2 of these 4 characteristics**:
== Penalty System ==


### 1. Three-to-Five Leg Run-Up
{| class="wikitable"
```
|-
Markets top between leg 3 and leg 5.
! Condition !! Penalty !! Rationale
- Buy: legs 1-2
|-
- Ride: leg 3
| Creeper Move Detected || '''-50 points''' || Slow trends often reverse suddenly
- Take profits: legs 4-5
|-
- Buying late (leg 4-5) = large downside vs small upside
| 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
|}


### 2. Vertical Acceleration in Final Leg
== Bonus System ==
```
If the last leg is STEEPER than prior legs → likely final leg
The most vertical leg is usually the top.
```


### 3. Exhaustion Bar
{| class="wikitable"
```
|-
Final bar of final leg is:
! Condition !! Bonus !! Rationale
- Larger than recent bars
|-
- Often the largest bar of entire run
| Railroad Tracks || '''+15 points''' || Strong momentum confirmation
= Bulls deploy all remaining buying power
|-
= Market becomes top-heavy and vulnerable
| At Key Level || +10 points || Technical confluence present
```
|-
| Clean Entry Setup || +10 points || Clear technical pattern
|}


### 4. Three-Finger Spread (Dual Space)
== Probability Zone Analysis ==
```
Large separation between:
- Price
- 21-period MA
- 200-period MA


= Many traders holding large unrealized profits
=== The Asymmetric Probability Edge ===
= Any red bar can trigger mass profit-taking
= Creates fast, violent declines
```


### Code Implementation
When odds are low on one outcome, '''the opposite side usually carries high odds''':
```python
* If new high probability drops to 15%, then '''85% odds favor reversal'''
# File: signal_generation_trade_management.py:107
* We position ourselves on high-probability side where price position within recent range determines continuation probability:
three_finger_spread_threshold: float = 0.02  # 2% min spread for detection
* Every large move is divided into '''halves and thirds''', creating probability zones.
```
=== Odds of Continuation After Pullback ===
 
<pre>
---
 
# Part 2: Entry Methodology
 
## 2.1 The Fab Four Concept
 
The **Fab Four** defines the key reference points for entries and stops:
 
```
┌─────────────────────────────────────────────────────┐
┌─────────────────────────────────────────────────────┐
│  FAB FOUR ELEMENTS                                 
│  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        │ 
├─────────────────────────────────────────────────────┤
├─────────────────────────────────────────────────────┤
│  1. Previous Day High/Low (PDHL)                    │
│  SWING LOW                                         
│  2. 21-Period Moving Average                        │
│  3. 200-Period Moving Average                      │
│  4. Yesterday's Close                             
└─────────────────────────────────────────────────────┘
└─────────────────────────────────────────────────────┘
```
</pre>


### MA is a ZONE, Not a Line
{| class="wikitable"
|-
! 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
|}


> "The MA is a zone, not a thin line. Don't be exact with this."
=== 3-Finger Spread ===


```python
Measures separation between Price, 21 MA, and 200 MA:
# File: signal_generation_trade_management.py:68
ma_buffer_points: float = 25.0  # 21 MA zone width (not a thin line)
```


### Fab Four Tightness = Explosive Potential
<pre>
Three-Finger Spread Detection:
  - Large spread between Price/21MA/200MA
  - Indicates profit-taking pressure imminent
  - Minimum spread threshold: 2% of price


When the Fab Four elements are **tight together**:
Structure Types:
- Indicates compressed energy
  UPTREND:    Price > 21 MA > 200 MA (bullish stack)
- Expect **powerful move** (up or down)
  DOWNTREND:  Price < 21 MA < 200 MA (bearish stack)
- Best trades come from **narrowness**
  SIDEWAYS:  No clear MA separation
</pre>


---
=== Crash Bar Detection ===
 
## 2.2 Entry Position Hierarchy
 
### Best Entry Positions
 
```
FOR SHORTS:
┌─────────────────────────────────────────────────────┐
│  CEILING (Best short position)                      │
│  ═══════════════════════════════════════════        │  ← Price right under Fab Four
│  Price opens HERE                                  │
└─────────────────────────────────────────────────────┘
 
FOR LONGS:
┌─────────────────────────────────────────────────────┐
│  Price opens HERE                                  │
│  ═══════════════════════════════════════════        │  ← Price right above Fab Four
│  FLOOR (Best long position)                        │
└─────────────────────────────────────────────────────┘
```


### Multi-Timeframe Alignment
Identifies structural breaks via unusually large bars:


Check all timeframes simultaneously:
{| class="wikitable"
|-
! 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 ===
┌────────┬────────┬────────┬────────┐
│  2min  │  5min  │  15min │  Daily │
│  ────  │  ────  │  ────  │  ────  │
│ Under  │ Under  │ Under  │ Under  │
│  200  │  200  │  200  │  200  │
│ Tight  │ Tight  │ Tight  │ Tight  │
└────────┴────────┴────────┴────────┘
        = ALIGNED = HIGH QUALITY SETUP
```


### Code Implementation
{| class="wikitable"
```python
|-
# File: setup_quality_detection.py:43-48
! Type !! Characteristics !! Action
timeframe_alignment_weight: float = 0.30  # 30% of setup quality score
|-
```
| '''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 ===


## 2.3 Bar-by-Bar vs Big Bar Stops
Probability zones filter signals:


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


| When to Use | Stop Method | Why |
if zone_position < 33.3%:  # Bottom third
|-------------|-------------|-----|
    # Block LONG signals (only 15% chance of continuation)
| **Near MA** (hugging) | Big Bar stops | Eliminates noise |
    # Allow SHORT signals
| **Far from MA** (extended) | Bar-by-bar stops | Protect extended gains |


### The Warning
if zone_position > 66.7%:  # Top third
    # Allow LONG signals (80% continuation)
    # Block SHORT signals


> "Bar-by-bar will knock you out of riches. If there is one stopout that is going to knock you out of the biggest gains of your life, it's going to be bar-by-bar."
= PART 5: LAYER 3 - SETUP QUALITY GRADING =


**Use bar-by-bar ONLY when:**
== The 5-Factor Scoring System ==
- Price has moved significantly away from MA
- "You had better be moving to Pluto"
- Slant on both 2min and 5min is sharp


---
Every potential trade is scored on 5 factors:


# Part 3: Stop Loss Methodology
{| class="wikitable"
|-
! 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?
|}


## 3.1 Stop Placement Hierarchy
<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>


### Two Stop Options
== Grade Thresholds ==


| Type | Description | When to Use |
{| class="wikitable"
|------|-------------|-------------|
|-
| **Event Stop** | Based on price action event | Primary choice |
! Grade !! Score Range !! Action !! Position Size
| **Maximum Stop** | Dollar-based max loss | Fallback when event too far |
|-
| '''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''' || -
|}


### The Goal
== A+ Grade Special Requirements ==


```
To achieve A+ grade, ALL conditions must be true:
┌─────────────────────────────────────────────────────┐
* Final score ≥ 90
│  FAB FOUR ZONE (Helping Zone)                      │
* All 5 timeframes aligned with trade direction
├─────────────────────────────────────────────────────┤
* Entry within ±25 points of MA21
│  ↑ STOP SHOULD BE HERE (above/below Fab Four)      │
* Two-day trend present on Daily
├─────────────────────────────────────────────────────┤
* No institutional fight detected
│  Entry price                                        │
└─────────────────────────────────────────────────────┘
```


> "The real goal is to get your stop beyond the Fab Four helping zone."
== Score Calculation Example ==


### Code Implementation
<pre>
```python
Trade Setup: LONG on 5-min chart
# File: signal_generation_trade_management.py:59-60
min_stop_distance: float = 40.0    # TICKET-13: Increased from 20
default_stop_distance: float = 40.0  # Minimum buffer for price noise
```


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


## 3.2 Stop and Reverse Rules
Penalties Applied:
  - No Railroad Tracks: 0
  - No Creeper: 0
  - Has Two-Day: 0
                              ──────────
  Final Score: 80.75 → Grade: A
</pre>


Three criteria for a valid **Stop and Reverse**:
----


| Criteria | Description |
= PART 6: HARD LAYER 4 - FILTERS=
|----------|-------------|
| **1. Immediate** | Stop out happens INSTANTLY, not gradually |
| **2. Violent** | Move that stops you is hard, powerful, shakes earth |
| **3. Decent Position** | New position is NOT into resistance/support |


### Invalid Stop and Reverse
<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>


```
== 3 Hard Filters ==
❌ Going LONG right INTO the 200 MA
❌ Going LONG right INTO tight Fab Four zone
❌ Going SHORT right INTO strong support


Even if immediate + violent, bad position = no reversal
{| class="wikitable"
```
|-
! 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
|}


### Code Implementation
== Filter 1: Direction (MA21 Slope) ==
```python
# File: signal_generation_trade_management.py:80-81
bos_structure_lookback: int = 10  # TICKET-11: Extended for BOS stops
bos_stop_buffer_points: float = 5.0  # Buffer for structure-based stops
```


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


# Part 4: Color Change Confirmation
== Filter 2: Grade ==


## 4.1 The Color Change Entry
{| class="wikitable"
|-
! Grade !! Action
|-
| A+, A, B || '''PASS''' - Proceed to entry
|-
| C, D, F || '''BLOCKED''' - No trade
|}


### Entry Trigger
== Filter 3: Hour [work in progress examples] ==
```
FOR SHORTS:
Red bar closes BELOW green bar's low → ENTER SHORT
Stop: Above the high


FOR LONGS:
{| class="wikitable"
Green bar closes ABOVE red bar's high → ENTER LONG
|-
Stop: Below the low
! 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
|}


### Key Rule: Don't Wait for Bar to Complete
= PART 7: LAYER 5 - ENTRY TECHNIQUE =


> "As soon as the red bar crosses below the green, boom boom boom boom boom. You're in."
== MA21 Zone Principle ==


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


## 4.2 Profit Taking Rules
Entry is allowed within '''±25 points''' of MA21, not just at the exact MA value.
</blockquote>


### The Two-Bar Rule
== Why ±25 Points? ==


> "Take profits TWO bars after the opposite color, NOT one bar."
* Price rarely touches MA exactly
* Allows for normal market noise


```
== Entry Techniques ==
SHORT TRADE:
┌─────────────────────────────────────────────────────┐
│  GREEN bar (opposite color)                        │
├─────────────────────────────────────────────────────┤
│  RED bar 1 ← IGNITING bar (DO NOT take profit)      │
├─────────────────────────────────────────────────────┤
│  RED bar 2 ← FOLLOW-THROUGH bar (TAKE PROFIT)      │
└─────────────────────────────────────────────────────┘
```


### Position Management Flow
{| class="wikitable"
|-
! 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 =
Step 1: Enter with 2 lots
Step 2: Set stop above high
Step 3: Take profit on 1 lot (first follow-through bar)
Step 4: Move stop to break-even
Step 5: Take profit on remaining lot (second follow-through)
Step 6: Done
```


> "The first lot is your REAL trade. The second lot is the cherry on top."
== Stop Loss Methods (Priority Order) ==


### Code Implementation
{| class="wikitable"
```python
|-
# File: signal_generation_trade_management.py:111-118
! Priority !! Method !! Description
enable_color_change_filter: bool = False    # DISABLED - too restrictive
|-
color_change_ma_proximity: float = 20.0      # Points to consider "near" MA
| 1 || '''BOS-Based Stop''' || Below/above break of structure level
require_ma_bounce: bool = False              # Don't require strict MA bounce
|-
```
| 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 ==


## 4.3 The Traffic Jam Concept
<div style="background:#ffffcc; border:1px solid #ffcc00; padding:10px; margin:10px 0;">
'''MINIMUM: 40 points'''
</div>


When price gaps below **everything from prior day**:
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 =
┌─────────────────────────────────────────────────────┐
│  Yesterday's 200 MA                                │
│  Yesterday's 20 MA                                  │
│  Yesterday's Close                                  │
│  ═══════════════════════════════════════════        │
│  TRAFFIC JAM ZONE (resistance on any rally)        │
│  ═══════════════════════════════════════════        │
│                                                    │
│  TODAY'S GAP DOWN OPEN                              │
└─────────────────────────────────────────────────────┘
```


**Rule**: Any move UP into the traffic jam meets resistance. Short rallies into this zone.
== The 50% Rule ==


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


# Part 5: Trading Glossary for Engineers
For mean reversion trades, we target halfway back to moving average.
</div>


| Trading Term | System Translation | Code Location | Why It Matters |
== Why 50%? ==
|--------------|-------------------|---------------|----------------|
| **Creeper Move** | Small-bodied bars, consistent direction, low volume | `market_state_analysis.py:is_creeper_move` | Institutional accumulation before explosion. **PENALTY: -50 points** |
| **Railroad Trend** | Alternating green/red bars touching MA | `market_state_analysis.py:is_railroad_trend` | Healthy trend, not overextended. **BONUS: +15 points** |
| **Two-Day Trend** | Price consistently above/below MA for 2+ days | `market_state_analysis.py:has_two_day_trend` | Confirms trend maturity. **Required for A+ grade** |
| **Institutional Fight** | High volume with narrow range | `market_state_analysis.py:institutional_fight_in_progress` | Buyers vs sellers battle. **MULTIPLIER: 0.7x score** |
| **Discount Zone** | Price below 21 MA (for longs) | `probability_zone_analysis.py` | 80% continuation probability |
| **Premium Zone** | Price above 21 MA (for shorts) | `probability_zone_analysis.py` | Entry zone for short trades |
| **Fab Four** | PDHL, 21 MA, 200 MA, Yesterday's Close | `signal_generation.py:_calculate_stop_loss()` | Stop loss placement hierarchy |
| **Color Change** | Bar closes opposite color after move | `probability_zone_analysis.py:ColorChangeDetector` | Confirms reversal/continuation |
| **Break of Structure (BOS)** | Price closes beyond recent swing H/L | `market_state_analysis.py:bos_detected` | Confirms trend continuation/reversal |
| **MA Zone** | MA is a band, not thin line (21 MA +/- 25pts) | `signal_generation.py:ma_buffer_points=25` | "Fab Four" concept from philosophy |
| **Trend Phase** | EARLY / MIDDLE / LATE classification | `market_state_analysis.py:trend_phase` | MIDDLE phase = optimal entry timing |
| **Crash Bar** | Bar > 2x average size, violent | `probability_zone_analysis.py:crash_bar_multiplier` | Structural break indicator |
| **Traffic Jam** | Yesterday's price activity zone | Conceptual | Resistance zone for gaps |
| **Three-Finger Spread** | Large gap between Price, 21 MA, 200 MA | `signal_generation.py:three_finger_spread_threshold` | Market top indicator |


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


# Part 6: Component Architecture
== Minimum Target Rule ==


## 6.1 Pipeline Flow
<pre>
Minimum Target = Risk × 1.5


```
Example:
┌─────────────────┐   ┌───────────────────┐  ┌────────────────────┐
   Entry: 5700
│  Data Manager   │ → │  Trend Analysis  │ → │  Market State      │
   Stop: 5660 (40 points risk)
│  (1M/5M/1H/1D) │  │  (MA21, MA200)    │  │  (7 Detections)    │
└─────────────────┘  └───────────────────┘  └────────────────────┘
                                                      ↓
┌─────────────────┐  ┌───────────────────┐  ┌────────────────────┐
│  Trade Exec    │ ← │  Signal Gen      │ ← │  Setup Quality    │
│  (P&L, Costs)  │  │  (Entry/Exit)    │  │  (5-Factor Score)  │
└─────────────────┘  └───────────────────┘  └────────────────────┘
```


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


## 6.2 Setup Quality Detection
  Final Target: 5760 (60 points)
</pre>


**File**: `src/components/setup_quality_detection.py`
= PART 10: DYNAMIC STOP MANAGEMENT =


### 5-Factor Weighted Scoring System
== Two-Phase Protection ==


| Factor | Weight | What It Measures |
After entry, stops are managed dynamically in two phases:
|--------|--------|------------------|
| Timeframe Alignment | **30%** | All timeframes agree on direction |
| Trend Strength | **20%** | Healthy trend without warnings |
| Entry Quality | **15%** | Entry near MA, clean execution |
| Key Level Proximity | **20%** | Entry near support/resistance |
| Risk/Reward | **15%** | Favorable profit potential |


### Penalty System
{| class="wikitable"
|-
! 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
|}


| Condition | Penalty | Trading Reason |
== Phase 1: Breakeven Stop ==
|-----------|---------|----------------|
| Creeper Move | -50 pts | Quiet accumulation = reversal coming |
| MA Struggle | -30 pts | Price can't break MA = weak trend |
| No Two-Day Trend | -30 pts | Trend not confirmed |
| Wrong Trend Phase | -25 pts | Too early or too late in trend |
| Not Near MA | -40 pts | Entry too far from edge |
| Institutional Fight | 0.7x | Wait for resolution |


### Grade Thresholds
<pre>
Configuration:
  breakeven_activation = 25 points
  breakeven_buffer = 2 points


| Grade | Score | Position Size | Auto-Trade? |
Example (LONG from 5700):
|-------|-------|---------------|-------------|
  Price reaches 5725 (+25 pts profit)
| A+ | >= 90 | 2 lots | Yes |
  → Stop moves from 5660 to 5702 (entry + 2)
| A | >= 80 | 1 lot | Yes |
  → Trade is now "risk-free"
| B | >= 70 | 1 lot | No |
</pre>
| C | >= 60 | 1 lot | No |
| D | >= 50 | 1 lot | No |
| F | < 50 | 1 lot | No |


---
== Phase 2: Trailing Stop ==


## 6.3 Market State Analysis
<pre>
Configuration:
  trailing_stop_activation = 20 points
  trailing_stop_method = ATR_MULTIPLE
  atr_period = 14 bars
  atr_multiplier = 2.0
  minimum_trail_distance = 15 points


**File**: `src/components/market_state_analysis.py`
Example (LONG from 5700, ATR = 12):
  Trailing Distance = 12 × 2 = 24 points


### 7 Detection Algorithms
  Price at 5740:
  → Trail stop = 5740 - 24 = 5716


| # | Algorithm | What It Detects | Trading Implication |
  Price at 5760:
|---|-----------|-----------------|---------------------|
  → Trail stop = 5760 - 24 = 5736 (moved UP)
| 1 | Railroad Trend | Healthy alternating bars | +15 bonus, trend continuation likely |
| 2 | Creeper Move | Small bars, consistent direction | -50 penalty, reversal imminent |
| 3 | Volatility Calc | ATR-based regime | Adjust stop distance |
| 4 | Market State | TRENDING / SIDEWAYS / VOLATILE | Different strategy rules |
| 5 | Two-Day Trend | Multi-day momentum | Required for A+ grade |
| 6 | Trend Phase | EARLY / MIDDLE / LATE | MIDDLE = optimal entry |
| 7 | Institutional Behavior | Volume + price patterns | Fight = wait, Accumulation = prepare |


---
  Price drops to 5736:
  → STOPPED OUT at 5736 (profit locked)
</pre>


## 6.4 Signal Generation
== Why Both Phases? ==


**File**: `src/components/signal_generation_trade_management.py`
{| class="wikitable"
|-
! Phase !! Purpose
|-
| Breakeven || Eliminate risk quickly once trade moves in favor
|-
| Trailing || Let winners run while protecting accumulated profit
|}


### Entry Filters Applied
----


| Filter | Config Key | Purpose |
= PART 11: SLIPPAGE & COSTS =
|--------|------------|---------|
| Hour Filter | `blocked_hours: [9, 22, 23]` | Block loss-making hours |
| MA Direction | `enable_ma_direction_filter: True` | LONG only if MA rising |
| Probability Zone | `enable_probability_zone_filter: True` | Entry in favorable zones |
| Color Change | `enable_color_change_filter: False` | Disabled (too restrictive) |


---
== Slippage Model ==


# Part 7: Branch Changes (develop -> rikk_mtf_backtest001)
{| class="wikitable"
|-
! 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
|}


## 7.1 JIRA Fixes with Trading Context
== Cost Structure ==


| Ticket | Change | Trading Reason | Code Reference |
{| class="wikitable"
|--------|--------|----------------|----------------|
|-
| **TICKET-5** | Position sizing: 100 -> 1-2 lots | Rs 1L capital = max 2 lots realistic | `setup_quality_detection.py:545-579` |
! Cost Type !! Value
| **TICKET-7** | R:R preserved after slippage | Stop/target shift maintains edge | `signal_generation.py:250-272` |
|-
| **TICKET-8** | CTT rate: 0.05% -> 0.01% | Matched Dhan broker actual rates | `signal_generation.py:53-55` |
| Commission || Rs 20 per lot per side
| **TICKET-11** | BOS stop: 5 -> 10 bar lookback | Trend entries need wider stops | `signal_generation.py:80-81` |
|-
| **TICKET-12** | Hour filter: block 9, 22, 23 | Data-driven loss-making hours | `signal_generation.py:135-137` |
| STT || 0.01% on sell side
| **TICKET-13** | Min stop: 20 -> 40 points | Price noise hits tight stops | `signal_generation.py:59` |
|-
| **TICKET-19** | MA direction alignment | LONG only when MA21 rising | `signal_generation.py:96-97` |
| Exchange Fees || ~Rs 2 per lot
| **TICKET-20** | Probability zone filter | Top third = 80% continuation | `signal_generation.py:99-109` |
|-
| **TICKET-21** | Color change detector | Liquidity sweep confirmation | `signal_generation.py:111-118` |
| Stamp Duty || State-dependent
| **TICKET-25** | 1-hour data for market state | Creeper detection needs higher TF | `market_state_analysis.py:209-222` |
|}


---
== Why Model Slippage? ==


## 7.2 Key Files Added/Modified
* 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


### New Components (Entire `src/` directory)
----
```
services/backtest/src/
├── components/
│  ├── market_state_analysis.py      # 7 detection algorithms
│  ├── setup_quality_detection.py    # 5-factor scoring
│  ├── signal_generation_trade_management.py  # Entry/exit logic
│  ├── probability_zone_analysis.py  # Halves/thirds zones
│  └── trend_analysis_core.py        # MA calculations
├── config/
│  └── strategy_config.py            # 76D parameter vector
└── core/
    └── data_structures.py            # Trading enums/types
```


---
= PART 12: EXIT RULES =


# Part 8: Strategy Configuration
== 3 Exit Conditions ==


## 8.1 76D Parameter Vector
{| class="wikitable"
|-
! Exit Type !! Condition
|-
| '''Stop Loss''' || Price hits stop (original or trailing)
|-
| '''Target''' || Price hits take profit level
|-
| '''Timeout''' || End of day (no overnight holds)
|}


The strategy uses **regime-aware configuration** with 76 parameters:
= PART 13: PUTTING IT ALL TOGETHER =
- **44 Global Parameters** - Constant across all market regimes
- **32 Regime Parameters** - 8 parameters x 4 market regimes


**File**: `src/config/strategy_config.py`
== Trade Flow ==


### Key Parameters
<pre>
┌─────────────────────────────────────────────────────────────────┐
│  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>


| Parameter | Default | Description |
----
|-----------|---------|-------------|
| `primary_ma_period` | 21 | Main trend MA |
| `secondary_ma_period` | 200 | Long-term trend MA |
| `default_stop_distance` | 40 pts | Minimum stop distance |
| `default_risk_reward` | 2.0 | Target R:R ratio |
| `ma_buffer_points` | 25 pts | MA zone width |
| `creeper_move_penalty` | -50 | Score reduction |
| `railroad_trend_bonus` | +15 | Score increase |


---
= PART 14: HARD vs SOFT FILTERS =


# Part 9: Decision Trees
== Understanding the Difference ==


## 9.1 Should I Trade This Setup?
{| class="wikitable"
|-
! 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 ==
START: Signal Generated
  │
  ▼
[Is hour blocked (9, 22, 23)?]
  │ Yes → SKIP (loss-making hours)
  │ No ↓
  ▼
[Is MA21 direction aligned with trade?]
  │ LONG + MA rising? → Continue
  │ SHORT + MA falling? → Continue
  │ No alignment → SKIP
  │
  ▼
[Is price in probability zone?]
  │ LONG + Bottom Third? → Continue (80% odds)
  │ SHORT + Top Third? → Continue (80% odds)
  │ Wrong zone → SKIP
  │
  ▼
[Calculate Setup Quality Score]
  │
  ├─ Apply 5-factor scoring (TF 30%, Trend 20%, Entry 15%, KeyLevel 20%, R:R 15%)
  ├─ Apply penalties (creeper -50, MA struggle -30, etc.)
  ├─ Apply institutional fight multiplier (0.7x)
  │
  ▼
[Assign Grade (A+ to F)]
  │
  ├─ A+ or A → Auto-trade eligible (2 lots for A+, 1 lot for A)
  ├─ B to D → Manual review (1 lot)
  ├─ F → Skip or minimal size
  │
  ▼
[Execute Trade with Position Size]
```


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


## 9.2 Where to Place Stop?
----


```
= APPENDIX A: CONFIGURATION VALUES =
START: Trade Direction Determined
  │
  ▼
[Is Fab Four zone tight and close?]
  │ Yes → Place stop BEYOND Fab Four zone
  │ No ↓
  ▼
[Can I afford stop beyond Fab Four?]
  │ Yes → Use EVENT stop (beyond Fab Four)
  │ No → Use MAXIMUM loss stop ($6000 max)
  │
  ▼
[Once trade moves in favor:]
  │
  ├─ Move stop to recent swing high/low
  ├─ Then move to break-even after first profit
  │
  ▼
[Stop Placement Complete]
```


---
== MTF Configuration ==


# Part 10: Code Review Guidelines
{| class="wikitable"
|-
! 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
|}


## 10.1 What Reviewers Should Check
== Entry Configuration ==


- [ ] Code correctness (syntax, bugs)
{| class="wikitable"
- [ ] Integration (doesn't break other components)
|-
- [ ] Test coverage
! Parameter !! Value !! Source File
- [ ] Precision (6-decimal places per spec)
|-
- [ ] Performance (no excessive logging)
| 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
|}


## 10.2 What Reviewers Should NOT Question
== Stop/Target Configuration ==


- The penalty values themselves (-50, -30, etc.)
{| class="wikitable"
- Why 21 MA and not 20 MA
|-
- Why specific thresholds (these are trading decisions)
! Parameter !! Value !! Source File
- Why certain hours are blocked
|-
| 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
|}


## 10.3 Trading Authority Principle
== Dynamic Stop Configuration ==


**Rikk has final authority on:**
{| class="wikitable"
- Entry/exit conditions
|-
- Threshold values
! Parameter !! Value !! Source File
- Setup definitions
|-
- What constitutes a valid signal
| enable_trailing_stop || True || trade_execution_engine.py:58
- Penalty/bonus amounts
|-
| 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
|}


**Engineers have authority on:**
== Slippage Configuration ==
- Code quality and structure
- Performance optimization
- Error handling
- System integration
- Test coverage


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


# Part 11: Quick Reference Cards
== Trade Execution Limits ==


## Card 1: Probability Zones
{| class="wikitable"
|-
! 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 ==
TOP THIRD    = 80% continuation (SHORT zone)
TOP HALF    = 65% continuation
BOTTOM HALF  = 35% continuation
BOTTOM THIRD = 15% continuation (LONG zone with 85% reversal odds)
```


## Card 2: Setup Quality Formula
{| class="wikitable"
|-
! 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 ==
Score = (TF_align * 0.30) + (Trend * 0.20) + (Entry * 0.15) + (KeyLevel * 0.20) + (R:R * 0.15)


Then apply:
{| class="wikitable"
- Creeper detected? → Score - 50
|-
- MA struggle? → Score - 30
! Parameter !! Value !! Source File
- No two-day trend? → Score - 30
|-
- Wrong phase? → Score - 25
| timeframe_alignment_weight || 30% || setup_quality_detection.py:44
- Institutional fight? → Score * 0.7
|-
```
| 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
|}


## Card 3: Profit Taking
== Probability Zone Configuration ==


```
{| class="wikitable"
1. Enter with 2 lots
|-
2. Set stop above high (short) / below low (long)
! Parameter !! Value !! Source File
3. Wait for follow-through bar (2nd bar after opposite color)
|-
4. Take profit on 1 lot
| enable_probability_zone_filter || True || signal_generation_trade_management.py:104
5. Move stop to break-even
|-
6. Wait for next follow-through bar
| probability_zone_swing_lookback || 20 bars || signal_generation_trade_management.py:105
7. Take profit on remaining lot
|-
8. Done
| 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


---
|}


*Last Updated: 2026-01-05 | Branch: rikk_mtf_backtest001 | Validated: 19-month backtest*
----

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