PROTECTED SOURCE SCRIPT

Advanced Market Structure Sniper -> PROFABIGHI_CAPITAL Strategy

18
🌟 Overview

The Advanced Market Structure Sniper → PROFABIGHI_CAPITAL Strategy is a precision market structure trading system that leverages Break of Structure (BOS) and Change of Character (CHoCH) detection for trend continuation and reversal signals, integrated with multi-mode EMA trend validation and interim swing-based risk placement. It offers directional trading flexibility, conservative or aggressive position management, dynamic stop-loss and take-profit levels, and comprehensive visual feedback including colored candles and performance metrics for optimized backtesting and live execution.

⚙️ Strategy Configuration

- Initial Capital: Starting account balance for simulation and performance calculation
- Slippage Modeling: Adjustable execution cost to reflect real-market friction
- Position Sizing: Equity percentage allocation per trade for consistent risk exposure
- Pyramiding Control: Disabled to limit directional exposure to single positions
- Order Execution: Processes trades on confirmed bar close to avoid repainting
- Margin Settings: Zero leverage for both long and short positions, focusing on cash-based trading
- Overlay Display: Renders all elements directly on the price chart for contextual analysis

📅 Date Range Settings

- Date Filter Activation: Toggle to limit backtesting to user-defined periods or enable full history
- Backtest Start Date: Customizable starting point for trade evaluation, ignoring prior data
- Range Validation: Ensures entries and exits only occur within the specified timeframe
- Historical Flexibility: Disable filter for comprehensive analysis across entire dataset

📊 PROFABIGHI_CAPITAL Metrics Display

Performance Visualization Options:
- Equity Curve: Plots account growth including unrealized positions for trend assessment
- Open Profit Tracking: Monitors current trade profitability in real-time
- Gross Profit Summary: Cumulative wins before deductions for raw performance view
- Net Profit Calculation: Final returns after all costs and losses
- Strategy Overview: Holistic equity path from initial capital
- Display None: Clean chart without performance overlays

Table Customization:
- Positioning Choices: Flexible placement across chart edges or centers for visibility
- Full Detail Mode: In-depth stats like win rate, Sharpe ratio, and maximum drawdown
- Simplified View: Core metrics only, such as total profit and trade count
- Hidden Option: Remove table entirely for focused price action review

🎯 Mode and Style Settings

- Directional Mode: Select long-only for bullish bias, short-only for bearish, or both for balanced approach
- Trade Style Selection: Conservative limits to one active position; aggressive allows concurrent trades
- Bias Alignment: Ensures signals match selected mode to filter irrelevant opportunities
- Position Overlap Control: Aggressive mode enables multi-trade scenarios while maintaining risk limits

📊 BOS/CHoCH Swing Detection

- Left Bar Confirmation: Adjustable lookback bars before pivot for robust high/low identification
- Right Bar Validation: Post-pivot bars required to confirm swing strength and reliability
- Body-Focused Pivots: Analyzes candle body extremes for cleaner structure over wick noise
- Fractal Formation: Detects new highs/lows to establish reference levels for breaks
- Crossover Logic: Triggers on price crossing prior swing levels to signal structure shifts

📊 Interim High/Low Swing Detection

- Dedicated Left Bars: Independent lookback for identifying recent swing extremes
- Dedicated Right Bars: Confirmation period tailored for interim pivot accuracy
- Opposing Candle Tracking: Monitors last bearish candle low for long stops, bullish high for short stops
- Pivot Fallback Integration: Uses interim pivots when available, defaults to recent candle bodies
- Reactive Reference: Provides tighter, more current levels for dynamic risk placement

👁️ Display Settings

- BOS/CHoCH Label Toggle: Show or hide text markers for structure break events
- Swing Line Visibility: Enable lines connecting pivot points for structural mapping
- Line Extension Duration: Configurable forward projection of swing levels for future reference
- Label Styling: Tiny, direction-colored text (green for bullish, red for bearish) with arrow styles
- Clean Visualization: Options to declutter chart by disabling non-essential elements

📈 EMA Trend Confirmation System

Mode Selection:
- Basis Mode: Unified short/long EMA pair for simple, consistent trend reading
- Advanced Mode: Separate EMA pairs optimized for long (bullish) and short (bearish) biases

Basis Parameters:
- Short EMA Length: Faster moving average for responsive trend signals
- Long EMA Length: Slower moving average for overall direction confirmation

