PROTECTED SOURCE SCRIPT

Trading/ Range Tracker Advanced -> PROFABIGHI_CAPITAL Strategy

43
🌟 Overview

The Trading/Range Tracker Advanced Strategy is a fully automated swing breakout trading system that combines impulsive candle filtering, multi-channel range/trend detection, and EMA confirmation for systematic trade execution. It features ATR-based market regime classification, separate swing detection for entries and risk placement, dual-mode EMA frameworks, and comprehensive performance metrics for backtesting optimization.

⚙️ Strategy Configuration

- Initial Capital: Starting equity for backtest simulation
- Slippage: Execution slippage modeling for realistic results
- Position Sizing: Percentage of equity allocated per trade
- Pyramiding Disabled: Prevents multiple entries in same direction
- Order Processing: Executes trades on bar close for confirmed signals
- Zero Margin: No leverage applied to long or short positions

📅 Date Range Settings

- Date Filter Toggle: Enable or disable backtesting time restrictions
- Start Date Selection: Specify beginning date for strategy evaluation
- Full Historical Option: Disable filter to test across entire chart history
- In-Range Condition: Ensures trades only execute within specified timeframe

📊 PROFABIGHI_CAPITAL Metrics Display

Performance Curve Options:
- Strategy Equity: Total account value including open positions
- Equity Only: Closed position equity excluding open trades
- Open Profit: Current unrealized profit or loss
- Gross Profit: Total winning trade value before costs
- Net Profit: Final profit after all costs and losses
- None: Hide performance curve display

Metrics Table Configuration:
- Table Position: Place metrics in any screen quadrant or center
- Full Table: Comprehensive statistics including win rate, drawdown, profit factor
- Simple Table: Essential metrics only for minimal display
- None: Hide table for clean chart visualization

⚙️ Mode and Style Settings

- Trading Mode Selection: Choose between long-only, short-only, or bidirectional trading
- Trade Style Configuration: Conservative mode (single position) or Aggressive mode (concurrent trades)
- Sniper Mode Toggle: Require impulsive candles for entries or allow relaxed breakout entries
- Execution Flexibility: Adapt strategy behavior to market conditions and risk appetite

📊 Swing Detection Settings

- Left Bar Lookback: Number of bars before pivot for swing high/low identification
- Right Bar Confirmation: Number of bars after pivot to validate swing structure
- Line Extension Length: Visual display duration for swing level reference lines
- Body-Based Pivots: Uses candle body extremes rather than wicks for cleaner structure

📊 Interim High/Low Detection

Separate SL/TP Calculation Framework:
- Independent Pivot Detection: Dedicated left and right bar parameters for stop loss reference
- Interim Left Bars: Lookback for identifying recent swing extremes
- Interim Right Bars: Confirmation period for interim pivot validation
- Last Candle Tracking: Continuously updates most recent opposing candle body levels
- Dual Reference System: Combines interim pivots with last opposing candle for tighter stops

Risk Placement Logic:
- Long trades use last negative bar low (red candle body low) or interim swing low
- Short trades use last positive bar high (green candle body high) or interim swing high
- Provides more reactive stop placement than main swing levels

📈 EMA Trend Confirmation System

Basis Mode:
- Single pair of short and long EMAs for unified trend determination
- Consistent trend reading across both long and short trade directions
- Simplified decision framework with one trend reference

Advanced Mode:
- Dedicated EMA pairs for long trend detection with separate parameters
- Independent EMA pairs for short trend detection with different periods
- Direction-specific validation for enhanced precision
- Greater flexibility in asymmetric market conditions

EMA Exit Trigger Options:
- Intrabar: Exit signal triggers in real-time during bar formation
- Closed Bar: Exit signal only confirmed at bar close for reduced false exits

⚡ Impulsive Candle Detection

Multi-Factor Validation:
- Size Multiplier: Candle range must exceed average true range by adjustable factor
- Volume Multiplier: Trading volume must exceed average volume by configurable threshold
- Body-to-Wick Ratio: Candle body must represent minimum percentage of total range
- Volume Check Toggle: Optional volume validation (disable for crypto tickers with unreliable volume)

Application in Strategy:
- Breakout Validation: Impulsive candles indicate strong momentum behind swing breaks
- Entry Window: Time-limited entry opportunity after impulsive breakout (adjustable bar count)
- Sniper Mode Filter: When enabled, entries only permitted on impulsive candle breakouts
- Visual Highlighting: Orange bar coloring for impulsive candles outside active trades

🎨 Color Customization

- EMA UpTrend Color: Green color for bullish EMA alignment in Basis mode
- EMA DownTrend Color: Red color for bearish EMA alignment in Basis mode
- Swing Line Color: Yellow for interim high/low reference lines
- Stop Loss Color: Red dashed lines showing risk levels
- Take Profit Color: Green dashed lines showing target levels
- Impulsive Candle Color: Orange bar highlighting when impulse detected

🛡️ Risk Management Framework

