Jump to content

Alpha Research: Difference between revisions

From PlusEV Wiki Page
No edit summary
No edit summary
 
(100 intermediate revisions by 6 users not shown)
Line 1: Line 1:
= Alpha Research: MCX Crude Oil MA21 Strategy =
= Multi_Timeframe Dynamic Trend (MTFDR) =
----
 
= PART 1: STRATEGY OVERVIEW =
 
== What Is This Strategy? ==
 
'''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) ==


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


----
= PART 2: Core Concept (Why This Works) =


== Quick Reference: Backtest Proof ==
The edge comes from '''requiring multiple independent confirmations''' before trading. Each layer filters out bad trades:


{| class="wikitable"
{| class="wikitable"
! Metric !! Value !! Notes
|-
|-
| '''Total P&L''' || Rs +25,48,101 || 19-month validation period
! Layer !! What It Filters Out
|-
|-
| '''Win Rate''' || 57.6% || Above 55% threshold
| 1. MTF Analysis || Counter-trend trades, choppy markets
|-
|-
| '''Profit Factor''' || 1.20 || Risk-adjusted returns
| 2. Market State || Dangerous conditions (creeper moves, institutional fights)
|-
|-
| '''Total Trades''' || 7,534 || Statistical significance
| 3. Quality Grading || Scores the setup (used by hard filter)
|-
|-
| '''Initial Capital''' || Rs 1,00,000 || Starting portfolio
| 4. Hard Filters || Wrong direction, low grades (C/D/F), blocked hours
|-
|-
| '''Final Capital''' || Rs 26,48,101 || 2548% return
| 5. Entry Technique || Chasing price far from value areas
|}
|}


'''Branch''': <code>rikk_mtf_backtest001</code> | '''Commit''': <code>68dae212</code>
== The Math ==
 
{{quote|In trading systems, empirical results > theoretical understanding. If the backtest shows it works, we ship it.}}
 
----
 
= Part 1: Core Trading Philosophy =
 
== 1.1 Foundational Principles ==
 
<pre>
Simple systems outperform complex ones.
Market behavior is probabilistic, not predictive.
The goal is positioning with asymmetric probabilities, not prediction.
</pre>


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


When odds are low on one outcome, '''the opposite side usually carries high odds''':
'''Result:''' Fewer trades, but each trade has multiple confluences supporting it.
* If new high probability drops to 15%, then '''85% odds favor reversal'''
* We position ourselves on the high-probability side


----
----


== 1.2 Probability Zones (Halves & Thirds) ==
= PART 3: LAYER 1 - MULTI-TIMEFRAME ANALYSIS (The Foundation) =


Every large move is divided into '''halves and thirds''', creating probability zones.
<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>


=== Odds of Continuation After Pullback ===
== The 5 Timeframes ==
 
<pre>
┌─────────────────────────────────────────────────────┐
│  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                                          │
└─────────────────────────────────────────────────────┘
</pre>
 
=== Code Implementation ===
<syntaxhighlight lang="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
</syntaxhighlight>
 
----
 
== 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 ===
 
<pre>
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
</pre>
 
=== Key Statistics ===
* 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 ===
<syntaxhighlight lang="python">
# File: signal_generation_trade_management.py:108
crash_bar_multiplier: float = 2.0  # Bar must be 2x average for crash detection
</syntaxhighlight>
 
----
 
== 1.4 Pullback vs Collapse (Critical Distinction) ==
 
=== Healthy Pullback (Tradeable) ===


{| class="wikitable"
{| class="wikitable"
! Characteristic !! Description
|-
|-
| Angle || 45-degree drifting decline, NOT vertical
! Timeframe !! Role !! Weight
|-
| '''Daily (1D)''' || Overall market bias || Highest
|-
|-
| Bars || No violent or oversized red bars
| '''4-Hour (4H)''' || Primary trend direction || High
|-
|-
| Depth || Holds '''above halfway point''' of prior run
| '''1-Hour (1H)''' || Trend confirmation || Medium
|-
|-
| Confirmation || Color change (green overtakes red)
| '''15-Minute (15M)''' || Entry timing context || Lower
|-
| '''5-Minute (5M)''' || Execution timeframe || Lowest
|}
|}


'''Interpretation''': Pullbacks are rests, not reversals. Odds favor continuation.
== What We Analyze Per Timeframe ==


=== Collapse (NOT Tradeable) ===
For each of 5 timeframes, our system calculates:


{| class="wikitable"
{| class="wikitable"
! Characteristic !! Description
|-
|-
| Angle || Vertical, elongated, violent first drop
! Analysis !! Description
|-
| '''MA21 Value''' || 21-period Moving Average
|-
| '''MA21 Slope''' || Rising/Flat/Declining
|-
| '''MA200 Value''' || 200-period Moving Average
|-
|-
| Depth || Breaks deeply into or below prior run
| '''Price vs MA21''' || Above/Below/At the MA
|-
|-
| Momentum || Abrupt and forceful
| '''Trend Direction''' || UP/DOWN/NEUTRAL
|}
|}


'''Interpretation''': Indicates institutional selling. Bounces are sucker plays.
== MTF Alignment Score ==
 
----
 
== 1.5 Identifying Market Tops (4 Characteristics) ==


Major tops usually exhibit '''at least 2 of these 4 characteristics''':
=== 1. Three-to-Five Leg Run-Up ===
<pre>
<pre>
Markets top between leg 3 and leg 5.
For each timeframe:
- Buy: legs 1-2
  1. Determine trend direction (UP/DOWN/NEUTRAL)
- Ride: leg 3
  2. Check if aligned with trade direction
- Take profits: legs 4-5
  3. Apply timeframe weight
- Buying late (leg 4-5) = large downside vs small upside
  4. Sum weighted alignment scores
</pre>


=== 2. Vertical Acceleration in Final Leg ===
Example (LONG trade):
<pre>
  Daily:  UP (aligned)    × 1.00 weight = 1.00
If the last leg is STEEPER than prior legs → likely final leg
  4H:    UP (aligned)    × 0.86 weight = 0.86
The most vertical leg is usually the top.
  1H:    UP (aligned)    × 0.72 weight = 0.72
  15M:    DOWN (not aligned) × 0.58 weight = 0.00
  5M:    UP (aligned)    × 0.44 weight = 0.44
  ─────────────────────────────────────────────
  Total MTF Score: 3.02 / 3.60 = 83.9% aligned
</pre>
</pre>


=== 3. Exhaustion Bar ===
== Why MTF Matters ==
<pre>
Final bar of final leg is:
- Larger than recent bars
- Often the largest bar of entire run
= Bulls deploy all remaining buying power
= Market becomes top-heavy and vulnerable
</pre>


=== 4. Three-Finger Spread (Dual Space) ===
{| class="wikitable"
<pre>
|-
Large separation between:
! Scenario !! MTF Alignment !! Action
- Price
|-
- 21-period MA
| All 5 timeframes aligned || ~90% || '''High conviction trade A+ 2lots'''
- 200-period MA
|-
 
| 4 of 5 aligned || ~80% || Trade with normal size A 1 lot
= Many traders holding large unrealized profits
|-
= Any red bar can trigger mass profit-taking
| 3 of 5 aligned || ~70% || Proceed with caution B 1 lot
= Creates fast, violent declines
|-
</pre>
| 2 or fewer aligned || <60% || '''No Trade'''
 
|}
=== Code Implementation ===
<syntaxhighlight lang="python">
# File: signal_generation_trade_management.py:107
three_finger_spread_threshold: float = 0.02  # 2% min spread for detection
</syntaxhighlight>


----
----


= Part 2: Entry Methodology =
= PART 4: LAYER 2 - MARKET STATE ANALYSIS =


== 2.1 The Fab Four Concept ==
== The 7 Market State Algorithms ==


The '''Fab Four''' defines the key reference points for entries and stops:
Our system runs 7 independent algorithms to understand current market context:


<pre>
{| class="wikitable"
┌─────────────────────────────────────────────────────┐
|-
│  FAB FOUR ELEMENTS                                  │
! # !! Algorithm !! What It Detects !! Impact
├─────────────────────────────────────────────────────┤
|-
│  1. Previous Day High/Low (PDHL)                   │
| 1 || '''Railroad Tracks''' || Strong momentum bars in sequence || +15% bonus
│  2. 21-Period Moving Average                        │
|-
│  3. 200-Period Moving Average                      │
| 2 || '''Creeper Move''' || Slow grinding trend (dangerous) || '''-50% penalty'''
│  4. Yesterday's Close                              │
|-
└─────────────────────────────────────────────────────┘
| 3 || '''Two-Day Trend''' || Trend visible on Daily for 2+ days || Required for A+
</pre>
|-
 
| 4 || '''Phase Analysis''' || Accumulation/Distribution/Markup/Markdown || Phase mismatch = -25%
=== MA is a ZONE, Not a Line ===
|-
 
| 5 || '''Institutional Activity''' || Big player accumulation/distribution || Fight = 0.7× multiplier
{{quote|The MA is a zone, not a thin line. Don't be exact with this.}}
|-
 
| 6 || '''Break of Structure (BOS)''' || Key level breaks || Affects stop placement
<syntaxhighlight lang="python">
|-
# File: signal_generation_trade_management.py:68
| 7 || '''Volatility Regime''' || High/Normal/Low volatility || Adjusts expectations
ma_buffer_points: float = 25.0  # 21 MA zone width (not a thin line)
|}
</syntaxhighlight>
 
=== Fab Four Tightness = Explosive Potential ===
 
When the Fab Four elements are '''tight together''':
* Indicates compressed energy
* Expect '''powerful move''' (up or down)
* Best trades come from '''narrowness'''
 
----
 
== 2.2 Entry Position Hierarchy ==


=== Best Entry Positions ===
== Penalty System ==
 
<pre>
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)                        │
└─────────────────────────────────────────────────────┘
</pre>
 
=== Multi-Timeframe Alignment ===
 
Check all timeframes simultaneously:
 
<pre>
┌────────┬────────┬────────┬────────┐
│  2min  │  5min  │  15min │  Daily │
│  ────  │  ────  │  ────  │  ────  │
│ Under  │ Under  │ Under  │ Under  │
│  200  │  200  │  200  │  200  │
│ Tight  │ Tight  │ Tight  │ Tight  │
└────────┴────────┴────────┴────────┘
        = ALIGNED = HIGH QUALITY SETUP
</pre>
 
=== Code Implementation ===
<syntaxhighlight lang="python">
# File: setup_quality_detection.py:43-48
timeframe_alignment_weight: float = 0.30  # 30% of setup quality score
</syntaxhighlight>
 
----
 
== 2.3 Bar-by-Bar vs Big Bar Stops ==
 
=== The Rule ===


{| class="wikitable"
{| class="wikitable"
! When to Use !! Stop Method !! Why
|-
|-
| '''Near MA''' (hugging) || Big Bar stops || Eliminates noise
! Condition !! Penalty !! Rationale
|-
| Creeper Move Detected || '''-50 points''' || Slow trends often reverse suddenly
|-
|-
| '''Far from MA''' (extended) || Bar-by-bar stops || Protect extended gains
| 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
|}
|}


=== The Warning ===
== Bonus System ==
 
{{quote|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.}}
 
'''Use bar-by-bar ONLY when:'''
* Price has moved significantly away from MA
* "You had better be moving to Pluto"
* Slant on both 2min and 5min is sharp
 
----
 
= Part 3: Stop Loss Methodology =
 
== 3.1 Stop Placement Hierarchy ==
 
=== Two Stop Options ===


{| class="wikitable"
{| class="wikitable"
! Type !! Description !! When to Use
|-
|-
| '''Event Stop''' || Based on price action event || Primary choice
! Condition !! Bonus !! Rationale
|-
|-
| '''Maximum Stop''' || Dollar-based max loss || Fallback when event too far
| Railroad Tracks || '''+15 points''' || Strong momentum confirmation
|-
| At Key Level || +10 points || Technical confluence present
|-
| Clean Entry Setup || +10 points || Clear technical pattern
|}
|}


=== The Goal ===
== Probability Zone Analysis ==
 
=== The Asymmetric Probability Edge ===


When odds are low on one outcome, '''the opposite side usually carries high odds''':
* If new high probability drops to 15%, then '''85% odds favor reversal'''
* We position ourselves on high-probability side where price position within recent range determines continuation probability:
* Every large move is divided into '''halves and thirds''', creating probability zones.
=== Odds of Continuation After Pullback ===
<pre>
<pre>
┌─────────────────────────────────────────────────────┐
┌─────────────────────────────────────────────────────┐
│  FAB FOUR ZONE (Helping Zone)                     
│  SWING HIGH                                       
├─────────────────────────────────────────────────────┤
├─────────────────────────────────────────────────────┤
│  ↑ STOP SHOULD BE HERE (above/below Fab Four)     
│  TOP THIRD        →  ~80% chance of new high       
├─────────────────────────────────────────────────────┤
├─────────────────────────────────────────────────────┤
│  Entry price                                       
│  TOP HALF        →  ~66% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM HALF      →  ~33% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM THIRD    →  ~15% chance of new high        │ 
├─────────────────────────────────────────────────────┤
│  SWING LOW                                         
└─────────────────────────────────────────────────────┘
└─────────────────────────────────────────────────────┘
</pre>
</pre>
{{quote|The real goal is to get your stop beyond the Fab Four helping zone.}}
=== Code Implementation ===
<syntaxhighlight lang="python">
# 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
</syntaxhighlight>
----
== 3.2 Stop and Reverse Rules ==
Three criteria for a valid '''Stop and Reverse''':


{| class="wikitable"
{| class="wikitable"
! Criteria !! Description
|-
|-
| '''1. Immediate''' || Stop out happens INSTANTLY, not gradually
! Zone !! Position !! Continuation Probability !! Action
|-
|-
| '''2. Violent''' || Move that stops you is hard, powerful, shakes earth
| '''Top Third''' || >66.6% of range || '''80%''' likely to continue higher || Favor LONG
|-
|-
| '''3. Decent Position''' || New position is NOT into resistance/support
| '''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
|}
|}