Advanced Parameters:
- Long Trend Short EMA: Quick EMA for bullish trend detection
- Long Trend Long EMA: Supporting EMA for sustained uptrend validation
- Short Trend Short EMA: Responsive EMA for bearish momentum
- Short Trend Long EMA: Confirmatory EMA for downtrend persistence

Trend Validity:
- Uptrend Condition: Short EMA above long EMA in Basis; aligned pair in Advanced
- Downtrend Condition: Short EMA below long EMA in Basis; misaligned pair in Advanced
- Dynamic Plotting: Lines color-coded (green up, red down, gray invalid) with varying thickness

🎨 Color Customization

- EMA Trend Colors: Green for uptrends, red for downtrends in Basis mode
- Advanced EMA Colors: Green/gray for long pairs, red/gray for short pairs
- Entry Arrow Colors: Green up arrows for buys, red down for sells
- Exit Signal Colors: Dark blue for profitable closes, purple for loss exits
- Interim Line Color: Yellow for swing reference lines
- Risk Line Colors: Red for stops, green for take-profits

🛡️ Risk Management Framework

- Risk/Reward Ratio: Scalable profit target based on stop distance for asymmetric returns
- Stop Offset Percentage: Buffer added to interim levels to protect against whipsaws
- Long Stop Placement: Below last bearish candle low or interim swing low, with offset
- Short Stop Placement: Above last bullish candle high or interim swing high, with offset
- Target Derivation: Automatically calculates take-profit from entry and risk distance
- Buffer Safety: Offset ensures stops avoid tight structure for better execution

📊 Market Structure Tracking

- Structure State Variables: Tracks upper/lower swing values, locations, and cross status
- Direction Flag: Maintains bullish (1) or bearish (-1) bias based on breaks
- CHoCH Detection: Flags major reversals when breaking against prior trend
- BOS Confirmation: Validates continuations after initial CHoCH in same direction
- Cross Prevention: Boolean locks prevent duplicate signals on same level
- Fractal Updates: Dynamically refreshes swing references on new pivots

📈 Entry Signal Generation

Long Signal Requirements:
- CHoCH Confirmation: Initial bullish structure shift detected
- BOS Validation: Subsequent continuation break in uptrend
- EMA Alignment: Trend valid per selected mode (Basis or Advanced)
- Mode Permission: Long trades enabled in selected directional setting
- New Trade Allowance: No active long in conservative style
- Date Compliance: Within backtest range for execution

Short Signal Requirements:
- CHoCH Confirmation: Initial bearish structure shift detected
- BOS Validation: Subsequent continuation break in downtrend
- EMA Alignment: Trend valid per selected mode (Basis or Advanced)
- Mode Permission: Short trades enabled in selected directional setting
- New Trade Allowance: No active short in conservative style
- Date Compliance: Within backtest range for execution

Signal Filtering:
- Structure Sequence: Requires CHoCH first, then BOS for layered confirmation
- Trend Gate: EMA validity blocks counter-trend entries
- Position Lock: Conservative mode halts new signals until exit
- Visual Markers: Small triangle shapes below/above bars for immediate recognition

📤 Exit Management Logic

Stop Loss Triggers:
- Long Exit: Price reaches or breaches calculated stop below interim low
- Short Exit: Price reaches or breaches calculated stop above interim high
- Immediate Closure: Position closed on touch for strict risk adherence

Take Profit Triggers:
- Long Exit: Price hits target above entry by risk/reward multiple
- Short Exit: Price hits target below entry by risk/reward multiple
- Profit Locking: Secures gains at predefined level for disciplined trading

EMA Reversal Exits:
- Basis Mode: Short EMA crosses against long EMA direction
- Advanced Mode: Direction-specific pair misalignment triggers exit
- Profit/Loss Sorting: Classifies as profit if favorable to entry price, else loss
- Bar Confirmation: Exits processed on close to filter noise

Position Reset:
- State Clearing: Flags reset post-exit to allow new setups
- Line Deletion: Removes SL/TP visuals for chart clarity
- Condition Refresh: BOS/CHoCH trackers cleared for fresh analysis
- Allowance Unlock: Conservative mode re-enables signals after closure

🎨 Visualization Features

Entry and Exit Markers:
- Buy Arrows: Green triangles below bars for long signals
- Sell Arrows: Red triangles above bars for short signals
- Profit Exits: Dark blue triangles marking successful closes
- Loss Exits: Purple triangles indicating stopped trades

Structure and Swing Lines:
- BOS/CHoCH Lines: Horizontal extensions from break points in trend colors
- Interim Swing Lines: Yellow dashed lines for high/low references
- Risk Lines: Dashed red (stops) and green (targets) projecting forward
- Label Placement: Centered text between pivot and break for context