- Risk/Reward Ratio Configuration: Adjustable profit target multiplier (default 2.2:1)
- Stop Loss Offset Percentage: Buffer applied to interim swing levels for execution safety
- Long Stop Placement: Below last negative bar low or interim swing low with offset
- Short Stop Placement: Above last positive bar high or interim swing high with offset
- Dynamic Target Calculation: Take profit automatically derived from entry and stop distance
- Offset Protection: Prevents stops too close to structure for stop-hunting protection

📊 Detector Decision Filter

Market Condition Filtering:
- Range Mode: Strategy only executes in ranging market conditions
- Trending Mode: Strategy only executes in trending markets (up or down)
- Off Mode: No market condition filter applied (original behavior)

Conditional Execution:
- Swing high/low detection only active when condition matches
- Entry signals only generated when market regime matches selected filter
- Visual swing labels (SH/SL) only displayed during matching conditions

📈 Trend Range Identifier V2

ATR-Based Trend Detection:
- ATR Length: Period for Average True Range calculation in trend analysis
- ATR Multiplier Trend: Multiplier for trend continuation levels (tighter bands)
- ATR Multiplier Reverse: Multiplier for trend reversal levels (wider bands)
- Asymmetric Bands: Different multipliers create adaptive channel width based on trend direction

Range Detection Parameters:
- Range Length: Lookback period for range channel calculation
- Standard Deviation: Multiplier for channel band width
- Channel Type Selection: Choose between Keltner Channel, Bollinger Bands, or Donchian Channel

Supertrend Integration:
- Supertrend Length: Period for Supertrend indicator calculation
- Supertrend Multiplier: ATR multiplier for Supertrend bands
- Crossover Type Selection: Choose price crossover method (close, highlow, reversehighlow, supertrend)

Channel Display Options:
- Yes: Always show channel bands regardless of market condition
- No: Hide channel bands completely
- Range: Only display channel when market is in range condition

📊 Market Regime Classification

Three-State System:
- Trending Up: Price crosses above upper ATR band and maintains upward momentum
- Trending Down: Price crosses below lower ATR band and maintains downward pressure
- Range: Price oscillates between bands without breaking trend thresholds

Trend Logic Framework:
- Accumulative Trend Tracking: Counts consecutive bars in trend for strength measurement
- Line Compression Detection: Range condition identified when bands narrow over lookback period
- Directional Crossover: Trend initiated when price crosses adaptive ATR levels
- Supertrend Confirmation: Optional supertrend-based crossover validation

Visual Indicators:
- UpLine and DownLine: Color-coded step lines (green for uptrend, red for downtrend, purple for range)
- Channel Bands: Teal-colored upper and lower bands with semi-transparent fill
- Candle Coloring: Silver candles during range conditions when showRange enabled

🎯 Entry Signal Generation

Long Entry Requirements:
- Price breaks above last swing high
- Impulsive candle present (if Sniper Mode enabled)
- EMA trend bullish (short EMA above long EMA or long-specific EMAs aligned)
- Within entry window after breakout (adjustable bar count)
- Market condition matches Detector Decision filter
- Mode permits long trades
- Not already in long position (if Conservative mode)

Short Entry Requirements:
- Price breaks below last swing low
- Impulsive candle present (if Sniper Mode enabled)
- EMA trend bearish (short EMA below long EMA or short-specific EMAs aligned)
- Within entry window after breakout
- Market condition matches Detector Decision filter
- Mode permits short trades
- Not already in short position (if Conservative mode)

Breakout Memory System:
- Breakout Tracking: System remembers when swing levels are breached
- Bar Counting: Tracks bars elapsed since breakout for entry window validation
- Breakout Reset: New swing formation invalidates previous breakout signals
- Entry Window Expiration: Breakout must confirm with EMA within specified bar count

📤 Exit Management Logic

Stop Loss Exit:
- Long position: price touches or crosses below calculated stop level
- Short position: price touches or crosses above calculated stop level
- Strategy closes position immediately on stop hit

Take Profit Exit:
- Long position: price reaches calculated target based on risk/reward ratio
- Short position: price reaches calculated target below entry
- Strategy closes position immediately on target hit

EMA Reversal Exit:
- Basis Mode: Short EMA crosses below long EMA (long exit) or above (short exit)
- Advanced Mode: Direction-specific EMA pair crosses against trade direction
- Intrabar Trigger: Exit in real-time when EMA condition met (if selected)
- Closed Bar Trigger: Exit only after bar confirms (if selected)
- Profit/Loss Classification: Exit marked as profit if price favorable to entry, else loss

Position State Management:
- Trade flags reset after exit
- Conservative mode re-enables entries for both directions
- Breakout conditions cleared after exit
- Stop and target lines deleted from chart

🎨 Visualization Features

Entry and Exit Markers:
- Long Entry Arrows: Green triangles below bars
- Short Entry Arrows: Red triangles above bars
- Profit Exit Markers: Dark blue triangles showing successful exits
- Loss Exit Markers: Purple triangles showing stopped trades