=== Invalid Stop and Reverse ===
=== 3-Finger Spread ===
 
<pre>
❌ 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
</pre>
 
=== Code Implementation ===
<syntaxhighlight lang="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
</syntaxhighlight>
 
----
 
= Part 4: Color Change Confirmation =


== 4.1 The Color Change Entry ==
Measures separation between Price, 21 MA, and 200 MA:


=== Entry Trigger ===
<pre>
<pre>
FOR SHORTS:
Three-Finger Spread Detection:
Red bar closes BELOW green bar's low → ENTER SHORT
  - Large spread between Price/21MA/200MA
Stop: Above the high
  - Indicates profit-taking pressure imminent
  - Minimum spread threshold: 2% of price


FOR LONGS:
Structure Types:
Green bar closes ABOVE red bar's high → ENTER LONG
  UPTREND:    Price > 21 MA > 200 MA (bullish stack)
Stop: Below the low
  DOWNTREND:  Price < 21 MA < 200 MA (bearish stack)
  SIDEWAYS:   No clear MA separation
</pre>
</pre>


=== Key Rule: Don't Wait for Bar to Complete ===
=== Crash Bar Detection ===


{{quote|As soon as the red bar crosses below the green, boom boom boom boom boom. You're in.}}
Identifies structural breaks via unusually large bars:


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


== 4.2 Profit Taking Rules ==
=== Pullback Classification ===


=== The Two-Bar Rule ===
{| class="wikitable"
 
|-
{{quote|Take profits TWO bars after the opposite color, NOT one bar.}}
! Type !! Characteristics !! Action
 
|-
<pre>
| '''Healthy Pullback''' || 45° drift, holds above halfway point || Good entry opportunity
SHORT TRADE:
|-
┌─────────────────────────────────────────────────────┐
| '''Collapse''' || Vertical drop (>60% retracement) || Avoid entry, wait for structure
│  GREEN bar (opposite color)                         │
|-
├─────────────────────────────────────────────────────┤
| '''Bounce''' || Recovery after crash bar || Short opportunity
│  RED bar 1 ← IGNITING bar (DO NOT take profit)      │
|}
├─────────────────────────────────────────────────────┤
│  RED bar 2 ← FOLLOW-THROUGH bar (TAKE PROFIT)      │
└─────────────────────────────────────────────────────┘
</pre>
 
=== Position Management Flow ===
 
<pre>
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
</pre>


{{quote|The first lot is your REAL trade. The second lot is the cherry on top.}}
=== Signal Filtering ===


=== Code Implementation ===
Probability zones filter signals:
<syntaxhighlight lang="python">
# File: signal_generation_trade_management.py:111-118
enable_color_change_filter: bool = False    # DISABLED - too restrictive
color_change_ma_proximity: float = 20.0      # Points to consider "near" MA
require_ma_bounce: bool = False              # Don't require strict MA bounce
</syntaxhighlight>


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


== 4.3 The Traffic Jam Concept ==
if zone_position < 33.3%:  # Bottom third
    # Block LONG signals (only 15% chance of continuation)
    # Allow SHORT signals


When price gaps below '''everything from prior day''':
if zone_position > 66.7%: # Top third
    # Allow LONG signals (80% continuation)
    # Block SHORT signals


<pre>
= PART 5: LAYER 3 - SETUP QUALITY GRADING =
┌─────────────────────────────────────────────────────┐
│  Yesterday's 200 MA                                │
│  Yesterday's 20 MA                                  │
│  Yesterday's Close                                  │
│  ═══════════════════════════════════════════        │
│  TRAFFIC JAM ZONE (resistance on any rally)        │
│  ═══════════════════════════════════════════        │
│                                                    │
│  TODAY'S GAP DOWN OPEN                              │
└─────────────────────────────────────────────────────┘
</pre>


'''Rule''': Any move UP into the traffic jam meets resistance. Short rallies into this zone.
== The 5-Factor Scoring System ==


----
Every potential trade is scored on 5 factors:
 
= Part 5: Trading Glossary for Engineers =


{| class="wikitable"
{| class="wikitable"
! Trading Term !! System Translation !! Code Location !! Why It Matters
|-
|-
| '''Creeper Move''' || Small-bodied bars, consistent direction, low volume || <code>market_state_analysis.py:is_creeper_move</code> || Institutional accumulation before explosion. '''PENALTY: -50 points'''
! Factor !! Weight !! What It Measures
|-
|-
| '''Railroad Trend''' || Alternating green/red bars touching MA || <code>market_state_analysis.py:is_railroad_trend</code> || Healthy trend, not overextended. '''BONUS: +15 points'''
| '''Timeframe Alignment''' || '''30%''' || How well all 5 timeframes agree
|-
|-
| '''Two-Day Trend''' || Price consistently above/below MA for 2+ days || <code>market_state_analysis.py:has_two_day_trend</code> || Confirms trend maturity. '''Required for A+ grade'''
| '''Trend Strength''' || '''20%''' || Quality of the trend (Railroad vs Creeper)
|-
|-
| '''Institutional Fight''' || High volume with narrow range || <code>market_state_analysis.py:institutional_fight_in_progress</code> || Buyers vs sellers battle. '''MULTIPLIER: 0.7x score'''
| '''Key Level Proximity''' || '''20%''' || Is entry near significant S/R level?
|-
|-
| '''Discount Zone''' || Price below 21 MA (for longs) || <code>probability_zone_analysis.py</code> || 80% continuation probability
| '''Entry Quality''' || '''15%''' || How clean is the entry technique?
|-
|-
| '''Premium Zone''' || Price above 21 MA (for shorts) || <code>probability_zone_analysis.py</code> || Entry zone for short trades
| '''Risk:Reward''' || '''15%''' || Is the R:R ratio favorable?
|}
 
<div style="background:#e6f3ff; border:1px solid #3399ff; padding:10px; margin:10px 0;">
'''Note:''' Weights sum to 100%. Timeframe Alignment has highest weight (30%) because MTF is the foundation.
</div>
 
== Grade Thresholds ==
 
{| class="wikitable"
|-
|-
| '''Fab Four''' || PDHL, 21 MA, 200 MA, Yesterday's Close || <code>signal_generation.py:_calculate_stop_loss()</code> || Stop loss placement hierarchy
! Grade !! Score Range !! Action !! Position Size
|-
|-
| '''Color Change''' || Bar closes opposite color after move || <code>probability_zone_analysis.py:ColorChangeDetector</code> || Confirms reversal/continuation
| '''A+''' || 90-100 || Trade with full conviction || 2 lots
|-
|-
| '''Break of Structure (BOS)''' || Price closes beyond recent swing H/L || <code>market_state_analysis.py:bos_detected</code> || Confirms trend continuation/reversal
| '''A''' || 80-89 || Trade with confidence || 1 lot
|-
|-
| '''MA Zone''' || MA is a band, not thin line (21 MA +/- 25pts) || <code>signal_generation.py:ma_buffer_points=25</code> || "Fab Four" concept from philosophy
| '''B''' || 70-79 || Trade normally || 1 lot
|-
|-
| '''Trend Phase''' || EARLY / MIDDLE / LATE classification || <code>market_state_analysis.py:trend_phase</code> || MIDDLE phase = optimal entry timing
| '''C''' || 60-69 || '''NO TRADE''' || -
|-
|-
| '''Crash Bar''' || Bar > 2x average size, violent || <code>probability_zone_analysis.py:crash_bar_multiplier</code> || Structural break indicator
| '''D''' || 50-59 || '''NO TRADE''' || -
|-
|-
| '''Traffic Jam''' || Yesterday's price activity zone || Conceptual || Resistance zone for gaps
| '''F''' || <50 || '''NO TRADE''' || -
|-
| '''Three-Finger Spread''' || Large gap between Price, 21 MA, 200 MA || <code>signal_generation.py:three_finger_spread_threshold</code> || Market top indicator
|}
|}


----
== A+ Grade Special Requirements ==


= Part 6: Component Architecture =
To achieve A+ grade, ALL conditions must be true:
* Final score ≥ 90
* All 5 timeframes aligned with trade direction
* Entry within ±25 points of MA21
* Two-day trend present on Daily
* No institutional fight detected


== 6.1 Pipeline Flow ==
== Score Calculation Example ==


<pre>
<pre>
┌─────────────────┐   ┌───────────────────┐  ┌────────────────────┐
Trade Setup: LONG on 5-min chart
│  Data Manager   │ → │  Trend Analysis  │ → │ Market State      │
 
│  (1M/5M/1H/1D)  │   (MA21, MA200)    │   (7 Detections)    │
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
│  Trade Exec    │ ← │  Signal Gen      │ ← │  Setup Quality    │
   Entry Quality:      80 × 0.15 = 12.0
│  (P&L, Costs)     │  (Entry/Exit)    │   │  (5-Factor Score)  │
   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
</pre>
</pre>


----
----


== 6.2 Setup Quality Detection ==
= PART 6: HARD LAYER 4 - FILTERS=


'''File''': <code>src/components/setup_quality_detection.py</code>
<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>


=== 5-Factor Weighted Scoring System ===
== 3 Hard Filters ==


{| class="wikitable"
{| class="wikitable"
! Factor !! Weight !! What It Measures
|-
|-
| Timeframe Alignment || '''30%''' || All timeframes agree on direction
! Filter !! Rule !! Effect
|-
|-
| Trend Strength || '''20%''' || Healthy trend without warnings
| '''1. Direction Filter''' || MA21 slope must match trade direction || Wrong direction = BLOCKED
|-
|-
| Entry Quality || '''15%''' || Entry near MA, clean execution
| '''2. Grade Filter''' || Only A+, A, B grades allowed || C/D/F grades = BLOCKED
|-
|-
| Key Level Proximity || '''20%''' || Entry near support/resistance
| '''3. Hour Filter''' || Block hours [WIP] || Blocked hours = BLOCKED
|-
| Risk/Reward || '''15%''' || Favorable profit potential
|}
|}


=== Penalty System ===
== Filter 1: Direction (MA21 Slope) ==


{| class="wikitable"
{| class="wikitable"
! Condition !! Penalty !! Trading Reason
|-
| 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
! MA21 Slope !! Allowed Direction !! Logic
|-
|-
| Wrong Trend Phase || -25 pts || Too early or too late in trend
| '''Rising''' (↗) || LONG only || Trade with uptrend, never short
|-
|-
| Not Near MA || -40 pts || Entry too far from edge
| '''Declining''' (↘) || SHORT only || Trade with downtrend, never long
|-
|-
| Institutional Fight || 0.7x || Wait for resolution
| '''Flat''' (→) || Use MTF direction || Higher timeframes decide
|}
|}


=== Grade Thresholds ===
== Filter 2: Grade ==


{| class="wikitable"
{| class="wikitable"
! Grade !! Score !! Position Size !! Auto-Trade?
|-
| A+ || >= 90 || 2 lots || Yes
|-
| A || >= 80 || 1 lot || Yes
|-
|-
| B || >= 70 || 1 lot || No
! Grade !! Action
|-
|-
| C || >= 60 || 1 lot || No
| A+, A, B || '''PASS''' - Proceed to entry
|-
|-
| D || >= 50 || 1 lot || No
| C, D, F || '''BLOCKED''' - No trade
|-
| F || < 50 || 1 lot || No
|}
|}


----
== Filter 3: Hour [work in progress examples] ==
 
== 6.3 Market State Analysis ==
 
'''File''': <code>src/components/market_state_analysis.py</code>
 
=== 7 Detection Algorithms ===


{| class="wikitable"
{| class="wikitable"
! # !! Algorithm !! What It Detects !! Trading Implication
|-
| 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
! Hour !! Status !! Reason
|-
|-
| 4 || Market State || TRENDING / SIDEWAYS / VOLATILE || Different strategy rules
| 9 (9:00-9:59 AM) || '''BLOCKED''' || Market open volatility
|-
|-
| 5 || Two-Day Trend || Multi-day momentum || Required for A+ grade
| 10-21 (10:00 AM - 9:59 PM) || '''ALLOWED''' || Normal trading hours
|-
|-
| 6 || Trend Phase || EARLY / MIDDLE / LATE || MIDDLE = optimal entry
| 22 (10:00-10:59 PM) || '''BLOCKED''' || Near market close
|-
|-
| 7 || Institutional Behavior || Volume + price patterns || Fight = wait, Accumulation = prepare
| 23 (11:00-11:59 PM) || '''BLOCKED''' || Market close
|}
|}


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


== 6.4 Signal Generation ==
== MA21 Zone Principle ==


'''File''': <code>src/components/signal_generation_trade_management.py</code>
<blockquote>
'''"The MA is a ZONE, not a thin line or exact value"'''


=== Entry Filters Applied ===
Entry is allowed within '''±25 points''' of MA21, not just at the exact MA value.
</blockquote>


{| class="wikitable"
== Why ±25 Points? ==
! Filter !! Config Key !! Purpose
|-
| Hour Filter || <code>blocked_hours: [9, 22, 23]</code> || Block loss-making hours
|-
| MA Direction || <code>enable_ma_direction_filter: True</code> || LONG only if MA rising
|-
| Probability Zone || <code>enable_probability_zone_filter: True</code> || Entry in favorable zones
|-
| Color Change || <code>enable_color_change_filter: False</code> || Disabled (too restrictive)
|}
 
----


= Part 7: Branch Changes (service/backtest → rikk_mtf_backtest001) =
* Price rarely touches MA exactly
* Allows for normal market noise


== 7.1 Complete Git Diff Summary ==
== Entry Techniques ==


'''Total Changes''': 65 files changed across core source, scripts, and data
=== Modified (M) Source Files ===
{| class="wikitable"
{| class="wikitable"
! File !! Type !! Key Changes
|-
|-
| <code>signal_generation_trade_management.py</code> || Component || TICKET-7,8,10,11,12,13,18,19,20,21,24 + PDF fixes + Grading fix
! Technique !! Direction !! Description
|-
|-
| <code>trade_execution_engine.py</code> || Component || TICKET-9,13,15,17,20: Trailing stop, breakeven, ATR
| '''NEAR_MA''' || Both || Price within ±25 pts of MA21 (most common)
|-
|-
| <code>market_state_analysis.py</code> || Component || TICKET-25: 5MIN → 1HOUR data
| MA_BOUNCE_LONG || Long || Price touches MA21 and bounces up
|-
|-
| <code>setup_quality_detection.py</code> || Component || TICKET-5: Position sizing fix
| MA_BOUNCE_SHORT || Short || Price touches MA21 and rejects down
|-
|-
| <code>timeframe_conversion.py</code> || Core || Date column fix, 1m skip, emoji removal
| GREEN_BAR_AFTER_PULLBACK || Long || Bullish candle after pullback to MA
|-
|-
| <code>data_structures.py</code> || Core || TICKET-15: <code>current_stop_price</code> field
| RED_BAR_AFTER_RALLY || Short || Bearish candle after rally to MA
|-
|-
| <code>multi_timeframe_analysis.py</code> || Component || Whitespace cleanup
| BOS_ENTRY_LONG || Long || Break of structure to upside
|-
|-
| <code>main.py</code> || Entry || TICKET-12 config, emoji removal
| BOS_ENTRY_SHORT || Short || Break of structure to downside
|}
|}


=== Added (A) Files ===
= PART 8: STOP LOSS CALCULATION =
 
== Stop Loss Methods (Priority Order) ==
 
{| class="wikitable"
{| class="wikitable"
! File !! Purpose
|-
|-
| <code>probability_zone_analysis.py</code> || '''NEW''': Implements trade_philosophy.pdf (974 lines)
! Priority !! Method !! Description
|-
|-
| <code>50+ scripts/analyze_*.py</code> || Analysis scripts for hypothesis building
| 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 ==


== 7.2 JIRA Ticket Fixes (Complete Details) ==
<div style="background:#ffffcc; border:1px solid #ffcc00; padding:10px; margin:10px 0;">
'''MINIMUM: 40 points'''
</div>


=== TICKET-5: Position Sizing Fix ===
This prevents:
'''File''': <code>setup_quality_detection.py:544-567</code>
* 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


'''Problem''': Previous sizing = 100-200 lots = Rs 5.7 Crore exposure on Rs 1 lakh capital (5700x!)
= PART 9: TARGET CALCULATION =


<syntaxhighlight lang="python">
== The 50% Rule ==
# BEFORE (service/backtest):
multipliers = {
    SetupQualityGrade.A_PLUS: 200,  # 200 lots (impossible!)
    SetupQualityGrade.A: 150,
    SetupQualityGrade.B: 100,
    # ...
}


# AFTER (rikk_mtf_backtest001):
<div style="background:#e6f3ff; border:1px solid #3399ff; padding:10px; margin:10px 0;">
position_sizes = {
'''Target = 50% of distance to MA21'''
    SetupQualityGrade.A_PLUS: 2,    # 2 lots (Rs 1.14L exposure - realistic)
    SetupQualityGrade.A: 1,        # 1 lot
    SetupQualityGrade.B: 1,
    SetupQualityGrade.C: 1,
    SetupQualityGrade.D: 1,
    SetupQualityGrade.F: 1
}
</syntaxhighlight>


----
For mean reversion trades, we target halfway back to moving average.
</div>


=== TICKET-7: R:R Preservation After Slippage ===
== Why 50%? ==
'''File''': <code>signal_generation_trade_management.py:241-285</code>


'''Problem''': Slippage moved entry but stop/target stayed fixed = corrupted R:R ratio
* 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


<syntaxhighlight lang="python">
== Minimum Target Rule ==
# BEFORE: Stop and target not adjusted after slippage
actual_execution_price = execution_price + market_slippage  # Entry moved
# BUT stop_loss_price and take_profit_price stayed at original levels!
# RESULT: R:R became inverted (target closer than stop)


# AFTER: Shift stop and target with entry to maintain R:R
<pre>
# Example (LONG with +1.5 pts slippage):
Minimum Target = Risk × 1.5
#  Before: entry=5710, stop=5680, target=5740 (30 pts each, 1:1 R:R)
#  After slippage: entry=5711.5, stop=5680, target=5740
#  WRONG R:R: stop=31.5 pts, target=28.5 pts (INVERTED!)
#  FIX: entry=5711.5, stop=5681.5, target=5741.5 (30 pts each, 1:1 R:R)


if signal.direction == Direction.LONG:
Example:
    actual_execution_price = execution_price + market_slippage
  Entry: 5700
    # TICKET-7: Shift stop and target UP by slippage to maintain R:R
  Stop: 5660 (40 points risk)
    adjusted_stop_loss = signal.stop_loss_price + market_slippage
    adjusted_take_profit = signal.take_profit_price + market_slippage
else: # SHORT
    actual_execution_price = execution_price - market_slippage
    # TICKET-7: Shift stop and target DOWN by slippage to maintain R:R
    adjusted_stop_loss = signal.stop_loss_price - market_slippage
    adjusted_take_profit = signal.take_profit_price - market_slippage
</syntaxhighlight>


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


=== TICKET-8: CTT Rate Fix ===
  Final Target: 5760 (60 points)
'''File''': <code>signal_generation_trade_management.py:48-55</code>
</pre>


'''Problem''': CTT was 0.05% (5x too high!). Dhan broker calculates Rs 52 on Rs 5.2L = 0.01%
= PART 10: DYNAMIC STOP MANAGEMENT =


<syntaxhighlight lang="python">
== Two-Phase Protection ==
# BEFORE:
transaction_tax_rate: float = 0.000500  # 0.05% - WRONG!


# AFTER:
After entry, stops are managed dynamically in two phases:
# MCX CTT = 0.01% on SELL side only. Since code charges at entry+exit,
# use 0.005% per leg so round-trip = 0.01% total (matches actual CTT)
# Dhan verified: CTT Rs 52 on Rs 5,20,000 sell value = 0.01%
transaction_tax_rate: float = 0.000050  # 0.005% per leg × 2 = 0.01% total
</syntaxhighlight>


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


=== TICKET-9: Market Impact Slippage Cap ===
== Phase 1: Breakeven Stop ==
'''File''': <code>trade_execution_engine.py:40-42, 585-605</code>


'''Problem''': 100 lots × 0.1 = 10 pts slippage (excessive!)
<pre>
Configuration:
  breakeven_activation = 25 points
  breakeven_buffer = 2 points


<syntaxhighlight lang="python">
Example (LONG from 5700):
# BEFORE: No cap on market impact
  Price reaches 5725 (+25 pts profit)
size_impact = signal.position_size * self.config.market_impact_factor
  → Stop moves from 5660 to 5702 (entry + 2)
  → Trade is now "risk-free"
</pre>


# AFTER: Cap to prevent excessive slippage
== Phase 2: Trailing Stop ==
max_market_impact_slippage: float = 2.0  # Maximum 2 points


raw_size_impact = signal.position_size * self.config.market_impact_factor
<pre>
size_impact = min(raw_size_impact, self.config.max_market_impact_slippage)
Configuration:
  trailing_stop_activation = 20 points
  trailing_stop_method = ATR_MULTIPLE
  atr_period = 14 bars
  atr_multiplier = 2.0
  minimum_trail_distance = 15 points


# For 1-2 lots (after TICKET-5 fix):
Example (LONG from 5700, ATR = 12):
#   - base: 1.0 pts
   Trailing Distance = 12 × 2 = 24 points
#  - market_impact: min(1×0.1, 2.0) = 0.1 pts (capped at 2.0)
#  - volatility: 0.5 pts
#  - total: ~1.6 pts (realistic for MCX crude)
</syntaxhighlight>


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


=== TICKET-10: Entry Technique Alignment ===
  Price at 5760:
'''File''': <code>signal_generation_trade_management.py:2012-2140</code>
  → Trail stop = 5760 - 24 = 5736 (moved UP)


'''Problem''': Entry technique logic didn't match strategy_engine.py priority order
  Price drops to 5736:
  → STOPPED OUT at 5736 (profit locked)
</pre>


<syntaxhighlight lang="python">
== Why Both Phases? ==
# COMPLETE REWRITE of _determine_entry_technique():
# BEFORE: Random priority order, creeper before BOS, missing key level checks


# AFTER (aligned with strategy_engine.py::_classify_entry_technique_exact()):
{| class="wikitable"
# PRIORITY 1: Creeper move → NEAR_MA (NOT green_bar/red_bar!)
|-
# PRIORITY 2: BOS detected → BOS_ENTRY (only if NOT creeper)
! Phase !! Purpose
# PRIORITY 3: Near key level → DISCOUNT_ZONE / BREAKOUT_PULLBACK
|-
# PRIORITY 4: Near MA → MA_BOUNCE
| Breakeven || Eliminate risk quickly once trade moves in favor
# PRIORITY 5: Two-day trend → TWO_GREEN_DAILY / TWO_RED_DAILY
|-
# PRIORITY 6: Railroad trend → GREEN_BAR_AFTER_PULLBACK / RED_BAR_AFTER_RALLY
| Trailing || Let winners run while protecting accumulated profit
# PRIORITY 7: Fallback → NEAR_MA
|}
</syntaxhighlight>


----
----


=== TICKET-11: BOS Stop Settings ===
= PART 11: SLIPPAGE & COSTS =
'''File''': <code>signal_generation_trade_management.py:78-81</code>


'''Problem''': 5-bar lookback + no buffer = stop too close in trending markets = 66.7% stop rate
== Slippage Model ==


<syntaxhighlight lang="python">
{| class="wikitable"
# BEFORE:
|-
structure_lookback: int = 5 # Too short for BOS
! 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
|}


# AFTER:
== Cost Structure ==
bos_structure_lookback: int = 10    # Extended lookback for BOS stops
bos_stop_buffer_points: float = 5.0  # Buffer below/above structure
</syntaxhighlight>


----
{| class="wikitable"
 
|-
=== TICKET-12: Hour Filter ===
! Cost Type !! Value
'''File''': <code>signal_generation_trade_management.py:83-93, 126-137, 571-581</code>
|-
 
| Commission || Rs 20 per lot per side
'''Problem''': Certain hours consistently lose money
|-
| STT || 0.01% on sell side
|-
| Exchange Fees || ~Rs 2 per lot
|-
| Stamp Duty || State-dependent
|}


<syntaxhighlight lang="python">
== Why Model Slippage? ==
# NEW CONFIGURATION:
enable_hour_filter: bool = True
blocked_hours: [9, 22, 23]  # Block 9-10 AM and after 10 PM


# Data-driven analysis showed (from 1439 trades):
* Backtest results must reflect real trading
# Worst hours: 15(-Rs244K), 22(-Rs209K), 09(-Rs199K), 21(-Rs101K), etc.
* Prevents over-optimistic performance estimates
# Profitable hours: 16, 17, 18, 19, 23 (total +Rs341K)
* 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
# Applied in generate_signal():
if self.config.enable_hour_filter and self.config.blocked_hours:
    current_hour = current_timestamp.hour
    if current_hour in self.config.blocked_hours:
        return None # No signal during blocked hours
</syntaxhighlight>


----
----


=== TICKET-13: Minimum Stop Distance ===
= PART 12: EXIT RULES =
'''File''': <code>signal_generation_trade_management.py:57-60, 852-870</code>


'''Problem''': 20pt stops hit too frequently due to normal price noise
== 3 Exit Conditions ==


<syntaxhighlight lang="python">
{| class="wikitable"
# BEFORE:
|-
default_stop_distance: float = 20.000000
! Exit Type !! Condition
 
|-
# AFTER:
| '''Stop Loss''' || Price hits stop (original or trailing)
min_stop_distance: float = 40.000000    # Minimum stop distance
|-
default_stop_distance: float = 40.000000  # Default increased
| '''Target''' || Price hits take profit level
 
|-
# ENFORCEMENT in generate_signal():
| '''Timeout''' || End of day (no overnight holds)
# TICKET-13 FIX: ENFORCE MINIMUM STOP DISTANCE (40 POINTS)
|}
stop_distance = max(calculated_stop_distance, self.config.min_stop_distance)
</syntaxhighlight>
 
----
 
=== TICKET-15: Trailing Stop Tracking ===
'''File''': <code>data_structures.py:2982-2984</code>, <code>trade_execution_engine.py:54-70, 295-392</code>
 
'''Problem''': No way to track current trailing stop position vs original
 
<syntaxhighlight lang="python">
# NEW FIELD in Trade dataclass:
current_stop_price: Optional[float] = None  # Current trailing stop (moves with price)
 
# NEW METHOD in TradeExecutionEngine:
def _update_trailing_stop(self, trade: Trade, current_high: float, current_low: float):
    """
    TICKET-15/17/20: Update stop based on price movement.
 
    Two-Phase Stop Management:
    PHASE 1 - Breakeven (TICKET-17): Move stop to entry when profitable
    PHASE 2 - Trailing (TICKET-15/20): Trail stop behind price
    """
    if trade.current_stop_price is None:
        trade.current_stop_price = trade.original_stop_price
 
    # Calculate trailing distance (ATR-based or fixed)
    if self.config.trailing_stop_method == "ATR_MULTIPLE":
        trailing_distance = self.current_atr * self.config.atr_multiplier
        trailing_distance = max(trailing_distance, 15.0) # Min 15 pts for Crude
    else:
        trailing_distance = self.config.trailing_stop_distance
 
    if trade.direction == Direction.LONG:
        current_profit = current_high - trade.entry_price
        if current_profit >= self.config.trailing_stop_activation:
            new_stop = current_high - trailing_distance
            if new_stop > trade.current_stop_price:
                trade.current_stop_price = new_stop  # Only move UP
</syntaxhighlight>
 
----
 
=== TICKET-17: Breakeven Stop ===
'''File''': <code>trade_execution_engine.py:64-68</code>
 
'''Problem''': Needed automatic breakeven move when in profit
 
<syntaxhighlight lang="python">
# NEW CONFIGURATION:
enable_breakeven_stop: bool = True
breakeven_activation: float = 25.0  # Points profit before moving to breakeven
breakeven_buffer: float = 2.0      # Points above/below entry for buffer
 
# Tested 10pt activation but cut winners too short (26% WR vs 49%)
# 25pt activation is the sweet spot
</syntaxhighlight>
 
----
 
=== TICKET-18: Creeper Move Handling ===
'''File''': <code>signal_generation_trade_management.py:582-595</code>
 
'''Problem''': Previous implementation blocked creeper signals entirely (too aggressive)
 
<syntaxhighlight lang="python">
# BEFORE: Creeper signals blocked with return None
 
# AFTER (comment explains fix):
# CORE BEHAVIOR: Creeper moves get -50 penalty + 0.7x target + uses NEAR_MA
# Previous implementation: Blocked entirely with return None (too aggressive)
#
# FIX: Let creeper signals through - penalty applied in setup_quality_detection,
# NEAR_MA technique used in _determine_entry_technique()
# Let the scoring system decide rather than blocking outright
</syntaxhighlight>
 
----
 
=== TICKET-19: MA Direction Filter + Score Adjustment ===
'''File''': <code>signal_generation_trade_management.py:95-97, 987-1034, 1955-2010</code>
 
'''Problem''': Trades against MA21 slope direction had poor performance
 
<syntaxhighlight lang="python">
# CONFIGURATION:
enable_ma_direction_filter: bool = True
 
# DIRECTION LOGIC COMPLETE REWRITE (_determine_signal_direction):
# BEFORE: Used alignment score threshold (>= 60%)
# AFTER: Uses MA21 slope as primary direction source
 
def _determine_signal_direction(self, timeframe_analysis, market_state, market_data=None):
    """MA21 SLOPE ALIGNMENT DIRECTION LOGIC (trade_philosophy.pdf)"""
    trend_direction = getattr(market_state, 'trend_direction', None)
 
    if trend_direction == "up":
        return Direction.LONG      # MA21 rising → only LONG
    elif trend_direction == "down":
        return Direction.SHORT    # MA21 declining → only SHORT
    else:
        # Fallback to MTF primary_direction if MA21 is flat/unknown
        return getattr(timeframe_analysis, 'primary_direction', None)
 
# SCORE ADJUSTMENT (lines 987-1034):
# +15% bonus if trade direction aligns with MA21 slope
# -10% penalty if trade direction against MA21 slope
</syntaxhighlight>
 
----
 
=== TICKET-20: Probability Zone Filter + ATR Trailing ===
'''File''': <code>signal_generation_trade_management.py:99-109, 628-817</code>, <code>trade_execution_engine.py:57-63, 295-340</code>
 
'''Problem''': Needed trade_philosophy.pdf concepts in code
 
<syntaxhighlight lang="python">
# NEW CONFIGURATION (Probability Zones):
enable_probability_zone_filter: bool = True
probability_zone_swing_lookback: int = 20
probability_zone_min_range: float = 20.0
three_finger_spread_threshold: float = 0.02
crash_bar_multiplier: float = 2.0
sideways_mean_reversion: bool = True
 
# NEW CONFIGURATION (ATR Trailing):
trailing_stop_method: str = "ATR_MULTIPLE"  # or "FIXED_POINTS"
atr_period: int = 14
atr_multiplier: float = 2.0  # 2x ATR = trailing distance
 
# NEW ATR CALCULATION in trade_execution_engine.py:295-340
def _calculate_atr(self, five_min_data: Dict) -> None:
    """Calculate Average True Range for dynamic trailing stop."""
    # TrueRange = max(high-low, abs(high-prev_close), abs(low-prev_close))
    # ATR = SMA(TrueRange, period)
    true_ranges = []
    for i in range(1, len(high_vals)):
        tr = max(
            high_vals[i] - low_vals[i],          # Current high - low
            abs(high_vals[i] - close_vals[i-1]),  # High - previous close
            abs(low_vals[i] - close_vals[i-1])    # Low - previous close
        )
        true_ranges.append(tr)
    self.current_atr = sum(true_ranges) / len(true_ranges)
</syntaxhighlight>
 
----
 
=== TICKET-21: Color Change Filter (DISABLED) ===
'''File''': <code>signal_generation_trade_management.py:111-118</code>
 
'''Problem''': color_change.pdf patterns too restrictive for automation
 
<syntaxhighlight lang="python">
# CONFIGURATION (disabled):
enable_color_change_filter: bool = False  # DISABLED - too restrictive
color_change_ma_proximity: float = 20.0  # Points to consider "near" MA
require_ma_bounce: bool = False          # Too strict
color_change_require_in_zones: bool = True
 
# NOTE: ColorChangeDetector class still exists for future use
# Implements liquidity sweep patterns:
# - LONG: Green bar sweeps BELOW red bar low + bounce from 21 MA
# - SHORT: Red bar sweeps ABOVE green bar high + rejection from 21 MA
</syntaxhighlight>
 
----
 
=== TICKET-24: Creeper Move Entry Technique Fix ===
'''File''': <code>signal_generation_trade_management.py:2037-2050</code>
 
'''Problem''': strategy_engine.py bug - uses wrong entry technique for creeper moves
 
<syntaxhighlight lang="python">
# STRATEGY ENGINE BUG FOUND:
# backtesting_standalone/src/strategy_engine.py lines 3338-3380
# checks bos_detected FIRST but doesn't consider is_creeper_move.
# This causes BOS entries in creeper moves (inappropriate).
 
# FIX: Check creeper FIRST before BOS
if is_creeper:
    # Creeper gets -50 penalty + 0.7x target from setup_quality_detection
    # But uses NEAR_MA as technique (NOT green_bar/red_bar!)
    return EntryTechnique.NEAR_MA  # Strategy engine fallback
</syntaxhighlight>
 
----
 
=== TICKET-25: Market State 5MIN → 1HOUR ===
'''File''': <code>market_state_analysis.py:191-360</code>
 
'''Problem''': Creeper threshold 0.5% calibrated for 1H bars (~0.8-1.2% range), but code used 5MIN (~0.16% range) = 98.9% false positives!
 
<syntaxhighlight lang="python">
# BEFORE:
required_tf = TimeframeValue.FIVE_MIN
 
# AFTER:
def validate_input(self, input_data: Dict, context: ComponentContext):
    """
    TICKET-25 FIX: Market state analysis uses 1-HOUR data (not 5MIN)
    to match strategy_engine.py behavior for creeper/railroad detection.
    """
    primary_tf = TimeframeValue.ONE_HOUR
    fallback_tf = TimeframeValue.FIVE_MIN
 
    if primary_tf in input_data and input_data[primary_tf] is not None:
        required_tf = primary_tf
    elif fallback_tf in input_data and input_data[fallback_tf] is not None:
        required_tf = fallback_tf
        # Warning: 5MIN fallback may cause inaccurate creeper detection
 
def _get_primary_timeframe(self, input_data: Dict) -> TimeframeValue:
    """
    TICKET-25 FIX: Use ONE_HOUR for market state analysis.
 
    The 0.5% creeper threshold is calibrated for 1-HOUR bars (~0.8-1.2% typical range),
    not 5-MIN bars (~0.16% typical range). Using 5MIN caused 98.9% false positives.
    """
    primary_tf = TimeframeValue.ONE_HOUR  # Was FIVE_MIN
</syntaxhighlight>
 
----
 
=== PDF-FIX: MA Buffer Points ===
'''File''': <code>signal_generation_trade_management.py:67-68</code>
 
'''Source''': Fab Four concept - "MA is a zone, not a thin line"
 
<syntaxhighlight lang="python">
# BEFORE:
ma_buffer_points: float = 5.000000  # Too tight!
 
# AFTER:
# PDF-FIX: MA is a "zone, not a thin line" (Fab Four) - use wider buffer
ma_buffer_points: float = 25.000000  # 21 MA zone width
</syntaxhighlight>
 
----
 
=== GRADING FIX: Score-to-Grade Recalculation ===
'''File''': <code>signal_generation_trade_management.py:1054, 1132-1170</code>
 
'''Problem''': Grade assigned from capped original score instead of adjusted score
 
<syntaxhighlight lang="python">
# BEFORE:
setup_quality=setup_quality.grade,    # Grade from CAPPED original score (79)
setup_score=setup_quality.score,      # Original score (79)
# Problem: Score=79 → Grade=A, but if adjustment makes it 89, should be A+!
 
# AFTER:
setup_quality=self._calculate_grade_from_score(adjusted_score),  # RECALCULATED
setup_score=adjusted_score,  # MA-adjusted score
 
# NEW METHOD ADDED:
def _calculate_grade_from_score(self, score: float) -> SetupQualityGrade:
    """GRADING FIX: Calculate grade from FINAL adjusted score."""
    if score >= 90: return SetupQualityGrade.A_PLUS
    elif score >= 80: return SetupQualityGrade.A
    elif score >= 70: return SetupQualityGrade.B
    elif score >= 60: return SetupQualityGrade.C
    elif score >= 50: return SetupQualityGrade.D
    else: return SetupQualityGrade.F
</syntaxhighlight>
 
----
 
== 7.3 New File: probability_zone_analysis.py (974 lines) ==
 
This file implements concepts from <code>trade_philosophy.pdf</code>:
 
=== Enums Defined ===
<syntaxhighlight lang="python">
class ProbabilityZone(Enum):
    TOP_THIRD = "top_third"          # 80% continuation probability
    TOP_HALF = "top_half"            # 65% continuation probability
    BOTTOM_HALF = "bottom_half"      # 35% continuation probability
    BOTTOM_THIRD = "bottom_third"    # 15% continuation (85% reversal)
 
class MarketStructure(Enum):
    UPTREND = "uptrend"              # Price > 21 MA > 200 MA
    DOWNTREND = "downtrend"          # Price < 21 MA < 200 MA
    SIDEWAYS = "sideways"            # No clear structure
    THREE_FINGER_SPREAD_BULL = "..."  # Large spread (bearish signal)
    THREE_FINGER_SPREAD_BEAR = "..."  # Large spread (bullish signal)
 
class PullbackType(Enum):
    HEALTHY_PULLBACK = "healthy_pullback"  # 45-degree drift, holds above halfway
    COLLAPSE = "collapse"                  # Vertical drop, breaks deeply
    NO_PULLBACK = "no_pullback"            # Price at or near highs
    BOUNCE = "bounce"                      # Bounce after crash (short opportunity)
 
class ColorChangeType(Enum):
    BULLISH_REVERSAL = "bullish_reversal"  # Green bar takes out red bar high
    BEARISH_REVERSAL = "bearish_reversal"  # Red bar takes out green bar low
    NO_PATTERN = "no_pattern"
</syntaxhighlight>
 
=== Key Classes ===
* <code>ProbabilityZoneResult</code> - Analysis result with zone, probabilities, MA structure
* <code>ColorChangeResult</code> - Pattern detection result
* <code>ProbabilityZoneConfig</code> - Configuration with thresholds
* <code>ProbabilityZoneAnalyzer</code> - Main analyzer class
* <code>ColorChangeDetector</code> - Detects liquidity sweep patterns
 
=== Configuration Defaults ===
<syntaxhighlight lang="python">
@dataclass
class ProbabilityZoneConfig:
    top_third_probability: float = 0.80    # 80% continuation
    top_half_probability: float = 0.65    # 65% continuation
    bottom_half_probability: float = 0.35  # 35% continuation
    bottom_third_probability: float = 0.15 # 15% continuation
 
    swing_lookback_bars: int = 20          # Bars for swing H/L
    crash_bar_multiplier: float = 2.0      # Bar > 2x avg = crash
    three_finger_min_spread_pct: float = 0.02  # 2% spread threshold
</syntaxhighlight>
 
----
 
== 7.4 timeframe_conversion.py Changes ==
 
'''File''': <code>src/core/timeframe_conversion.py</code>
 
=== Changes ===
# '''Emoji removal''' - All emoji characters replaced with <code>[OK]</code>, <code>[FAIL]</code>, <code>[CONV]</code>, etc.
# '''Date column fix''' - Handle 'date' as alias for 'timestamp'
# '''1m skip''' - Don't overwrite source file when saving
# '''Mixed timestamp format''' - Use <code>format='mixed'</code> for pandas parsing
 
<syntaxhighlight lang="python">
# Date column alias:
if 'date' in source_df.columns and 'timestamp' not in source_df.columns:
    source_df = source_df.rename(columns={'date': 'timestamp'})
    logger.info("[FIX] Renamed 'date' column to 'timestamp'")
 
# Skip 1m overwrite:
if timeframe == '1m':
    logger.info(f"[SKIP] 1m: Source file preserved (not overwritten)")
    continue


# Mixed timestamp parsing:
= PART 13: PUTTING IT ALL TOGETHER =
pd.to_datetime(df['timestamp'], format='mixed')
</syntaxhighlight>


----
== Trade Flow ==
 
== 7.5 main.py Changes ==
 
'''File''': <code>src/main.py</code>
 
=== Changes ===
# '''Hour filter configuration''' - TICKET-12 support
# '''Emoji removal''' - Console output cleanup
 
<syntaxhighlight lang="python">
# TICKET-12: Hour Filter configuration:
enable_hour_filter=strategy_config.get('enable_hour_filter', False),
blocked_hours=strategy_config.get('blocked_hours', [])
 
print(f"  TICKET-12 Hour Filter: Enabled={signal_generator_config.enable_hour_filter}, "
      f"Blocked Hours={signal_generator_config.blocked_hours}")
</syntaxhighlight>
 
----
 
== 7.6 Complete File Tree ==


<pre>
<pre>
services/backtest/src/
┌─────────────────────────────────────────────────────────────────┐
├── components/
STEP 1: Load data for all 5 timeframes                        │
  ├── market_state_analysis.py      # TICKET-25: 5MIN → 1HOUR
Daily, 4H, 1H, 15M, 5M OHLCV data                            │
  ├── multi_timeframe_analysis.py  # Whitespace cleanup
└─────────────────────────────────────────────────────────────────┘
  ├── probability_zone_analysis.py # NEW: trade_philosophy.pdf (974 lines)
                              ↓
  ├── setup_quality_detection.py    # TICKET-5: position sizing
┌─────────────────────────────────────────────────────────────────┐
  ├── signal_generation_trade_management.py # TICKET-7,8,10,11,12,13,18,19,20,21,24 + GRADING FIX
│  STEP 2: LAYER 1 - MTF Analysis (Foundation)                  
  └── trade_execution_engine.py    # TICKET-9,13,15,17,20: trailing/breakeven/ATR
│  Calculate MA21, MA200, trend direction for each timeframe      │
├── core/
Compute MTF alignment score                                    │
  ├── data_structures.py            # TICKET-15: current_stop_price field
└─────────────────────────────────────────────────────────────────┘
  └── timeframe_conversion.py      # Date fix, 1m skip, emoji removal
                              ↓
└── main.py                          # TICKET-12 config, emoji removal
┌─────────────────────────────────────────────────────────────────┐
 
STEP 3: LAYER 2 - Market State Analysis                        │
services/backtest/scripts/          # 50+ NEW analysis scripts
Run 7 algorithms: Railroad, Creeper, Phase, BOS, etc.         │
├── analyze_alignment_pnl.py
│  Calculate penalties and bonuses                                │
├── analyze_alignment_pnl_v2.py
└─────────────────────────────────────────────────────────────────┘
├── analyze_aplus.py
                              ↓
├── analyze_by_hour.py
┌─────────────────────────────────────────────────────────────────┐
├── analyze_combined_filters.py
│  STEP 4: LAYER 3 - Setup Quality Grading                        │
├── analyze_crash_short_potential.py
│  Score 5 factors, apply penalties/bonuses                      │
├── analyze_hour_filter.py
│  Assign grade: A+ / A / B / C / D / F                          │
├── analyze_hourly_pnl.py
└─────────────────────────────────────────────────────────────────┘
├── analyze_long_short_detail.py
                              ↓
├── analyze_longs.py
┌─────────────────────────────────────────────────────────────────┐
├── analyze_ma_alignment.py
│  STEP 5: LAYER 4 - HARD FILTERS (The Gate)  ◄── PASS/FAIL      │
├── analyze_ma_slope_filter.py
│  • Direction: MA21 slope matches trade direction?              │
├── analyze_morning_times.py
│  • Grade: Is grade A+, A, or B?                                │
├── analyze_pdf_results.py
│  • Hour: Is current hour allowed (not 9, 22, 23)?              │
├── analyze_quick_exits.py
│  ANY FAIL → NO TRADE                                            │
├── analyze_red_bar_rally.py
└─────────────────────────────────────────────────────────────────┘
├── analyze_shorts.py
                              ↓
├── analyze_stop_exits.py
┌─────────────────────────────────────────────────────────────────┐
├── analyze_stop_loss_detail.py
│  STEP 6: LAYER 5 - Entry Technique                              │
├── analyze_test_summary.py
│  Is price within ±25 points of MA21?                            │
├── analyze_trade_bias.py
│  Select entry technique (NEAR_MA, BOS_ENTRY, etc.)              │
├── analyze_trading_hours_filter.py
└─────────────────────────────────────────────────────────────────┘
├── analyze_trend_direction_at_entry.py
                              ↓
├── aplus_vs_a_analysis.py
┌─────────────────────────────────────────────────────────────────┐
├── check_all_data.py
│  STEP 7: Calculate Stop Loss                                    │
├── check_costs.py
│  BOS-based → Swing-based → Default (40 pts minimum)            │
├── check_data_range.py
└─────────────────────────────────────────────────────────────────┘
├── check_price_trend.py
                              ↓
├── comprehensive_analysis.py
┌─────────────────────────────────────────────────────────────────┐
├── comprehensive_backtest_analysis.py
│  STEP 8: Calculate Target                                      │
├── comprehensive_summary.py
│  50% of distance to MA (minimum 1.5× risk)                      │
├── cost_impact_analysis.py
└─────────────────────────────────────────────────────────────────┘
├── detailed_monthly.py
                              ↓
├── diagnose_color_change.py
┌─────────────────────────────────────────────────────────────────┐
├── diagnose_direction_bias.py
│  STEP 9: Execute Trade                                          │
├── framework_comparison_analysis.py
│  Apply entry slippage (+1 pt), create trade record              │
├── generate_test_summary.py
└─────────────────────────────────────────────────────────────────┘
├── grade_and_equity.py
                              ↓
├── monthly_breakdown.py
┌─────────────────────────────────────────────────────────────────┐
├── no_morning_analysis.py
│  STEP 10: Manage Trade                                          │
├── path_to_profitability.py
│  Monitor: Breakeven at +25 pts → Trail at +20 pts              │
├── philosophy_v1_blend_analysis.py
│  Exit: Stop hit | Target hit | Timeout                          │
├── root_cause_summary.py
└─────────────────────────────────────────────────────────────────┘
├── short_market_state_alignment.py
├── short_technique_analysis.py
├── simulate_target_rr.py
├── simulate_target_rr_v2.py
├── stop_out_deep_analysis.py
├── strategy_engine_gap_analysis.py
├── test_summary.py
└── v1_optimization_impact_analysis.py
</pre>
</pre>


----
----


= Part 8: Strategy Configuration =
= PART 14: HARD vs SOFT FILTERS =


== 8.1 76D Parameter Vector ==
== Understanding the Difference ==


The strategy uses '''regime-aware configuration''' with 76 parameters:
{| class="wikitable"
* '''44 Global Parameters''' - Constant across all market regimes
|-
* '''32 Regime Parameters''' - 8 parameters × 4 market regimes
! Filter Type !! Behavior !! Examples
 
|-
'''File''': <code>src/config/strategy_config.py</code>
| '''HARD''' || Blocks trade completely || Direction filter, Hour filter, Grade C/D/F
|-
| '''SOFT''' || Affects quality score || MTF alignment, Market state penalties
|}


=== Key Parameters ===
== Complete Filter List ==


{| class="wikitable"
{| class="wikitable"
! Parameter !! Default !! Description
|-
|-
| <code>primary_ma_period</code> || 21 || Main trend MA
! Filter !! Type !! Effect
|-
| MA21 Direction || '''HARD''' || Wrong direction = NO TRADE
|-
| Hour Filter || '''HARD''' || Hours 9, 22, 23 = NO TRADE
|-
|-
| <code>secondary_ma_period</code> || 200 || Long-term trend MA
| Grade < B || '''HARD''' || C/D/F grades = NO TRADE
|-
|-
| <code>default_stop_distance</code> || 40 pts || Minimum stop distance
| MTF Alignment || SOFT || Low alignment = reduced score (30% weight)
|-
|-
| <code>default_risk_reward</code> || 2.0 || Target R:R ratio
| Creeper Move || SOFT || -50 points penalty
|-
|-
| <code>ma_buffer_points</code> || 25 pts || MA zone width
| No Two-Day Trend || SOFT || -30 points penalty
|-
|-
| <code>creeper_move_penalty</code> || -50 || Score reduction
| Institutional Fight || SOFT || 0.7× score multiplier
|-
|-
| <code>railroad_trend_bonus</code> || +15 || Score increase
| Far from MA21 || SOFT || -40 points penalty
|}
|}


----
----


= Part 9: Decision Trees =
= APPENDIX A: CONFIGURATION VALUES =


== 9.1 Should I Trade This Setup? ==
== MTF Configuration ==


<pre>
{| class="wikitable"
START: Signal Generated
|-
  │
! Parameter !! Value !! Source File !! Description
  ▼
|-
[Is hour blocked (9, 22, 23)?]
| context_timeframe || DAILY || main.py:162 || Highest timeframe for overall bias
  │ Yes → SKIP (loss-making hours)
|-
  │ No ↓
| primary_timeframe || 1-HOUR || main.py:163 || Primary trend direction
  ▼
|-
[Is MA21 direction aligned with trade?]
| confirmation_timeframe || 15-MIN || main.py:164 || Entry timing confirmation
  │ LONG + MA rising? → Continue
|-
  │ SHORT + MA falling? → Continue
| entry_timeframe || 5-MIN || main.py:165 || Execution timeframe
  │ No alignment → SKIP
|-
  │
| require_all_timeframes_aligned || '''False''' || main.py:166 || Allow partial alignment
  ▼
|-
[Is price in probability zone?]
| min_alignment_score || '''0.70 (70%)''' || main.py:167 || Minimum MTF alignment score
  │ LONG + Bottom Third? → Continue (80% odds)
|-
  │ SHORT + Top Third? → Continue (80% odds)
| wait_for_15min_alignment || '''True''' || main.py:168 || Wait for 15M confirmation
  │ Wrong zone → SKIP
|-
  │
| min_15min_confirmation_bars || '''2 bars''' || main.py:169 || Bars needed for 15M confirmation
  ▼
|}
[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)
  ├─ Apply MA direction adjustment (+15% aligned, -10% against)
  │
  ▼
[Recalculate Grade from ADJUSTED score]
  │
  ├─ 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]
</pre>


----
== Entry Configuration ==


== 9.2 Where to Place Stop? ==
{| class="wikitable"
|-
! 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
|}


<pre>
== Stop/Target Configuration ==
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)
  │
  ▼
[ENFORCE minimum 40pt stop (TICKET-13)]
  │
  ▼
[Once trade moves in favor:]
  │
  ├─ 25 pts profit → Move stop to breakeven (TICKET-17)
  ├─ 20+ pts profit → Start trailing (TICKET-15/20)
  ├─ Use ATR-based trail distance (2x ATR, min 15 pts)
  │
  ▼
[Stop Placement Complete]
</pre>


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


= Part 10: Code Review Guidelines =
== Dynamic Stop Configuration ==


== 10.1 What Reviewers Should Check ==
{| class="wikitable"
|-
! 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
|}


* Code correctness (syntax, bugs)
== Slippage Configuration ==
* Integration (doesn't break other components)
* Test coverage
* Precision (6-decimal places per spec)
* Performance (no excessive logging)


== 10.2 What Reviewers Should NOT Question ==
{| 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
|}


* The penalty values themselves (-50, -30, etc.)
== Trade Execution Limits ==
* Why 21 MA and not 20 MA
* Why specific thresholds (these are trading decisions)
* Why certain hours are blocked


== 10.3 Trading Authority Principle ==
{| 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
|}


'''Rikk has final authority on:'''
== Cost Configuration ==
* Entry/exit conditions
* Threshold values
* Setup definitions
* What constitutes a valid signal
* Penalty/bonus amounts


'''Engineers have authority on:'''
{| class="wikitable"
* Code quality and structure
|-
* Performance optimization
! Parameter !! Value !! Source File !! Description
* Error handling
|-
* System integration
| commission_per_lot || '''Rs 20/lot/leg''' || signal_generation_trade_management.py:49 || Dhan broker commission
* Test coverage
|-
 
| 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
|}


= Part 11: Quick Reference Cards =
== Grading Configuration ==
 
== Card 1: Probability Zones ==
 
<pre>
TOP THIRD    = 80% continuation (SHORT zone)
TOP HALF    = 65% continuation
BOTTOM HALF  = 35% continuation
BOTTOM THIRD = 15% continuation (LONG zone with 85% reversal odds)
</pre>
 
== Card 2: Setup Quality Formula ==
 
<pre>
Score = (TF_align × 0.30) + (Trend × 0.20) + (Entry × 0.15) + (KeyLevel × 0.20) + (R:R × 0.15)
 
Then apply:
- Creeper detected? → Score - 50
- MA struggle? → Score - 30
- No two-day trend? → Score - 30
- Wrong phase? → Score - 25
- Institutional fight? → Score × 0.7
- MA direction aligned? → Score + 15%
- MA direction against? → Score - 10%
 
Finally: Recalculate grade from ADJUSTED score (not original!)
</pre>
 
== Card 3: Profit Taking ==
 
<pre>
1. Enter with 2 lots
2. Set stop above high (short) / below low (long)
3. Wait for follow-through bar (2nd bar after opposite color)
4. Take profit on 1 lot
5. Move stop to break-even
6. Wait for next follow-through bar
7. Take profit on remaining lot
8. Done
</pre>
 
== Card 4: JIRA Tickets Summary ==


{| class="wikitable"
{| class="wikitable"
! Ticket !! One-Line Summary
|-
|-
| TICKET-5 || Position sizing: 200 lots → 2/1 lots (realistic for Rs 1L capital)
! Parameter !! Value !! Source File
|-
|-
| TICKET-7 || R:R preservation: shift stop/target with slippage
| timeframe_alignment_weight || 30% || setup_quality_detection.py:44
|-
|-
| TICKET-8 || CTT rate: 0.05% → 0.005% per leg (5x fix)
| trend_strength_weight || 20% || setup_quality_detection.py:45
|-
|-
| TICKET-9 || Market impact: cap slippage at 2 pts max
| key_level_proximity_weight || 20% || setup_quality_detection.py:47
|-
|-
| TICKET-10 || Entry technique: align with strategy_engine.py priority order
| entry_technique_weight || 15% || setup_quality_detection.py:46
|-
|-
| TICKET-11 || BOS stops: 5 → 10 bar lookback + 5pt buffer
| risk_reward_weight || 15% || setup_quality_detection.py:48
|-
|-
| TICKET-12 || Hour filter: block hours 9, 22, 23 (loss-making)
| a_plus_min_score || 90 || setup_quality_detection.py:51
|-
|-
| TICKET-13 || Min stop: 20 → 40 pts (noise protection)
| a_min_score || 80 || setup_quality_detection.py:52
|-
|-
| TICKET-15 || Trailing stop: add current_stop_price tracking
| b_min_score || 70 || setup_quality_detection.py:53
|}
 
== Probability Zone Configuration ==
 
{| class="wikitable"
|-
|-
| TICKET-17 || Breakeven: move stop to entry at 25pt profit
! Parameter !! Value !! Source File
|-
|-
| TICKET-18 || Creeper handling: let through (don't block), use penalty
| enable_probability_zone_filter || True || signal_generation_trade_management.py:104
|-
|-
| TICKET-19 || MA direction: use slope as primary direction source
| probability_zone_swing_lookback || 20 bars || signal_generation_trade_management.py:105
|-
|-
| TICKET-20 || Probability zones + ATR trailing (trade_philosophy.pdf)
| probability_zone_min_range || 20 points || signal_generation_trade_management.py:106
|-
|-
| TICKET-21 || Color change: disabled (too restrictive)
| top_third_threshold || 66.7% || probability_zone_analysis.py:125
|-
|-
| TICKET-24 || Creeper entry: use NEAR_MA technique (not green/red bar)
| top_third_probability || 80% || probability_zone_analysis.py:131
|-
|-
| TICKET-25 || Market state: 5MIN → 1HOUR for creeper detection
| bottom_third_probability || 15% || probability_zone_analysis.py:134
|-
|-
| GRADING FIX || Recalculate grade from adjusted score
| crash_bar_multiplier || 2.0 || probability_zone_analysis.py:145
|-
|-
| PDF-FIX || MA buffer: 5 → 25 pts (MA is zone, not line)
| 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