Jump to content

Alpha Research: Difference between revisions

From PlusEV Wiki Page
No edit summary
Blanked the page
Tag: Blanking
Line 1: Line 1:
# Alpha Research: MCX Crude Oil MA21 Strategy


**Single Source of Truth for the PlusEV Trading System**
---
## Quick Reference: Backtest Proof
| Metric | Value | Notes |
|--------|-------|-------|
| **Total P&L** | Rs +25,48,101 | 19-month validation period |
| **Win Rate** | 57.6% | Above 55% threshold |
| **Profit Factor** | 1.20 | Risk-adjusted returns |
| **Total Trades** | 7,534 | Statistical significance |
| **Initial Capital** | Rs 1,00,000 | Starting portfolio |
| **Final Capital** | Rs 26,48,101 | 2548% return |
**Branch**: `rikk_mtf_backtest001` | **Commit**: `68dae212`
> "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
```
Simple systems outperform complex ones.
Market behavior is probabilistic, not predictive.
The goal is positioning with asymmetric probabilities, not prediction.
```
### 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 the high-probability side
---
## 1.2 Probability Zones (Halves & Thirds)
Every large move is divided into **halves and thirds**, creating probability zones.
### Odds of Continuation After Pullback
```
┌─────────────────────────────────────────────────────┐
│  SWING HIGH                                        │
├─────────────────────────────────────────────────────┤
│  TOP THIRD        →  ~80% chance of new high        │  ← IDEAL SHORT ZONE
├─────────────────────────────────────────────────────┤
│  TOP HALF        →  ~65% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM HALF      →  ~35% chance of new high        │
├─────────────────────────────────────────────────────┤
│  BOTTOM THIRD    →  ~15% chance of new high        │  ← IDEAL LONG ZONE
├─────────────────────────────────────────────────────┤
│  SWING LOW                                          │
└─────────────────────────────────────────────────────┘
```
### Code Implementation
```python
# File: signal_generation_trade_management.py:99-109
enable_probability_zone_filter: bool = True
probability_zone_swing_lookback: int = 20    # Bars to find swing H/L
probability_zone_min_range: float = 20.0    # Min range for valid zone
```
---
## 1.3 The Crash Play (Core Strategy)
### What is a Crash Bar?
- **Much larger** than recent bars
- **Fast, violent, elongated** movement
- Indicates a **structural break**
### The Crash Play Logic
```
1. Identify crash bar (bar > 2x average size)
2. Divide it into halves and thirds
3. Watch for bounce INTO these zones
4. Enter when:
  - Color change confirms (red overtakes green), OR
  - Price reaches upper zones
```
### Key Statistics
- 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
```python
# File: signal_generation_trade_management.py:108
crash_bar_multiplier: float = 2.0  # Bar must be 2x average for crash detection
```
---
## 1.4 Pullback vs Collapse (Critical Distinction)
### Healthy Pullback (Tradeable)
| Characteristic | Description |
|----------------|-------------|
| Angle | 45-degree drifting decline, NOT vertical |
| Bars | No violent or oversized red bars |
| Depth | Holds **above halfway point** of prior run |
| Confirmation | Color change (green overtakes red) |
**Interpretation**: Pullbacks are rests, not reversals. Odds favor continuation.
### Collapse (NOT Tradeable)
| Characteristic | Description |
|----------------|-------------|
| Angle | Vertical, elongated, violent first drop |
| Depth | Breaks deeply into or below prior run |
| Momentum | Abrupt and forceful |
**Interpretation**: Indicates institutional selling. Bounces are sucker plays.
---
## 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
```
Markets top between leg 3 and leg 5.
- Buy: legs 1-2
- Ride: leg 3
- Take profits: legs 4-5
- Buying late (leg 4-5) = large downside vs small upside
```
### 2. Vertical Acceleration in Final Leg
```
If the last leg is STEEPER than prior legs → likely final leg
The most vertical leg is usually the top.
```
### 3. Exhaustion Bar
```
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
```
### 4. Three-Finger Spread (Dual Space)
```
Large separation between:
- Price
- 21-period MA
- 200-period MA
= Many traders holding large unrealized profits
= Any red bar can trigger mass profit-taking
= Creates fast, violent declines
```
### Code Implementation
```python
# File: signal_generation_trade_management.py:107
three_finger_spread_threshold: float = 0.02  # 2% min spread for detection
```
---
# Part 2: Entry Methodology
## 2.1 The Fab Four Concept
The **Fab Four** defines the key reference points for entries and stops:
```
┌─────────────────────────────────────────────────────┐
│  FAB FOUR ELEMENTS                                  │
├─────────────────────────────────────────────────────┤
│  1. Previous Day High/Low (PDHL)                    │
│  2. 21-Period Moving Average                        │
│  3. 200-Period Moving Average                      │
│  4. Yesterday's Close                              │
└─────────────────────────────────────────────────────┘
```
### MA is a ZONE, Not a Line
> "The MA is a zone, not a thin line. Don't be exact with this."
```python
# File: signal_generation_trade_management.py:68
ma_buffer_points: float = 25.0  # 21 MA zone width (not a thin line)
```
### Fab Four Tightness = Explosive Potential
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
```
FOR SHORTS:
┌─────────────────────────────────────────────────────┐
│  CEILING (Best short position)                      │
│  ═══════════════════════════════════════════        │  ← Price right under Fab Four
│  Price opens HERE                                  │
└─────────────────────────────────────────────────────┘
FOR LONGS:
┌─────────────────────────────────────────────────────┐
│  Price opens HERE                                  │
│  ═══════════════════════════════════════════        │  ← Price right above Fab Four
│  FLOOR (Best long position)                        │
└─────────────────────────────────────────────────────┘
```
### Multi-Timeframe Alignment
Check all timeframes simultaneously:
```
┌────────┬────────┬────────┬────────┐
│  2min  │  5min  │  15min │  Daily │
│  ────  │  ────  │  ────  │  ────  │
│ Under  │ Under  │ Under  │ Under  │
│  200  │  200  │  200  │  200  │
│ Tight  │ Tight  │ Tight  │ Tight  │
└────────┴────────┴────────┴────────┘
        = ALIGNED = HIGH QUALITY SETUP
```
### Code Implementation
```python
# File: setup_quality_detection.py:43-48
timeframe_alignment_weight: float = 0.30  # 30% of setup quality score
```
---
## 2.3 Bar-by-Bar vs Big Bar Stops
### The Rule
| When to Use | Stop Method | Why |
|-------------|-------------|-----|
| **Near MA** (hugging) | Big Bar stops | Eliminates noise |
| **Far from MA** (extended) | Bar-by-bar stops | Protect extended gains |
### The Warning
> "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
| Type | Description | When to Use |
|------|-------------|-------------|
| **Event Stop** | Based on price action event | Primary choice |
| **Maximum Stop** | Dollar-based max loss | Fallback when event too far |
### The Goal
```
┌─────────────────────────────────────────────────────┐
│  FAB FOUR ZONE (Helping Zone)                      │
├─────────────────────────────────────────────────────┤
│  ↑ STOP SHOULD BE HERE (above/below Fab Four)      │
├─────────────────────────────────────────────────────┤
│  Entry price                                        │
└─────────────────────────────────────────────────────┘
```
> "The real goal is to get your stop beyond the Fab Four helping zone."
### Code Implementation
```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
```
---
## 3.2 Stop and Reverse Rules
Three criteria for a valid **Stop and Reverse**:
| Criteria | Description |
|----------|-------------|
| **1. Immediate** | Stop out happens INSTANTLY, not gradually |
| **2. Violent** | Move that stops you is hard, powerful, shakes earth |
| **3. Decent Position** | New position is NOT into resistance/support |
### Invalid Stop and Reverse
```
❌ 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
```
### Code Implementation
```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
```
---
# Part 4: Color Change Confirmation
## 4.1 The Color Change Entry
### Entry Trigger
```
FOR SHORTS:
Red bar closes BELOW green bar's low → ENTER SHORT
Stop: Above the high
FOR LONGS:
Green bar closes ABOVE red bar's high → ENTER LONG
Stop: Below the low
```
### Key Rule: Don't Wait for Bar to Complete
> "As soon as the red bar crosses below the green, boom boom boom boom boom. You're in."
---
## 4.2 Profit Taking Rules
### The Two-Bar Rule
> "Take profits TWO bars after the opposite color, NOT one bar."
```
SHORT TRADE:
┌─────────────────────────────────────────────────────┐
│  GREEN bar (opposite color)                        │
├─────────────────────────────────────────────────────┤
│  RED bar 1 ← IGNITING bar (DO NOT take profit)      │
├─────────────────────────────────────────────────────┤
│  RED bar 2 ← FOLLOW-THROUGH bar (TAKE PROFIT)      │
└─────────────────────────────────────────────────────┘
```
### Position Management Flow
```
Step 1: Enter with 2 lots
Step 2: Set stop above high
Step 3: Take profit on 1 lot (first follow-through bar)
Step 4: Move stop to break-even
Step 5: Take profit on remaining lot (second follow-through)
Step 6: Done
```
> "The first lot is your REAL trade. The second lot is the cherry on top."
### Code Implementation
```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
```
---
## 4.3 The Traffic Jam Concept
When price gaps below **everything from prior day**:
```
┌─────────────────────────────────────────────────────┐
│  Yesterday's 200 MA                                │
│  Yesterday's 20 MA                                  │
│  Yesterday's Close                                  │
│  ═══════════════════════════════════════════        │
│  TRAFFIC JAM ZONE (resistance on any rally)        │
│  ═══════════════════════════════════════════        │
│                                                    │
│  TODAY'S GAP DOWN OPEN                              │
└─────────────────────────────────────────────────────┘
```
**Rule**: Any move UP into the traffic jam meets resistance. Short rallies into this zone.
---
# Part 5: Trading Glossary for Engineers
| Trading Term | System Translation | Code Location | Why It Matters |
|--------------|-------------------|---------------|----------------|
| **Creeper Move** | Small-bodied bars, consistent direction, low volume | `market_state_analysis.py:is_creeper_move` | Institutional accumulation before explosion. **PENALTY: -50 points** |
| **Railroad Trend** | Alternating green/red bars touching MA | `market_state_analysis.py:is_railroad_trend` | Healthy trend, not overextended. **BONUS: +15 points** |
| **Two-Day Trend** | Price consistently above/below MA for 2+ days | `market_state_analysis.py:has_two_day_trend` | Confirms trend maturity. **Required for A+ grade** |
| **Institutional Fight** | High volume with narrow range | `market_state_analysis.py:institutional_fight_in_progress` | Buyers vs sellers battle. **MULTIPLIER: 0.7x score** |
| **Discount Zone** | Price below 21 MA (for longs) | `probability_zone_analysis.py` | 80% continuation probability |
| **Premium Zone** | Price above 21 MA (for shorts) | `probability_zone_analysis.py` | Entry zone for short trades |
| **Fab Four** | PDHL, 21 MA, 200 MA, Yesterday's Close | `signal_generation.py:_calculate_stop_loss()` | Stop loss placement hierarchy |
| **Color Change** | Bar closes opposite color after move | `probability_zone_analysis.py:ColorChangeDetector` | Confirms reversal/continuation |
| **Break of Structure (BOS)** | Price closes beyond recent swing H/L | `market_state_analysis.py:bos_detected` | Confirms trend continuation/reversal |
| **MA Zone** | MA is a band, not thin line (21 MA +/- 25pts) | `signal_generation.py:ma_buffer_points=25` | "Fab Four" concept from philosophy |
| **Trend Phase** | EARLY / MIDDLE / LATE classification | `market_state_analysis.py:trend_phase` | MIDDLE phase = optimal entry timing |
| **Crash Bar** | Bar > 2x average size, violent | `probability_zone_analysis.py:crash_bar_multiplier` | Structural break indicator |
| **Traffic Jam** | Yesterday's price activity zone | Conceptual | Resistance zone for gaps |
| **Three-Finger Spread** | Large gap between Price, 21 MA, 200 MA | `signal_generation.py:three_finger_spread_threshold` | Market top indicator |
---
# Part 6: Component Architecture
## 6.1 Pipeline Flow
```
┌─────────────────┐  ┌───────────────────┐  ┌────────────────────┐
│  Data Manager  │ → │  Trend Analysis  │ → │  Market State      │
│  (1M/5M/1H/1D)  │  │  (MA21, MA200)    │  │  (7 Detections)    │
└─────────────────┘  └───────────────────┘  └────────────────────┘
                                                      ↓
┌─────────────────┐  ┌───────────────────┐  ┌────────────────────┐
│  Trade Exec    │ ← │  Signal Gen      │ ← │  Setup Quality    │
│  (P&L, Costs)  │  │  (Entry/Exit)    │  │  (5-Factor Score)  │
└─────────────────┘  └───────────────────┘  └────────────────────┘
```
---
## 6.2 Setup Quality Detection
**File**: `src/components/setup_quality_detection.py`
### 5-Factor Weighted Scoring System
| Factor | Weight | What It Measures |
|--------|--------|------------------|
| Timeframe Alignment | **30%** | All timeframes agree on direction |
| Trend Strength | **20%** | Healthy trend without warnings |
| Entry Quality | **15%** | Entry near MA, clean execution |
| Key Level Proximity | **20%** | Entry near support/resistance |
| Risk/Reward | **15%** | Favorable profit potential |
### Penalty System
| 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 |
| Wrong Trend Phase | -25 pts | Too early or too late in trend |
| Not Near MA | -40 pts | Entry too far from edge |
| Institutional Fight | 0.7x | Wait for resolution |
### Grade Thresholds
| Grade | Score | Position Size | Auto-Trade? |
|-------|-------|---------------|-------------|
| A+ | >= 90 | 2 lots | Yes |
| A | >= 80 | 1 lot | Yes |
| B | >= 70 | 1 lot | No |
| C | >= 60 | 1 lot | No |
| D | >= 50 | 1 lot | No |
| F | < 50 | 1 lot | No |
---
## 6.3 Market State Analysis
**File**: `src/components/market_state_analysis.py`
### 7 Detection Algorithms
| # | 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 |
| 4 | Market State | TRENDING / SIDEWAYS / VOLATILE | Different strategy rules |
| 5 | Two-Day Trend | Multi-day momentum | Required for A+ grade |
| 6 | Trend Phase | EARLY / MIDDLE / LATE | MIDDLE = optimal entry |
| 7 | Institutional Behavior | Volume + price patterns | Fight = wait, Accumulation = prepare |
---
## 6.4 Signal Generation
**File**: `src/components/signal_generation_trade_management.py`
### Entry Filters Applied
| Filter | Config Key | Purpose |
|--------|------------|---------|
| Hour Filter | `blocked_hours: [9, 22, 23]` | Block loss-making hours |
| MA Direction | `enable_ma_direction_filter: True` | LONG only if MA rising |
| Probability Zone | `enable_probability_zone_filter: True` | Entry in favorable zones |
| Color Change | `enable_color_change_filter: False` | Disabled (too restrictive) |
---
# Part 7: Branch Changes (develop -> rikk_mtf_backtest001)
## 7.1 JIRA Fixes with Trading Context
| Ticket | Change | Trading Reason | Code Reference |
|--------|--------|----------------|----------------|
| **TICKET-5** | Position sizing: 100 -> 1-2 lots | Rs 1L capital = max 2 lots realistic | `setup_quality_detection.py:545-579` |
| **TICKET-7** | R:R preserved after slippage | Stop/target shift maintains edge | `signal_generation.py:250-272` |
| **TICKET-8** | CTT rate: 0.05% -> 0.01% | Matched Dhan broker actual rates | `signal_generation.py:53-55` |
| **TICKET-11** | BOS stop: 5 -> 10 bar lookback | Trend entries need wider stops | `signal_generation.py:80-81` |
| **TICKET-12** | Hour filter: block 9, 22, 23 | Data-driven loss-making hours | `signal_generation.py:135-137` |
| **TICKET-13** | Min stop: 20 -> 40 points | Price noise hits tight stops | `signal_generation.py:59` |
| **TICKET-19** | MA direction alignment | LONG only when MA21 rising | `signal_generation.py:96-97` |
| **TICKET-20** | Probability zone filter | Top third = 80% continuation | `signal_generation.py:99-109` |
| **TICKET-21** | Color change detector | Liquidity sweep confirmation | `signal_generation.py:111-118` |
| **TICKET-25** | 1-hour data for market state | Creeper detection needs higher TF | `market_state_analysis.py:209-222` |
---
## 7.2 Key Files Added/Modified
### New Components (Entire `src/` directory)
```
services/backtest/src/
├── components/
│  ├── market_state_analysis.py      # 7 detection algorithms
│  ├── setup_quality_detection.py    # 5-factor scoring
│  ├── signal_generation_trade_management.py  # Entry/exit logic
│  ├── probability_zone_analysis.py  # Halves/thirds zones
│  └── trend_analysis_core.py        # MA calculations
├── config/
│  └── strategy_config.py            # 76D parameter vector
└── core/
    └── data_structures.py            # Trading enums/types
```
---
# Part 8: Strategy Configuration
## 8.1 76D Parameter Vector
The strategy uses **regime-aware configuration** with 76 parameters:
- **44 Global Parameters** - Constant across all market regimes
- **32 Regime Parameters** - 8 parameters x 4 market regimes
**File**: `src/config/strategy_config.py`
### Key Parameters
| Parameter | Default | Description |
|-----------|---------|-------------|
| `primary_ma_period` | 21 | Main trend MA |
| `secondary_ma_period` | 200 | Long-term trend MA |
| `default_stop_distance` | 40 pts | Minimum stop distance |
| `default_risk_reward` | 2.0 | Target R:R ratio |
| `ma_buffer_points` | 25 pts | MA zone width |
| `creeper_move_penalty` | -50 | Score reduction |
| `railroad_trend_bonus` | +15 | Score increase |
---
# Part 9: Decision Trees
## 9.1 Should I Trade This Setup?
```
START: Signal Generated
  │
  ▼
[Is hour blocked (9, 22, 23)?]
  │ Yes → SKIP (loss-making hours)
  │ No ↓
  ▼
[Is MA21 direction aligned with trade?]
  │ LONG + MA rising? → Continue
  │ SHORT + MA falling? → Continue
  │ No alignment → SKIP
  │
  ▼
[Is price in probability zone?]
  │ LONG + Bottom Third? → Continue (80% odds)
  │ SHORT + Top Third? → Continue (80% odds)
  │ Wrong zone → SKIP
  │
  ▼
[Calculate Setup Quality Score]
  │
  ├─ Apply 5-factor scoring (TF 30%, Trend 20%, Entry 15%, KeyLevel 20%, R:R 15%)
  ├─ Apply penalties (creeper -50, MA struggle -30, etc.)
  ├─ Apply institutional fight multiplier (0.7x)
  │
  ▼
[Assign Grade (A+ to F)]
  │
  ├─ A+ or A → Auto-trade eligible (2 lots for A+, 1 lot for A)
  ├─ B to D → Manual review (1 lot)
  ├─ F → Skip or minimal size
  │
  ▼
[Execute Trade with Position Size]
```
---
## 9.2 Where to Place Stop?
```
START: Trade Direction Determined
  │
  ▼
[Is Fab Four zone tight and close?]
  │ Yes → Place stop BEYOND Fab Four zone
  │ No ↓
  ▼
[Can I afford stop beyond Fab Four?]
  │ Yes → Use EVENT stop (beyond Fab Four)
  │ No → Use MAXIMUM loss stop ($6000 max)
  │
  ▼
[Once trade moves in favor:]
  │
  ├─ Move stop to recent swing high/low
  ├─ Then move to break-even after first profit
  │
  ▼
[Stop Placement Complete]
```
---
# Part 10: Code Review Guidelines
## 10.1 What Reviewers Should Check
- [ ] Code correctness (syntax, bugs)
- [ ] 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
- The penalty values themselves (-50, -30, etc.)
- Why 21 MA and not 20 MA
- Why specific thresholds (these are trading decisions)
- Why certain hours are blocked
## 10.3 Trading Authority Principle
**Rikk has final authority on:**
- Entry/exit conditions
- Threshold values
- Setup definitions
- What constitutes a valid signal
- Penalty/bonus amounts
**Engineers have authority on:**
- Code quality and structure
- Performance optimization
- Error handling
- System integration
- Test coverage
---
# Part 11: Quick Reference Cards
## Card 1: Probability Zones
```
TOP THIRD    = 80% continuation (SHORT zone)
TOP HALF    = 65% continuation
BOTTOM HALF  = 35% continuation
BOTTOM THIRD = 15% continuation (LONG zone with 85% reversal odds)
```
## Card 2: Setup Quality Formula
```
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
```
## Card 3: Profit Taking
```
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
```
---
*Last Updated: 2026-01-05 | Branch: rikk_mtf_backtest001 | Validated: 19-month backtest*

Revision as of 19:26, 4 January 2026