EMA Trend Lines:
- Basis Plots: Single pair with color shifts for unified trend view
- Advanced Plots: Four lines with direction-specific coloring and gray invalid states
- Line Weights: Thinner for shorts, thicker for longs to emphasize hierarchy

Candle Coloring System:
- Long Trade Candles: Full green fill, border, and wicks during active positions
- Short Trade Candles: Full red fill, border, and wicks during active positions
- Exit Bar Highlight: Maintains trade color on closure bars for lifecycle tracking
- Neutral Default: Transparent when no active trade for standard view

🔔 Alert System

- Entry Alerts: Notifications for buy/sell signals with ticker and timeframe
- Exit Alerts: Separate messages for profit/loss closes in each direction
- Structure Alerts: CHoCH and BOS detections for proactive monitoring
- Custom Messages: Include instrument and interval for quick context
- Real-Time Triggers: Fire on condition met for timely trade decisions

📈 Strategy Execution Framework

Entry Execution:
- Long Orders: strategy.entry() on confirmed buy signal within date range
- Short Orders: strategy.entry() on confirmed sell signal within date range
- Confirmation Gate: barstate.isconfirmed ensures no intrabar repaints
- Range Restriction: Ignores signals outside backtest period

Exit Execution:
- Position Closes: strategy.close() on any profit, loss, or EMA reversal
- Unified Handling: Single call manages full position exit
- Condition Priority: SL/TP checked first, then EMA for layered protection
- Post-Entry Management: Continues exits even if outside date range

Position State Management:
- Trade Flags: Boolean trackers for long/short activity and entry prices
- Conservative Lock: Disables new entries until current position resolves
- Aggressive Freedom: Permits overlapping trades without restrictions
- Direction Switch: New opposite entry closes prior position automatically
- Reset Mechanism: Clears all states on exit for clean restarts

🔍 Advanced Features

Structure Break Logic:
- Crossover Detection: ta.crossover/close for precise level breaches
- Label Differentiation: 'CHoCH' for reversals, 'BOS' for continuations
- Trend Flip Handling: os flag updates bias on confirmed shifts
- Line Drawing: Connects pivot to break bar for visual confirmation

Interim Level Dynamics:
- Candle Body Priority: Uses max/min open/close for interim references
- Continuous Update: Refreshes on every opposing candle or pivot
- Fallback Safety: Defaults to prior bar high/low if no recent level
- Offset Application: Percentage adjustment for volatility adaptation

EMA Mode Adaptability:
- Unified vs Specialized: Basis for simplicity, Advanced for nuanced biases
- Validity Gating: Blocks entries on invalid trends to reduce whipsaws
- Exit Sensitivity: Detects flips from prior to current bar for timely action
- Color Feedback: Gray lines signal non-valid states for quick assessment

Trade Lifecycle Integration:
- Entry Price Capture: Locks close price on signal for accurate calculations
- Line Management: Deletes prior visuals before new draws for non-clutter
- State Persistence: var declarations maintain values across bars
- Exit Classification: Distinguishes profit/loss for metrics accuracy

Performance Safeguards:
- Barstate Checks: Confirmed states prevent lookahead in tests
- Date Gating: Strict range enforcement for reproducible results
- No Repaint Design: All detections use historical pivots
- Alert Granularity: Direction-specific notifications for focused monitoring

✅ Key Takeaways

- Precision Structure Trading: BOS/CHoCH combo delivers high-confidence breakouts and reversals
- Flexible Directional Control: Long/short/both modes adapt to market bias or user preference
- Dual EMA Frameworks: Basis for ease, Advanced for tailored trend validation per direction
- Interim Swing Risk: Reactive stops using recent candles or pivots for tighter protection
- Scalable Risk/Reward: Custom RR ratios with offsets ensure favorable trade math
- Conservative/Aggressive Styles: Single vs multi-position management for risk tuning
- Visual Trade Lifecycle: Arrows, lines, colored candles, and labels track every step
- Layered Exits: SL/TP fixed levels plus EMA dynamic closes for complete coverage
- Backtest Optimization: Date filters, metrics tables, and confirmed signals for reliable testing
- Alert-Driven Monitoring: Comprehensive notifications for entries, exits, and structure events
- Body-Based Cleanliness: Ignores wicks for robust pivot detection in noisy markets
- Stateful Tracking: Variables maintain structure memory without overload
- No-Leverage Focus: Emphasizes capital preservation over amplified exposure

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.