Swing Structure Lines:
- Swing High Lines: Yellow dashed horizontal lines with "SH" labels
- Swing Low Lines: Yellow dashed horizontal lines with "SL" labels
- Stop Loss Lines: Red dashed lines extending forward from entry
- Take Profit Lines: Green dashed lines showing target levels

EMA Trend Lines:
- Basis Mode EMAs: Color-coded for trend (green bullish, red bearish)
- Advanced Mode EMAs: Separate long EMAs (green/gray) and short EMAs (red/gray)
- Dynamic Coloring: Gray when EMA pair not in alignment

Trend Range Visualization:
- UpLine/DownLine: Thick step lines showing ATR-based trend levels (green/red/purple)
- Channel Bands: Upper and lower range boundaries with teal fill
- Conditional Display: Channel only shown based on showChannel setting

Trade Candle Coloring:
- Active Long Position: Green candles during long trade
- Active Short Position: Red candles during short trade
- Range Condition: Silver candles when market in range mode
- Impulsive Highlight: Orange bar color when impulsive candle detected outside trades

📈 Strategy Execution Framework

Entry Execution:
- Long Entry: strategy.entry() called when long signal confirms on bar close
- Short Entry: strategy.entry() called when short signal confirms on bar close
- Date Range Validation: Only executes if within backtesting date range
- Bar Confirmation: Uses barstate.isconfirmed to avoid repainting

Exit Execution:
- Position Closure: strategy.close() called on profit, loss, or EMA reversal exits
- Immediate Execution: Exits processed on same bar as exit condition
- Date Range Check: Continues to manage positions even outside date range
- Bar Confirmation: Exits confirmed at bar close for consistency

Position Management:
- Conservative Mode: Blocks new entries until current position closed
- Aggressive Mode: Allows multiple concurrent positions (pyramiding disabled in settings)
- Direction Blocking: Long entry exits shorts, short entry exits longs
- Trade State Tracking: Boolean flags track active position status

🔔 Alert System

- Long entry alerts with ticker and timeframe
- Short entry alerts with ticker and timeframe
- Stop loss hit alerts (combined for both directions)
- Take profit hit alerts (combined for both directions)
- Long EMA exit alerts
- Short EMA exit alerts
- Impulsive candle detection alerts

🔍 Advanced Features[/b>

Dual Swing Detection:
- Primary Swing Detection: Identifies breakout levels for entry signals
- Interim Swing Detection: Separate parameters for tighter stop loss placement
- Independent Configuration: Each detection system uses own left/right bar settings
- Last Candle Fallback: Uses most recent opposing candle if interim pivot not found

Adaptive ATR Bands:
- Directional Multipliers: Different ATR multiples for continuation vs reversal
- Trend Strength Tracking: Accumulative counter measures bars in trend
- Line Compression Logic: Range detected when bands narrow over specified period
- Crossover Flexibility: Multiple price/indicator crossover methods available

Channel Type Variations:
- Keltner Channel: ATR-based bands for volatility-adjusted ranges
- Bollinger Bands: Standard deviation-based statistical boundaries
- Donchian Channel: High/low range extremes for breakout context
- Unified Interface: Same function handles all channel types

Supertrend Integration:
- Direction Variable: Supertrend state (1 or -1) influences trend calculations
- Optional Crossover: Can use supertrend rather than price for trend triggers
- Combined Logic: Supertrend works with ATR bands for robust regime detection

Performance Optimization:
- Process Orders on Close: Prevents lookahead bias in backtesting
- Confirmed Signals Only: Uses barstate.isconfirmed for all entries/exits
- Slippage Modeling: Includes realistic execution costs
- Zero Pyramiding: Prevents position size inflation

✅ Key Takeaways

- Fully Automated Strategy: Complete execution system with entries, stops, and targets
- Dual Swing Framework: Separate detection for breakouts and risk placement
- ATR-Based Regime Filter: Three-state market classification (trending up/down/range)
- Multi-Channel Options: Choose between Keltner, Bollinger, or Donchian for range detection
- Impulsive Candle Filtering: Optional Sniper Mode ensures entries on momentum candles
- Flexible EMA Framework: Basis mode simplicity or Advanced mode direction-specific optimization
- Adaptive Risk Placement: Uses interim swings and last opposing candles for tighter stops
- Entry Window Control: Time-limited opportunity after breakouts prevents late entries
- Market Condition Filtering: Trade only in preferred environments (range, trending, or both)
- Comprehensive Metrics: Built-in performance analysis with PROFABIGHI_CAPITAL library
- Conservative vs Aggressive: Position management adapts to risk preference
- Multi-Exit Logic: Combines fixed targets with dynamic EMA-based exits
- Backtesting Ready: Date range filtering and confirmed signals prevent repainting
- Visual Trade Tracking: Color-coded candles, lines, and markers show complete trade lifecycle

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.