Alpha Research5: Difference between revisions
Plusev.blr (talk | contribs) No edit summary |
No edit summary |
||
| (5 intermediate revisions by one other user not shown) | |||
| Line 1: | Line 1: | ||
= | = Multi-Timeframe Trading Strategy System = | ||
'''Version:''' 2.0 | '''Last Updated:''' 2026-01-12 | '''Status:''' Production | |||
== | == Executive Summary == | ||
The | This document describes a systematic, rule-based crude oil futures trading strategy implemented as a multi-component backtesting system. The strategy uses '''multi-timeframe alignment''' (5M to Daily), '''market state analysis''', '''setup quality grading''', and '''institutional-grade signal generation''' to identify high-probability trade setups. | ||
{| class="wikitable" style="width:100%" | |||
|+ '''System Statistics (Latest Backtest)''' | |||
|- | |||
! Metric !! Value !! Notes | |||
|- | |||
| Total Trades || 1,829 || 7-month period (Jun 2025 - Dec 2025) | |||
|- | |||
| Win Rate || 55.1% || Above random chance | |||
|- | |||
| Avg Holding Period || 2.8 hours || Intraday focus | |||
|- | |||
| Primary Direction || 85% Short || Trend-following bias | |||
|- | |||
| Exit Types || Stop: 80%, Target: 17%, Timeout: 4% || Stop-based risk management | |||
|} | |||
---- | |||
== System Architecture Overview == | |||
<pre> | |||
+------------------------------------------+ | |||
| DATA LAYER | | |||
| +---------+ +---------+ +---------+ | | |||
| | 1-Min | | 5-Min | | 15-Min | | | |||
| | OHLCV | | OHLCV | | OHLCV | | | |||
| +---------+ +---------+ +---------+ | | |||
| +---------+ +---------+ +---------+ | | |||
| | 1-Hour | | 4-Hour | | Daily | | | |||
| | OHLCV | | OHLCV | | OHLCV | | | |||
| +---------+ +---------+ +---------+ | | |||
+---------------------|--------------------+ | |||
| | |||
v | |||
+-------------------------------------------------------------------------------------------+ | |||
| PIPELINE ENGINE (Orchestrator) | | |||
| | | |||
| +---------------+ +---------------+ +---------------+ +---------------+ | | |||
| | LAYER 1 | | LAYER 2 | | LAYER 3 | | LAYER 4 | | | |||
| | Trend |--->| Market State |--->| Setup Quality |--->| Signal | | | |||
| | Analysis | | Analysis | | Detection | | Generation | | | |||
| +---------------+ +---------------+ +---------------+ +---------------+ | | |||
| | | | | | | |||
| v v v v | | |||
| [MA21, MA200] [range_bound] [A+/A/B/C/D/F] [Entry/Stop/TP] | | |||
| [Trend Direction] [creeper_move] [Score 0-100] [Direction] | | |||
| [Trend Phase] [narrow_volume] [Risk %] [Position Size] | | |||
| | | |||
| | | | |||
| v | | |||
| +-------------------+ | | |||
| | LAYER 5 | | | |||
| | Trade Execution | | | |||
| | Engine | | | |||
| +-------------------+ | | |||
| | | | |||
| v | | |||
| [Open/Manage/Close Trades] | | |||
| [P&L Calculation] | | |||
| [Cost Accounting] | | |||
+-------------------------------------------------------------------------------------------+ | |||
| | |||
v | |||
+------------------------------------------+ | |||
| OUTPUT LAYER | | |||
| +------------------+ +---------------+ | | |||
| | Trade-Level CSV | | Summary JSON | | | |||
| | (All trades) | | (Metrics) | | | |||
| +------------------+ +---------------+ | | |||
+------------------------------------------+ | |||
</pre> | |||
---- | |||
== Component Details == | |||
=== Layer 1: Multi-Timeframe Trend Analysis === | |||
'''Purpose:''' Analyze trend direction and strength across 5 timeframes | |||
'''File:''' <code>src/components/multi_timeframe_analysis.py</code>, <code>src/components/trend_analysis_core.py</code> | |||
'''Timeframes Analyzed:''' | |||
{| class="wikitable" | |||
|- | |||
! Timeframe !! Weight !! Purpose | |||
|- | |||
| Daily (1D) || 30% || Context (overall trend) | |||
|- | |||
| 4-Hour (4H) || 25% || Primary trend | |||
|- | |||
| 1-Hour (1H) || 20% || Confirmation | |||
|- | |||
| 15-Min (15M) || 15% || Fine-tuning | |||
|- | |||
| 5-Min (5M) || 10% || Entry timing | |||
|} | |||
'''Key Calculations:''' | |||
<pre> | <pre> | ||
Alignment Score = SUM(Weight[tf] * Direction_Match[tf]) for all tf | |||
Where: | |||
- Direction_Match = 1 if tf direction matches dominant direction, else 0 | |||
- Dominant direction = direction with highest weighted votes | |||
MA Analysis per Timeframe: | |||
- MA21 (fast) - Short-term trend | |||
- MA200 (slow) - Long-term trend | |||
- Price position relative to MAs | |||
- MA slope (trending vs flat) | |||
</pre> | </pre> | ||
'''Output:''' <code>TimeframeAnalysisResult</code> | |||
* <code>final_direction</code>: LONG / SHORT / NEUTRAL | |||
* <code>alignment_score</code>: 0.0 - 1.0 | |||
* <code>timeframe_results</code>: Per-timeframe analysis dictionary | |||
---- | ---- | ||
== | === Layer 2: Market State Analysis === | ||
'''Purpose:''' Classify current market conditions into actionable states | |||
{| class="wikitable" | '''File:''' <code>src/components/market_state_analysis.py</code> | ||
'''Market States:''' | |||
<pre> | |||
+-------------------+--------------------------------+------------------+ | |||
| Market State | Characteristics | Trading Action | | |||
+-------------------+--------------------------------+------------------+ | |||
| range_bound | Price oscillating, no clear | Trade reversals | | |||
| | trend, MA21 relatively flat | at range edges | | |||
+-------------------+--------------------------------+------------------+ | |||
| creeper_move | Slow, grinding trend with | Trade WITH trend | | |||
| | small candles, steady MA21 | on pullbacks | | |||
+-------------------+--------------------------------+------------------+ | |||
| narrow_low_volume | Tight range, reduced volume, | CAUTION - await | | |||
| | consolidation pattern | breakout | | |||
+-------------------+--------------------------------+------------------+ | |||
| trending | Strong directional move, | Trade WITH trend | | |||
| | clear MA separation | aggressively | | |||
+-------------------+--------------------------------+------------------+ | |||
</pre> | |||
'''Detection Algorithm:''' | |||
<pre> | |||
1. Calculate recent volatility (ATR or range) | |||
2. Calculate MA21 slope | |||
3. Calculate volume relative to average | |||
4. Apply classification rules: | |||
IF slope < threshold AND range tight THEN narrow_low_volume | |||
ELIF slope small AND trend present THEN creeper_move | |||
ELIF volatility high AND no trend THEN range_bound | |||
ELIF strong directional move THEN trending | |||
</pre> | |||
'''Output:''' <code>MarketStateResult</code> | |||
* <code>market_state</code>: Enum value | |||
* <code>volatility_metrics</code>: ATR, range data | |||
* <code>trend_phase</code>: early/middle/late/exhaustion | |||
---- | |||
=== Layer 3: Setup Quality Detection === | |||
'''Purpose:''' Score and grade trade setups using 5-factor weighted system | |||
'''File:''' <code>src/components/setup_quality_detection.py</code> | |||
'''5-Factor Scoring System:''' | |||
<pre> | |||
+-------------------------+--------+------------------------------------------+ | |||
| Factor | Weight | Description | | |||
+-------------------------+--------+------------------------------------------+ | |||
| Timeframe Alignment | 30% | How many timeframes agree on direction | | |||
| Trend Strength | 20% | MA slope, price momentum | | |||
| Entry Quality | 15% | Clean candle, near MA, not extended | | |||
| Key Level Proximity | 20% | Near support/resistance levels | | |||
| Risk/Reward Ratio | 15% | Potential reward vs risk | | |||
+-------------------------+--------+------------------------------------------+ | |||
= 100% | |||
</pre> | |||
'''Grade Classification:''' | |||
<pre> | |||
Score >= 90 --> A+ Grade (Best setups, full position) | |||
Score >= 80 --> A Grade (Excellent, 80% position) | |||
Score >= 70 --> B Grade (Good, 60% position) | |||
Score >= 60 --> C Grade (Average, 40% position) | |||
Score >= 50 --> D Grade (Below average, 20% position) | |||
Score < 50 --> F Grade (Poor, NO TRADE) | |||
</pre> | |||
'''Penalty System:''' | |||
<pre> | |||
Penalties Applied: | |||
- Creeper Move detected: -50 points | |||
- MA Struggle (price fighting MA): -30 points | |||
- Missing Two-Day Trend: -30 points | |||
- Phase Mismatch: -25 points | |||
- Far from Key Level: -50 points | |||
- Far from MA: -40 points | |||
Bonuses Applied: | |||
+ Railroad Trend (strong alignment): +15 points | |||
+ At Key Level: +10 points | |||
+ Clean Entry Candle: +10 points | |||
</pre> | |||
'''Institutional Fight Detection:''' | |||
<pre> | |||
IF 4H direction != Daily direction THEN | |||
Apply 0.7x multiplier to final score | |||
(Institutions may be fighting retail) | |||
</pre> | |||
'''Output:''' <code>SetupQualityResult</code> | |||
* <code>grade</code>: A+ / A / B / C / D / F | |||
* <code>score</code>: 0 - 100 | |||
* <code>factor_scores</code>: Individual factor breakdown | |||
* <code>position_size</code>: Recommended lots | |||
* <code>risk_percent</code>: Account risk percentage | |||
* <code>can_auto_trade</code>: Boolean | |||
---- | |||
=== Layer 4: Signal Generation & Trade Management === | |||
'''Purpose:''' Generate precise entry/exit signals with risk parameters | |||
'''File:''' <code>src/components/signal_generation_trade_management.py</code> | |||
'''Signal Generation Flow:''' | |||
<pre> | |||
+------------------+ | |||
| Setup Quality | | |||
| Grade >= B | | |||
+--------+---------+ | |||
| | |||
v | |||
+------------------+ | |||
| Direction Check | | |||
| MTF Aligned? | | |||
+--------+---------+ | |||
| | |||
+--------------+--------------+ | |||
| | | |||
v v | |||
+--------+--------+ +--------+--------+ | |||
| FILTERS | | GENERATE | | |||
| Hour filter | | Entry price | | |||
| Prob zone | | Stop loss | | |||
| MA direction | | Take profit | | |||
+--------+--------+ | Position size | | |||
| +-----------------+ | |||
v | |||
+------------------+ | |||
| BLOCKED or | | |||
| PASSED | | |||
+------------------+ | |||
</pre> | |||
'''Entry Techniques (17 Types):''' | |||
<pre> | |||
1. near_ma - Entry near 21 MA | |||
2. ma_bounce - Bounce off 21 MA | |||
3. break_of_structure (BOS) - Breakout entry | |||
4. pullback_entry - Trend pullback | |||
5. key_level_entry - At support/resistance | |||
... (12 more specialized techniques) | |||
</pre> | |||
'''Stop Loss Calculation:''' | |||
<pre> | |||
LONG Stop = Entry Price - MAX(recent_low - buffer, min_stop_distance) | |||
SHORT Stop = Entry Price + MAX(recent_high + buffer, min_stop_distance) | |||
Where: | |||
- min_stop_distance = 40 points (prevents too-tight stops) | |||
- buffer = 5 points for BOS entries | |||
- recent lookback = 5-10 bars depending on technique | |||
</pre> | |||
'''Take Profit Methods:''' | |||
<pre> | |||
1. Fixed R:R - TP = Entry + (Stop_Distance * Risk_Reward_Ratio) | |||
2. Fixed Points - TP = Entry +/- default_profit_points | |||
3. ATR Multiple - TP = Entry +/- (ATR * atr_multiple) | |||
</pre> | |||
'''Active Filters:''' | |||
{| class="wikitable" | |||
|- | |||
! Filter !! Purpose !! Impact | |||
|- | |||
| Hour Filter || Block toxic hours (9, 22, 23) || Saves Rs 357k+ | |||
|- | |||
| MA Direction || Trade only with MA21 slope || Improves trend alignment | |||
|- | |||
| Probability Zone || Block counter-trend in extremes || Reduces false signals | |||
|} | |||
'''Output:''' <code>Signal</code> | |||
* <code>signal_id</code>: Unique identifier | |||
* <code>direction</code>: LONG / SHORT | |||
* <code>entry_price</code>: Precise entry level | |||
* <code>stop_loss_price</code>: Risk cutoff | |||
* <code>take_profit_price</code>: Target level | |||
* <code>position_size</code>: Lots to trade | |||
* <code>setup_quality</code>: Grade | |||
* <code>estimated_costs</code>: Brokerage + taxes | |||
---- | |||
=== Layer 5: Trade Execution Engine === | |||
'''Purpose:''' Execute signals, manage open positions, calculate P&L | |||
'''File:''' <code>src/components/trade_execution_engine.py</code> | |||
'''Trade Lifecycle:''' | |||
<pre> | |||
SIGNAL RECEIVED | |||
| | |||
v | |||
+-----+-----+ | |||
| Validate | | |||
| Signal | | |||
+-----+-----+ | |||
| | |||
v | |||
+-----+-----+ +-----------+ | |||
| Check |----->| REJECT | | |||
| Filters | NO | Signal | | |||
+-----+-----+ +-----------+ | |||
| YES | |||
v | |||
+-----+-----+ | |||
| OPEN | | |||
| Position | | |||
+-----+-----+ | |||
| | |||
v | |||
+-----+-----+ | |||
| Monitor |<----+ | |||
| Each Bar | | | |||
+-----+-----+ | | |||
| | | |||
v | | |||
+-----+-----+ | | |||
| Check | | | |||
| Exit | | | |||
| Conditions|-----+ | |||
+-----+-----+ NO HIT | |||
| HIT | |||
v | |||
+-----+-----+ | |||
| CLOSE | | |||
| Trade | | |||
+-----+-----+ | |||
| | |||
v | |||
+-----+-----+ | |||
| Calculate | | |||
| P&L | | |||
+-----+-----+ | |||
</pre> | |||
'''Exit Conditions:''' | |||
<pre> | |||
1. STOP HIT - Price touches stop_loss_price | |||
2. TARGET HIT - Price touches take_profit_price | |||
3. TIMEOUT - Max holding period reached | |||
4. EOD - End of day force close | |||
</pre> | |||
'''P&L Calculation:''' | |||
<pre> | |||
For LONG: | |||
Gross P&L = (Exit_Price - Entry_Price) * Position_Size * Lot_Multiplier | |||
For SHORT: | |||
Gross P&L = (Entry_Price - Exit_Price) * Position_Size * Lot_Multiplier | |||
Net P&L = Gross P&L - Commission - Taxes | |||
Where: | |||
Commission = Position_Size * Rs 20 per leg * 2 (entry + exit) | |||
Taxes (CTT) = Contract_Value * 0.01% (sell side) | |||
Lot_Multiplier = 100 (MCX Crude Oil) | |||
</pre> | |||
---- | |||
== Data Flow Diagram == | |||
<pre> | |||
RAW 1-MIN DATA | |||
| | |||
v | |||
+--------------------+ | |||
| Timeframe | | |||
| Conversion | | |||
| (1m->5m,15m,1h,4h,1d) | |||
+--------------------+ | |||
| | |||
v | |||
+------------------+ +------------------+ +------------------+ | |||
| 5-Min Candles | | 15-Min Candles | | Higher TFs | | |||
| with MA21, MA200 | | with MAs | | (1H, 4H, Daily) | | |||
+--------+---------+ +--------+---------+ +--------+---------+ | |||
| | | | |||
+----------------------+----------------------+ | |||
| | |||
v | |||
+--------------------+ | |||
| Bar-by-Bar | | |||
| Processing Loop | | |||
+--------------------+ | |||
| | |||
+---------------------+---------------------+ | |||
| | | | |||
v v v | |||
+--------+--------+ +--------+--------+ +--------+--------+ | |||
| Trend Analysis | | MTF Analysis | | Market State | | |||
| (5M focus) | | (All TFs) | | Analysis | | |||
+-----------------+ +-----------------+ +-----------------+ | |||
| | | | |||
+---------------------+---------------------+ | |||
| | |||
v | |||
+--------------------+ | |||
| Setup Quality | | |||
| Detection | | |||
| (5-Factor Score) | | |||
+--------------------+ | |||
| | |||
v | |||
+--------------------+ | |||
| Signal Generation | | |||
| (Entry/Stop/TP) | | |||
+--------------------+ | |||
| | |||
v | |||
+--------------------+ | |||
| Trade Execution | | |||
| Engine | | |||
+--------------------+ | |||
| | |||
v | |||
+--------------------+ | |||
| Trade Record | | |||
| (CSV + JSON) | | |||
+--------------------+ | |||
</pre> | |||
---- | |||
== Key Decision Points == | |||
=== When to Generate Signal === | |||
<pre> | |||
+------------------------------------------------------------------+ | |||
| SIGNAL GENERATION DECISION TREE | | |||
+------------------------------------------------------------------+ | |||
START | |||
| | |||
v | |||
[MTF Alignment Score >= 0.6?] --NO--> NO SIGNAL | |||
| | |||
YES | |||
v | |||
[Setup Quality Grade >= B?] --NO--> NO SIGNAL | |||
| | |||
YES | |||
v | |||
[Current Hour in Blocked Hours?] --YES--> BLOCKED (NO SIGNAL) | |||
| | |||
NO | |||
v | |||
[MA Direction Matches Trade Direction?] --NO--> BLOCKED | |||
| | |||
YES | |||
v | |||
[In Probability Zone Against Trade?] --YES--> BLOCKED | |||
| | |||
NO | |||
v | |||
[Position Already Open?] --YES--> NO NEW SIGNAL | |||
| | |||
NO | |||
v | |||
+-------------------+ | |||
| GENERATE SIGNAL! | | |||
+-------------------+ | |||
</pre> | |||
=== Trade Direction Logic === | |||
<pre> | |||
LONG CONDITIONS (all must be true): | |||
- Daily trend = UP or NEUTRAL | |||
- 4H trend = UP | |||
- 1H trend = UP | |||
- MA21 slope > 0 (rising) | |||
- Price above MA21 or bouncing from it | |||
- Not in upper probability zone (overbought) | |||
SHORT CONDITIONS (all must be true): | |||
- Daily trend = DOWN or NEUTRAL | |||
- 4H trend = DOWN | |||
- 1H trend = DOWN | |||
- MA21 slope < 0 (falling) | |||
- Price below MA21 or rejected from it | |||
- Not in lower probability zone (oversold) | |||
</pre> | |||
---- | |||
== Configuration Reference == | |||
=== Strategy Configuration === | |||
<pre> | |||
StrategyConfig: | |||
primary_timeframe: 5M | |||
ma21_period: 21 | |||
ma200_period: 200 | |||
min_bars_for_analysis: 21 | |||
max_position_size: 10 lots | |||
max_concurrent_trades: 3 | |||
default_risk_percent: 1.0% | |||
base_slippage_points: 2.0 | |||
</pre> | |||
=== Signal Generator Configuration === | |||
<pre> | |||
SignalGeneratorConfig: | |||
commission_per_lot: Rs 20.00 | |||
transaction_tax_rate: 0.005% per leg | |||
lot_size_multiplier: 100 (MCX) | |||
min_stop_distance: 40 points | |||
default_risk_reward: 2.0 | |||
# Filters | |||
enable_hour_filter: true | |||
blocked_hours: [9, 22, 23] | |||
enable_ma_direction_filter: true | |||
enable_probability_zone_filter: true | |||
</pre> | |||
---- | |||
== Performance Analysis Framework (ISOLATION) == | |||
=== Edge Discovery Process === | |||
<pre> | |||
STEP 1: BASELINE | |||
- Run full backtest | |||
- Calculate: Trades, Win Rate, P&L, Expectancy | |||
STEP 2: SLICE BY DIMENSIONS | |||
Dimension 1: Market State (range_bound, creeper_move, etc.) | |||
Dimension 2: Setup Grade (A+, A, B, C, D) | |||
Dimension 3: Hour of Day (9-23) | |||
Dimension 4: Month | |||
Dimension 5: Direction (Long/Short) | |||
STEP 3: IDENTIFY EDGES | |||
Per slice calculate: | |||
- Trade count | |||
- Win rate | |||
- Net P&L | |||
- Expectancy = (WR% * Avg Win) + ((1-WR%) * Avg Loss) | |||
- Profit Factor = Gross Profit / Gross Loss | |||
STEP 4: GATE 1 CRITERIA | |||
- Win Rate > 30% | |||
- Expectancy > 0 | |||
- Sample Size >= 30 trades | |||
STEP 5: FILTER/FOCUS | |||
- Remove toxic slices | |||
- Trade only edge slices | |||
</pre> | |||
=== Latest Analysis Results === | |||
'''EDGE Combinations (Profitable):''' | |||
{| class="wikitable" | |||
|- | |||
! Combination !! Trades !! Win% !! Net P&L !! Expectancy | |||
|- | |||
| range_bound + H11 || 100 || 82.0% || Rs +358,640 || Rs +3,586/trade | |||
|- | |||
| creeper_move + H19 || 42 || 78.6% || Rs +123,870 || Rs +2,949/trade | |||
|- | |||
| creeper_move + H21 || 36 || 77.8% || Rs +105,293 || Rs +2,925/trade | |||
|- | |||
| creeper_move + H17 || 30 || 86.7% || Rs +37,426 || Rs +1,248/trade | |||
|} | |||
'''TOXIC Combinations (Loss-Making):''' | |||
{| class="wikitable" | |||
|- | |||
! Combination !! Trades !! Win% !! Net P&L !! Expectancy | |||
|- | |||
| narrow_low_volume + H14 || 38 || 7.9% || Rs -157,167 || Rs -4,136/trade | |||
|- | |||
| creeper_move + H9 || 33 || 21.2% || Rs -107,488 || Rs -3,257/trade | |||
|- | |||
| range_bound + H9 || 110 || 45.5% || Rs -109,227 || Rs -993/trade | |||
|} | |||
---- | |||
== File Structure == | |||
<pre> | |||
services/backtest/ | |||
| | |||
+-- src/ | |||
| +-- core/ | |||
| | +-- pipeline_engine.py # Main orchestrator | |||
| | +-- data_structures.py # Enums, dataclasses | |||
| | +-- base_component.py # Component base classes | |||
| | +-- timeframe_conversion.py # 1min -> all TFs | |||
| | | |||
| +-- components/ | |||
| | +-- trend_analysis_core.py # Layer 1 | |||
| | +-- multi_timeframe_analysis.py # Layer 1a | |||
| | +-- market_state_analysis.py # Layer 2 | |||
| | +-- setup_quality_detection.py # Layer 3 | |||
| | +-- signal_generation_trade_management.py # Layer 4 | |||
| | +-- trade_execution_engine.py # Layer 5 | |||
| | +-- probability_zone_analysis.py # Support component | |||
| | | |||
| +-- main.py # Entry point | |||
| | |||
+-- data/ | |||
| +-- input/ | |||
| | +-- Crude/ | |||
| | +-- 1min/crude_1m.csv # Raw data | |||
| | +-- 5min/crude_5m.csv # Converted | |||
| | +-- ... (other TFs) | |||
| | | |||
| +-- output/ | |||
| +-- trade_level_data_for_frontend.csv | |||
| +-- trade_level_data_for_frontend_summary.json | |||
| | |||
+-- docs/ | |||
+-- STRATEGY_SYSTEM_ARCHITECTURE.mediawiki # This file | |||
</pre> | |||
---- | |||
== Glossary == | |||
{| class="wikitable" | |||
|- | |||
! Term !! Definition | |||
|- | |||
| MTF || Multi-Timeframe - analyzing multiple chart timeframes simultaneously | |||
|- | |- | ||
| MA21 || 21-period Moving Average - primary trend indicator | |||
|- | |- | ||
| | | MA200 || 200-period Moving Average - long-term trend context | ||
|- | |- | ||
| | | Setup Grade || A+ to F quality score for trade setups | ||
|- | |- | ||
| | | Expectancy || Average profit/loss per trade (Rs/trade) | ||
|- | |- | ||
| | | Profit Factor || Gross Profits / Gross Losses ratio | ||
|- | |- | ||
| | | BOS || Break of Structure - price breaking previous swing high/low | ||
|- | |- | ||
| | | CTT || Commodities Transaction Tax (India) | ||
|- | |- | ||
| | | MCX || Multi Commodity Exchange (India) | ||
|- | |- | ||
| | | R:R || Risk to Reward Ratio | ||
|- | |- | ||
| | | Lot Size || 100 barrels for MCX Crude Oil futures | ||
|} | |} | ||
---- | |||
== Version History == | |||
{| class="wikitable" | |||
|- | |||
! Version !! Date !! Changes | |||
|- | |||
| 2.0 || 2026-01-12 || ISOLATION analysis integration, filter documentation | |||
|- | |||
| 1.5 || 2026-01-10 || Added probability zone filtering, hour filters | |||
|- | |||
| 1.0 || 2025-12-01 || Initial 5-layer architecture documentation | |||
|} | |||
[[Category:Trading Systems]] | |||
[[Category:Backtesting]] | |||
[[Category:Technical Documentation]] | |||
Latest revision as of 19:19, 11 January 2026
Multi-Timeframe Trading Strategy System
[edit]Version: 2.0 | Last Updated: 2026-01-12 | Status: Production
Executive Summary
[edit]This document describes a systematic, rule-based crude oil futures trading strategy implemented as a multi-component backtesting system. The strategy uses multi-timeframe alignment (5M to Daily), market state analysis, setup quality grading, and institutional-grade signal generation to identify high-probability trade setups.
| Metric | Value | Notes |
|---|---|---|
| Total Trades | 1,829 | 7-month period (Jun 2025 - Dec 2025) |
| Win Rate | 55.1% | Above random chance |
| Avg Holding Period | 2.8 hours | Intraday focus |
| Primary Direction | 85% Short | Trend-following bias |
| Exit Types | Stop: 80%, Target: 17%, Timeout: 4% | Stop-based risk management |
System Architecture Overview
[edit] +------------------------------------------+
| DATA LAYER |
| +---------+ +---------+ +---------+ |
| | 1-Min | | 5-Min | | 15-Min | |
| | OHLCV | | OHLCV | | OHLCV | |
| +---------+ +---------+ +---------+ |
| +---------+ +---------+ +---------+ |
| | 1-Hour | | 4-Hour | | Daily | |
| | OHLCV | | OHLCV | | OHLCV | |
| +---------+ +---------+ +---------+ |
+---------------------|--------------------+
|
v
+-------------------------------------------------------------------------------------------+
| PIPELINE ENGINE (Orchestrator) |
| |
| +---------------+ +---------------+ +---------------+ +---------------+ |
| | LAYER 1 | | LAYER 2 | | LAYER 3 | | LAYER 4 | |
| | Trend |--->| Market State |--->| Setup Quality |--->| Signal | |
| | Analysis | | Analysis | | Detection | | Generation | |
| +---------------+ +---------------+ +---------------+ +---------------+ |
| | | | | |
| v v v v |
| [MA21, MA200] [range_bound] [A+/A/B/C/D/F] [Entry/Stop/TP] |
| [Trend Direction] [creeper_move] [Score 0-100] [Direction] |
| [Trend Phase] [narrow_volume] [Risk %] [Position Size] |
| |
| | |
| v |
| +-------------------+ |
| | LAYER 5 | |
| | Trade Execution | |
| | Engine | |
| +-------------------+ |
| | |
| v |
| [Open/Manage/Close Trades] |
| [P&L Calculation] |
| [Cost Accounting] |
+-------------------------------------------------------------------------------------------+
|
v
+------------------------------------------+
| OUTPUT LAYER |
| +------------------+ +---------------+ |
| | Trade-Level CSV | | Summary JSON | |
| | (All trades) | | (Metrics) | |
| +------------------+ +---------------+ |
+------------------------------------------+
Component Details
[edit]Layer 1: Multi-Timeframe Trend Analysis
[edit]Purpose: Analyze trend direction and strength across 5 timeframes
File: src/components/multi_timeframe_analysis.py, src/components/trend_analysis_core.py
Timeframes Analyzed:
| Timeframe | Weight | Purpose |
|---|---|---|
| Daily (1D) | 30% | Context (overall trend) |
| 4-Hour (4H) | 25% | Primary trend |
| 1-Hour (1H) | 20% | Confirmation |
| 15-Min (15M) | 15% | Fine-tuning |
| 5-Min (5M) | 10% | Entry timing |
Key Calculations:
Alignment Score = SUM(Weight[tf] * Direction_Match[tf]) for all tf Where: - Direction_Match = 1 if tf direction matches dominant direction, else 0 - Dominant direction = direction with highest weighted votes MA Analysis per Timeframe: - MA21 (fast) - Short-term trend - MA200 (slow) - Long-term trend - Price position relative to MAs - MA slope (trending vs flat)
Output: TimeframeAnalysisResult
final_direction: LONG / SHORT / NEUTRALalignment_score: 0.0 - 1.0timeframe_results: Per-timeframe analysis dictionary
Layer 2: Market State Analysis
[edit]Purpose: Classify current market conditions into actionable states
File: src/components/market_state_analysis.py
Market States:
+-------------------+--------------------------------+------------------+ | Market State | Characteristics | Trading Action | +-------------------+--------------------------------+------------------+ | range_bound | Price oscillating, no clear | Trade reversals | | | trend, MA21 relatively flat | at range edges | +-------------------+--------------------------------+------------------+ | creeper_move | Slow, grinding trend with | Trade WITH trend | | | small candles, steady MA21 | on pullbacks | +-------------------+--------------------------------+------------------+ | narrow_low_volume | Tight range, reduced volume, | CAUTION - await | | | consolidation pattern | breakout | +-------------------+--------------------------------+------------------+ | trending | Strong directional move, | Trade WITH trend | | | clear MA separation | aggressively | +-------------------+--------------------------------+------------------+
Detection Algorithm:
1. Calculate recent volatility (ATR or range) 2. Calculate MA21 slope 3. Calculate volume relative to average 4. Apply classification rules: IF slope < threshold AND range tight THEN narrow_low_volume ELIF slope small AND trend present THEN creeper_move ELIF volatility high AND no trend THEN range_bound ELIF strong directional move THEN trending
Output: MarketStateResult
market_state: Enum valuevolatility_metrics: ATR, range datatrend_phase: early/middle/late/exhaustion
Layer 3: Setup Quality Detection
[edit]Purpose: Score and grade trade setups using 5-factor weighted system
File: src/components/setup_quality_detection.py
5-Factor Scoring System:
+-------------------------+--------+------------------------------------------+
| Factor | Weight | Description |
+-------------------------+--------+------------------------------------------+
| Timeframe Alignment | 30% | How many timeframes agree on direction |
| Trend Strength | 20% | MA slope, price momentum |
| Entry Quality | 15% | Clean candle, near MA, not extended |
| Key Level Proximity | 20% | Near support/resistance levels |
| Risk/Reward Ratio | 15% | Potential reward vs risk |
+-------------------------+--------+------------------------------------------+
= 100%
Grade Classification:
Score >= 90 --> A+ Grade (Best setups, full position) Score >= 80 --> A Grade (Excellent, 80% position) Score >= 70 --> B Grade (Good, 60% position) Score >= 60 --> C Grade (Average, 40% position) Score >= 50 --> D Grade (Below average, 20% position) Score < 50 --> F Grade (Poor, NO TRADE)
Penalty System:
Penalties Applied: - Creeper Move detected: -50 points - MA Struggle (price fighting MA): -30 points - Missing Two-Day Trend: -30 points - Phase Mismatch: -25 points - Far from Key Level: -50 points - Far from MA: -40 points Bonuses Applied: + Railroad Trend (strong alignment): +15 points + At Key Level: +10 points + Clean Entry Candle: +10 points
Institutional Fight Detection:
IF 4H direction != Daily direction THEN
Apply 0.7x multiplier to final score
(Institutions may be fighting retail)
Output: SetupQualityResult
grade: A+ / A / B / C / D / Fscore: 0 - 100factor_scores: Individual factor breakdownposition_size: Recommended lotsrisk_percent: Account risk percentagecan_auto_trade: Boolean
Layer 4: Signal Generation & Trade Management
[edit]Purpose: Generate precise entry/exit signals with risk parameters
File: src/components/signal_generation_trade_management.py
Signal Generation Flow:
+------------------+
| Setup Quality |
| Grade >= B |
+--------+---------+
|
v
+------------------+
| Direction Check |
| MTF Aligned? |
+--------+---------+
|
+--------------+--------------+
| |
v v
+--------+--------+ +--------+--------+
| FILTERS | | GENERATE |
| Hour filter | | Entry price |
| Prob zone | | Stop loss |
| MA direction | | Take profit |
+--------+--------+ | Position size |
| +-----------------+
v
+------------------+
| BLOCKED or |
| PASSED |
+------------------+
Entry Techniques (17 Types):
1. near_ma - Entry near 21 MA 2. ma_bounce - Bounce off 21 MA 3. break_of_structure (BOS) - Breakout entry 4. pullback_entry - Trend pullback 5. key_level_entry - At support/resistance ... (12 more specialized techniques)
Stop Loss Calculation:
LONG Stop = Entry Price - MAX(recent_low - buffer, min_stop_distance) SHORT Stop = Entry Price + MAX(recent_high + buffer, min_stop_distance) Where: - min_stop_distance = 40 points (prevents too-tight stops) - buffer = 5 points for BOS entries - recent lookback = 5-10 bars depending on technique
Take Profit Methods:
1. Fixed R:R - TP = Entry + (Stop_Distance * Risk_Reward_Ratio) 2. Fixed Points - TP = Entry +/- default_profit_points 3. ATR Multiple - TP = Entry +/- (ATR * atr_multiple)
Active Filters:
| Filter | Purpose | Impact |
|---|---|---|
| Hour Filter | Block toxic hours (9, 22, 23) | Saves Rs 357k+ |
| MA Direction | Trade only with MA21 slope | Improves trend alignment |
| Probability Zone | Block counter-trend in extremes | Reduces false signals |
Output: Signal
signal_id: Unique identifierdirection: LONG / SHORTentry_price: Precise entry levelstop_loss_price: Risk cutofftake_profit_price: Target levelposition_size: Lots to tradesetup_quality: Gradeestimated_costs: Brokerage + taxes
Layer 5: Trade Execution Engine
[edit]Purpose: Execute signals, manage open positions, calculate P&L
File: src/components/trade_execution_engine.py
Trade Lifecycle:
SIGNAL RECEIVED
|
v
+-----+-----+
| Validate |
| Signal |
+-----+-----+
|
v
+-----+-----+ +-----------+
| Check |----->| REJECT |
| Filters | NO | Signal |
+-----+-----+ +-----------+
| YES
v
+-----+-----+
| OPEN |
| Position |
+-----+-----+
|
v
+-----+-----+
| Monitor |<----+
| Each Bar | |
+-----+-----+ |
| |
v |
+-----+-----+ |
| Check | |
| Exit | |
| Conditions|-----+
+-----+-----+ NO HIT
| HIT
v
+-----+-----+
| CLOSE |
| Trade |
+-----+-----+
|
v
+-----+-----+
| Calculate |
| P&L |
+-----+-----+
Exit Conditions:
1. STOP HIT - Price touches stop_loss_price 2. TARGET HIT - Price touches take_profit_price 3. TIMEOUT - Max holding period reached 4. EOD - End of day force close
P&L Calculation:
For LONG: Gross P&L = (Exit_Price - Entry_Price) * Position_Size * Lot_Multiplier For SHORT: Gross P&L = (Entry_Price - Exit_Price) * Position_Size * Lot_Multiplier Net P&L = Gross P&L - Commission - Taxes Where: Commission = Position_Size * Rs 20 per leg * 2 (entry + exit) Taxes (CTT) = Contract_Value * 0.01% (sell side) Lot_Multiplier = 100 (MCX Crude Oil)
Data Flow Diagram
[edit] RAW 1-MIN DATA
|
v
+--------------------+
| Timeframe |
| Conversion |
| (1m->5m,15m,1h,4h,1d)
+--------------------+
|
v
+------------------+ +------------------+ +------------------+
| 5-Min Candles | | 15-Min Candles | | Higher TFs |
| with MA21, MA200 | | with MAs | | (1H, 4H, Daily) |
+--------+---------+ +--------+---------+ +--------+---------+
| | |
+----------------------+----------------------+
|
v
+--------------------+
| Bar-by-Bar |
| Processing Loop |
+--------------------+
|
+---------------------+---------------------+
| | |
v v v
+--------+--------+ +--------+--------+ +--------+--------+
| Trend Analysis | | MTF Analysis | | Market State |
| (5M focus) | | (All TFs) | | Analysis |
+-----------------+ +-----------------+ +-----------------+
| | |
+---------------------+---------------------+
|
v
+--------------------+
| Setup Quality |
| Detection |
| (5-Factor Score) |
+--------------------+
|
v
+--------------------+
| Signal Generation |
| (Entry/Stop/TP) |
+--------------------+
|
v
+--------------------+
| Trade Execution |
| Engine |
+--------------------+
|
v
+--------------------+
| Trade Record |
| (CSV + JSON) |
+--------------------+
Key Decision Points
[edit]When to Generate Signal
[edit]+------------------------------------------------------------------+ | SIGNAL GENERATION DECISION TREE | +------------------------------------------------------------------+ START | v [MTF Alignment Score >= 0.6?] --NO--> NO SIGNAL | YES v [Setup Quality Grade >= B?] --NO--> NO SIGNAL | YES v [Current Hour in Blocked Hours?] --YES--> BLOCKED (NO SIGNAL) | NO v [MA Direction Matches Trade Direction?] --NO--> BLOCKED | YES v [In Probability Zone Against Trade?] --YES--> BLOCKED | NO v [Position Already Open?] --YES--> NO NEW SIGNAL | NO v +-------------------+ | GENERATE SIGNAL! | +-------------------+
Trade Direction Logic
[edit]LONG CONDITIONS (all must be true): - Daily trend = UP or NEUTRAL - 4H trend = UP - 1H trend = UP - MA21 slope > 0 (rising) - Price above MA21 or bouncing from it - Not in upper probability zone (overbought) SHORT CONDITIONS (all must be true): - Daily trend = DOWN or NEUTRAL - 4H trend = DOWN - 1H trend = DOWN - MA21 slope < 0 (falling) - Price below MA21 or rejected from it - Not in lower probability zone (oversold)
Configuration Reference
[edit]Strategy Configuration
[edit]StrategyConfig: primary_timeframe: 5M ma21_period: 21 ma200_period: 200 min_bars_for_analysis: 21 max_position_size: 10 lots max_concurrent_trades: 3 default_risk_percent: 1.0% base_slippage_points: 2.0
Signal Generator Configuration
[edit]SignalGeneratorConfig: commission_per_lot: Rs 20.00 transaction_tax_rate: 0.005% per leg lot_size_multiplier: 100 (MCX) min_stop_distance: 40 points default_risk_reward: 2.0 # Filters enable_hour_filter: true blocked_hours: [9, 22, 23] enable_ma_direction_filter: true enable_probability_zone_filter: true
Performance Analysis Framework (ISOLATION)
[edit]Edge Discovery Process
[edit]STEP 1: BASELINE - Run full backtest - Calculate: Trades, Win Rate, P&L, Expectancy STEP 2: SLICE BY DIMENSIONS Dimension 1: Market State (range_bound, creeper_move, etc.) Dimension 2: Setup Grade (A+, A, B, C, D) Dimension 3: Hour of Day (9-23) Dimension 4: Month Dimension 5: Direction (Long/Short) STEP 3: IDENTIFY EDGES Per slice calculate: - Trade count - Win rate - Net P&L - Expectancy = (WR% * Avg Win) + ((1-WR%) * Avg Loss) - Profit Factor = Gross Profit / Gross Loss STEP 4: GATE 1 CRITERIA - Win Rate > 30% - Expectancy > 0 - Sample Size >= 30 trades STEP 5: FILTER/FOCUS - Remove toxic slices - Trade only edge slices
Latest Analysis Results
[edit]EDGE Combinations (Profitable):
| Combination | Trades | Win% | Net P&L | Expectancy |
|---|---|---|---|---|
| range_bound + H11 | 100 | 82.0% | Rs +358,640 | Rs +3,586/trade |
| creeper_move + H19 | 42 | 78.6% | Rs +123,870 | Rs +2,949/trade |
| creeper_move + H21 | 36 | 77.8% | Rs +105,293 | Rs +2,925/trade |
| creeper_move + H17 | 30 | 86.7% | Rs +37,426 | Rs +1,248/trade |
TOXIC Combinations (Loss-Making):
| Combination | Trades | Win% | Net P&L | Expectancy |
|---|---|---|---|---|
| narrow_low_volume + H14 | 38 | 7.9% | Rs -157,167 | Rs -4,136/trade |
| creeper_move + H9 | 33 | 21.2% | Rs -107,488 | Rs -3,257/trade |
| range_bound + H9 | 110 | 45.5% | Rs -109,227 | Rs -993/trade |
File Structure
[edit]services/backtest/
|
+-- src/
| +-- core/
| | +-- pipeline_engine.py # Main orchestrator
| | +-- data_structures.py # Enums, dataclasses
| | +-- base_component.py # Component base classes
| | +-- timeframe_conversion.py # 1min -> all TFs
| |
| +-- components/
| | +-- trend_analysis_core.py # Layer 1
| | +-- multi_timeframe_analysis.py # Layer 1a
| | +-- market_state_analysis.py # Layer 2
| | +-- setup_quality_detection.py # Layer 3
| | +-- signal_generation_trade_management.py # Layer 4
| | +-- trade_execution_engine.py # Layer 5
| | +-- probability_zone_analysis.py # Support component
| |
| +-- main.py # Entry point
|
+-- data/
| +-- input/
| | +-- Crude/
| | +-- 1min/crude_1m.csv # Raw data
| | +-- 5min/crude_5m.csv # Converted
| | +-- ... (other TFs)
| |
| +-- output/
| +-- trade_level_data_for_frontend.csv
| +-- trade_level_data_for_frontend_summary.json
|
+-- docs/
+-- STRATEGY_SYSTEM_ARCHITECTURE.mediawiki # This file
Glossary
[edit]| Term | Definition |
|---|---|
| MTF | Multi-Timeframe - analyzing multiple chart timeframes simultaneously |
| MA21 | 21-period Moving Average - primary trend indicator |
| MA200 | 200-period Moving Average - long-term trend context |
| Setup Grade | A+ to F quality score for trade setups |
| Expectancy | Average profit/loss per trade (Rs/trade) |
| Profit Factor | Gross Profits / Gross Losses ratio |
| BOS | Break of Structure - price breaking previous swing high/low |
| CTT | Commodities Transaction Tax (India) |
| MCX | Multi Commodity Exchange (India) |
| R:R | Risk to Reward Ratio |
| Lot Size | 100 barrels for MCX Crude Oil futures |
Version History
[edit]| Version | Date | Changes |
|---|---|---|
| 2.0 | 2026-01-12 | ISOLATION analysis integration, filter documentation |
| 1.5 | 2026-01-10 | Added probability zone filtering, hour filters |
| 1.0 | 2025-12-01 | Initial 5-layer architecture documentation |