Advanced Trading Pattern Recognition and Dynamic Risk Management Strategy

EMA ATR FIBONACCI ENGULFING volatility VOLUME RISK-REWARD
Created on: 2025-06-19 13:57:50 Modified on: 2025-06-19 13:57:50
Copy: 4 Number of hits: 287
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Advanced Trading Pattern Recognition and Dynamic Risk Management Strategy  Advanced Trading Pattern Recognition and Dynamic Risk Management Strategy

Strategy Overview

The Advanced Trading Pattern Recognition and Dynamic Risk Management Strategy is a quantitative trading approach that combines precise engulfing pattern recognition techniques with a dynamic risk management system. The core of this strategy lies in its ability to accurately identify engulfing patterns through advanced mathematical validation methods, while using the 50-period Exponential Moving Average (EMA) as a trend filter to ensure trade directions align with the dominant market trend. The strategy employs deep analysis of candlestick patterns, volume confirmation, and volatility filtering through multiple technical indicators to screen for high-probability trading signals, while applying Fibonacci-based dynamic stop losses and profit targets for intelligent risk management.

Strategy Principles

The operational principles of this strategy are based on the collaborative functioning of several key components:

  1. Trend Identification System: Uses a 50-period EMA as the primary trend indicator. Price above the EMA is identified as an uptrend, suitable for long positions; price below the EMA is identified as a downtrend, suitable for short positions. This ensures trades always follow the dominant market direction.

  2. Advanced Engulfing Pattern Recognition: The strategy detects enhanced engulfing patterns, requiring the current candle to completely โ€œengulfโ€ the previous candle, and verifies the pattern quality through mathematical validation. The system analyzes:

    • The ratio of the current candle body relative to the previous candle body (minimum engulfing ratio)
    • The proportion of upper and lower wicks to the candle body (maximum wick ratio)
    • The relationship between the current candleโ€™s overall size and the Average True Range (ATR)
  3. Multiple Filtering Mechanisms:

    • Volume filtering: Ensures volume exceeds a specific multiple of the average
    • Volatility filtering: Confirms market volatility meets appropriate trading conditions through ATR
    • Wick quality control: Limits the size of candle upper and lower wicks to improve signal quality
  4. Dynamic Risk Management:

    • Stop loss calculation: Supports multiple stop loss strategies based on Fibonacci levels, fixed amounts, or ATR multiples
    • Profit targets: Can set targets using either fixed risk-reward ratios or Fibonacci levels
    • Automatic calculation of trading fees, ensuring strategy viability in actual trading environments

Strategy Advantages

Through deep analysis of the code, this strategy demonstrates the following significant advantages:

  1. Precise Entry Timing: By combining trend, pattern, and multiple confirmation indicators, the strategy can identify high-quality entry points with statistical advantages in the market, avoiding false signals that might arise from single indicators.

  2. Adaptive Risk Management: Unlike traditional strategies with fixed parameters, this strategyโ€™s risk management system dynamically adjusts based on current market conditions, using Fibonacci levels or ATR values to calculate stop losses and profit targets, better adapting to different market environments.

  3. Comprehensive Visualization Support: The strategy provides comprehensive chart markers and information panels, including entry signals, stop loss/profit levels, current trend status, and real-time P&L tracking, helping traders intuitively understand market conditions and strategy performance.

  4. High Customizability: The strategy offers rich parameter settings, including EMA length, engulfing ratio, risk-reward ratio, etc., allowing traders to adjust strategy performance according to personal risk preferences and different market conditions.

  5. Integrated Trading Fee Consideration: The strategy incorporates trading commission calculations, an important factor often overlooked by many trading systems, ensuring backtesting results more closely resemble actual trading environments.

Strategy Risks

Despite its multiple advantages, the strategy still has the following potential risks and limitations:

  1. Market Environment Dependency: The strategy performs best in markets with clear trends, while it may generate more false signals in ranging or highly volatile directionless markets. The solution is to assess the market state in higher timeframes before using the strategy, or to add additional market structure filters.

  2. Parameter Optimization Pitfalls: Excessive parameter optimization may lead to curve fitting, resulting in poor performance in future market environments. It is recommended to use forward testing or robustness testing under different market conditions to validate parameter effectiveness.

  3. Stop Loss Breach Risk: Under extreme market volatility or insufficient liquidity conditions, actual stop losses may experience slippage, exceeding anticipated losses. This risk can be reduced by adding stop loss buffer zones or using more conservative position sizing.

  4. Technical Indicator Lag: EMAs and other technical indicators inherently have lag, which may result in insufficient response during rapid market turns. It is recommended to combine higher timeframe analysis or add early warning indicators to compensate for this deficiency.

  5. Volume Quality Issues: The strategy only considers volume size rather than volume structure and quality, which may be misleading under certain market conditions. Consider adding volume distribution analysis or money flow indicators to enhance the depth of volume analysis.

Strategy Optimization Directions

Based on code analysis, the strategy can be optimized in the following directions:

  1. Market State Adaptation:

    • Implement market structure recognition functionality, using different parameter sets for trending and ranging markets
    • Introduce market volatility index (VIX) or other market sentiment indicators to automatically adjust risk parameters during high volatility periods
    • Reason: This will enable the strategy to intelligently adapt to different market environments, improving overall stability
  2. Multi-Timeframe Analysis:

    • Add higher timeframe trend confirmation mechanisms
    • Use lower timeframes to optimize entry precision
    • Reason: Multi-timeframe analysis can significantly improve trend identification accuracy, reducing counter-trend trading
  3. Advanced Volume Analysis:

    • Introduce Volume Weighted Moving Average (VWMA) as additional trend confirmation
    • Analyze buying and selling pressure rather than just considering total volume
    • Reason: More refined volume analysis can provide deeper insights into market participant behavior
  4. Machine Learning Enhancement:

    • Use simple machine learning algorithms to automatically optimize parameters
    • Identify optimal engulfing pattern characteristics based on historical data
    • Reason: Machine learning can identify subtle patterns and associations difficult for humans to discover
  5. Risk Management Enhancement:

    • Implement dynamic position sizing based on account equity
    • Add daily/weekly/monthly risk limits
    • Introduce breakeven functionality
    • Reason: More advanced risk management is the foundation for long-term trading success

Summary

The Advanced Trading Pattern Recognition and Dynamic Risk Management Strategy is a carefully designed trading system that creates a comprehensive trading framework by integrating traditional engulfing pattern technical analysis with modern quantitative methods. The core advantage of this strategy lies in its multidimensional signal confirmation mechanism and adaptive risk management system, enabling it to maintain relatively stable performance under different market conditions.

The strategy significantly improves entry signal quality through multiple mechanisms such as 50EMA trend filtering, advanced engulfing pattern recognition, and volume and volatility confirmation. Meanwhile, dynamic stop losses and profit targets calculated through Fibonacci levels or ATR multiples provide a clear risk-reward structure for each trade.

Despite inherent limitations such as market environment dependency and technical indicator lag, through the suggested optimization directions like market state adaptation, multi-timeframe analysis, and machine learning enhancement, this strategy has the potential to further improve its robustness and adaptability. For experienced traders, this is a professional-grade trading system offering comprehensive functionality, while for beginners, it serves as an educational tool for learning advanced trading concepts and risk management principles.

Strategy source code
/*backtest
start: 2025-05-19 00:00:00
end: 2025-06-18 00:00:00
period: 3h
basePeriod: 3h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=6
strategy("๐ŸŽฏ IKODO Engulfing Strategy with Dynamic RR & Commission", shorttitle="IKODO Engulfing Pro", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10, pyramiding=0, calc_on_every_tick=false, calc_on_order_fills=false, commission_type=strategy.commission.percent, commission_value=0.04)

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿ“Š ADVANCED INPUT PARAMETERS
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Commission Settings
enable_commission = input.bool(true, "Enable Commission", group="๐Ÿ’ฐ Commission Settings")
commission_rate = input.float(0.04, "Commission Rate (%)", minval=0.0, maxval=1.0, step=0.01, group="๐Ÿ’ฐ Commission Settings", tooltip="Binance Futures: 0.02% Maker, 0.04% Taker")
commission_type_input = input.string("Percentage", "Commission Type", options=["Percentage", "Fixed USD"], group="๐Ÿ’ฐ Commission Settings")

// Risk Management Inputs
rr_ratio = input.float(2.0, "Risk Reward Ratio", minval=0.5, maxval=10.0, step=0.1, group="๐ŸŽฏ Risk Management")
use_fibonacci_tp = input.bool(true, "Use Fibonacci Levels for TP", group="๐ŸŽฏ Risk Management")
fib_level_tp = input.float(0.618, "Fibonacci Level for TP", minval=0.236, maxval=1.0, step=0.001, group="๐ŸŽฏ Risk Management")

// Stop Loss Settings
sl_type = input.string("Fibonacci", "Stop Loss Type", options=["Fibonacci", "Fixed USD", "ATR Multiple"], group="๐Ÿ›ก๏ธ Stop Loss Settings")
sl_fib_level = input.float(0.236, "Fibonacci Level for SL", minval=0.1, maxval=0.5, step=0.001, group="๐Ÿ›ก๏ธ Stop Loss Settings")
sl_fixed_usd = input.float(50.0, "Fixed Stop Loss (USD)", minval=1.0, maxval=1000.0, step=1.0, group="๐Ÿ›ก๏ธ Stop Loss Settings")
sl_atr_multiple = input.float(1.5, "ATR Multiple for SL", minval=0.5, maxval=5.0, step=0.1, group="๐Ÿ›ก๏ธ Stop Loss Settings")

// EMA Settings
ema_length = input.int(50, "EMA Length", minval=1, maxval=200, group="๐Ÿ“ˆ Trend Filter")
ema_source = input.source(close, "EMA Source", group="๐Ÿ“ˆ Trend Filter")

// Pattern Recognition Settings
min_engulf_ratio = input.float(0.1, "Minimum Engulfing Ratio", minval=0.01, maxval=1.0, step=0.01, group="๐Ÿ” Pattern Recognition")
max_wick_ratio = input.float(0.3, "Maximum Wick Ratio", minval=0.1, maxval=0.8, step=0.01, group="๐Ÿ” Pattern Recognition")

// Advanced Filters
volume_filter = input.bool(true, "Use Volume Filter", group="๐Ÿ”ง Advanced Filters")
volume_multiplier = input.float(1.2, "Volume Multiplier", minval=1.0, maxval=3.0, step=0.1, group="๐Ÿ”ง Advanced Filters")
atr_filter = input.bool(true, "Use ATR Volatility Filter", group="๐Ÿ”ง Advanced Filters")
atr_length = input.int(14, "ATR Length", minval=1, maxval=50, group="๐Ÿ”ง Advanced Filters")
min_atr_ratio = input.float(0.5, "Minimum ATR Ratio", minval=0.1, maxval=2.0, step=0.1, group="๐Ÿ”ง Advanced Filters")

// Visualization Settings
show_fibonacci_levels = input.bool(true, "Show Fibonacci Levels", group="๐ŸŽจ Visualization")

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿงฎ QUANTITATIVE CALCULATIONS
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// EMA Calculation
ema_50 = ta.ema(ema_source, ema_length)

// ATR for Volatility Assessment
atr = ta.atr(atr_length)

// Volume Analysis
avg_volume = ta.sma(volume, 20)
volume_condition = not volume_filter or volume > avg_volume * volume_multiplier

// Fibonacci calculation for swing levels
swing_high = ta.highest(high, 20)
swing_low = ta.lowest(low, 20)

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿ” ADVANCED PATTERN RECOGNITION
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Current and Previous Candle Properties
curr_body = math.abs(close - open)
prev_body = math.abs(close[1] - open[1])
curr_range = high - low
prev_range = high[1] - low[1]

// Candle Color Identification
curr_bullish = close > open
curr_bearish = close < open
prev_bullish = close[1] > open[1]
prev_bearish = close[1] < open[1]

// Enhanced Engulfing Pattern Detection
bullish_engulfing = curr_bullish and prev_bearish and close > high[1] and low < low[1] and curr_body > prev_body * min_engulf_ratio

bearish_engulfing = curr_bearish and prev_bullish and close < low[1] and high > high[1] and curr_body > prev_body * min_engulf_ratio

// Wick Analysis for Quality Filter
curr_upper_wick = curr_bullish ? high - close : high - open
curr_lower_wick = curr_bullish ? open - low : close - low
wick_filter_long = curr_upper_wick <= curr_range * max_wick_ratio
wick_filter_short = curr_lower_wick <= curr_range * max_wick_ratio

// ATR Volatility Filter
atr_filter_condition = not atr_filter or curr_range >= atr * min_atr_ratio

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿ“ˆ TREND ANALYSIS & ENTRY CONDITIONS
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Trend Conditions
uptrend = close > ema_50
downtrend = close < ema_50

// Complete Entry Conditions
long_condition = uptrend and bullish_engulfing and wick_filter_long and volume_condition and atr_filter_condition

short_condition = downtrend and bearish_engulfing and wick_filter_short and volume_condition and atr_filter_condition

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐ŸŽฏ ADVANCED STOP LOSS CALCULATION
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Function to calculate stop loss based on type
calculate_stop_loss(entry_price, is_long, sl_type, swing_high, swing_low, atr, sl_fib_level, sl_fixed_usd, sl_atr_multiple) =>
    var float stop_loss = na
    
    if sl_type == "Fibonacci"
        if is_long
            fib_range = swing_high - swing_low
            stop_loss := swing_low + (fib_range * sl_fib_level)
        else
            fib_range = swing_high - swing_low
            stop_loss := swing_high - (fib_range * sl_fib_level)
    
    else if sl_type == "Fixed USD"
        if is_long
            stop_loss := entry_price - sl_fixed_usd
        else
            stop_loss := entry_price + sl_fixed_usd
    
    else if sl_type == "ATR Multiple"
        if is_long
            stop_loss := entry_price - (atr * sl_atr_multiple)
        else
            stop_loss := entry_price + (atr * sl_atr_multiple)
    
    stop_loss

// Function to calculate take profit
calculate_take_profit(entry_price, stop_loss, is_long, use_fibonacci_tp, swing_high, swing_low, fib_level_tp, rr_ratio) =>
    var float take_profit = na
    
    if use_fibonacci_tp
        if is_long
            fib_range = swing_high - swing_low
            take_profit := swing_low + (fib_range * fib_level_tp)
        else
            fib_range = swing_high - swing_low
            take_profit := swing_high - (fib_range * fib_level_tp)
    else
        // Traditional RR-based TP
        if is_long
            risk = entry_price - stop_loss
            take_profit := entry_price + (risk * rr_ratio)
        else
            risk = stop_loss - entry_price
            take_profit := entry_price - (risk * rr_ratio)
    
    take_profit

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐ŸŽฏ DYNAMIC RISK MANAGEMENT SYSTEM
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Dynamic Stop Loss and Take Profit Calculation
var float entry_price = na
var float stop_loss = na
var float take_profit = na
var float commission_cost = na

if long_condition and strategy.position_size == 0
    entry_price := close
    stop_loss := calculate_stop_loss(entry_price, true, sl_type, swing_high, swing_low, atr, sl_fib_level, sl_fixed_usd, sl_atr_multiple)
    take_profit := calculate_take_profit(entry_price, stop_loss, true, use_fibonacci_tp, swing_high, swing_low, fib_level_tp, rr_ratio)
    
    // Calculate commission cost
    commission_cost := enable_commission and commission_type_input == "Fixed USD" ? sl_fixed_usd * 2 : 0

if short_condition and strategy.position_size == 0
    entry_price := close
    stop_loss := calculate_stop_loss(entry_price, false, sl_type, swing_high, swing_low, atr, sl_fib_level, sl_fixed_usd, sl_atr_multiple)
    take_profit := calculate_take_profit(entry_price, stop_loss, false, use_fibonacci_tp, swing_high, swing_low, fib_level_tp, rr_ratio)
    
    // Calculate commission cost
    commission_cost := enable_commission and commission_type_input == "Fixed USD" ? sl_fixed_usd * 2 : 0

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿš€ STRATEGY EXECUTION WITH COMMISSION
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Entry Orders
if long_condition
    strategy.entry("Long", strategy.long, comment="๐ŸŸข Elite Long Entry")

if short_condition
    strategy.entry("Short", strategy.short, comment="๐Ÿ”ด Elite Short Entry")

// Exit Orders
if strategy.position_size > 0
    strategy.exit("Long Exit", "Long", stop=stop_loss, limit=take_profit, comment="๐ŸŽฏ Long Exit")

if strategy.position_size < 0
    strategy.exit("Short Exit", "Short", stop=stop_loss, limit=take_profit, comment="๐ŸŽฏ Short Exit")

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿ“Š ADVANCED VISUALIZATION - GLOBAL SCOPE
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// EMA Plot
plot(ema_50, "EMA 50", color=color.new(color.blue, 0), linewidth=2)

// Entry Signals
plotshape(long_condition, "Long Signal", shape.triangleup, location.belowbar, color.new(color.green, 0), size=size.normal)
plotshape(short_condition, "Short Signal", shape.triangledown, location.abovebar, color.new(color.red, 0), size=size.normal)

// Support/Resistance Levels
plot(strategy.position_size != 0 ? stop_loss : na, "Stop Loss", color.new(color.red, 0), linewidth=2, style=plot.style_linebr)
plot(strategy.position_size != 0 ? take_profit : na, "Take Profit", color.new(color.green, 0), linewidth=2, style=plot.style_linebr)

// Entry Price Line
plot(strategy.position_size != 0 ? entry_price : na, "Entry Price", color.new(color.yellow, 0), linewidth=1, style=plot.style_linebr)

// Fibonacci Levels Visualization - MOVED TO GLOBAL SCOPE
show_fib_condition = show_fibonacci_levels and (sl_type == "Fibonacci" or use_fibonacci_tp)
plot(show_fib_condition ? swing_high : na, "Swing High", color.new(color.gray, 50), linewidth=1, style=plot.style_circles)
plot(show_fib_condition ? swing_low : na, "Swing Low", color.new(color.gray, 50), linewidth=1, style=plot.style_circles)

// Additional Fibonacci Levels
fib_range = swing_high - swing_low
fib_236 = swing_low + (fib_range * 0.236)
fib_382 = swing_low + (fib_range * 0.382)
fib_618 = swing_low + (fib_range * 0.618)
fib_786 = swing_low + (fib_range * 0.786)

plot(show_fib_condition ? fib_236 : na, "Fib 23.6%", color.new(color.orange, 70), linewidth=1, style=plot.style_linebr)
plot(show_fib_condition ? fib_382 : na, "Fib 38.2%", color.new(color.orange, 70), linewidth=1, style=plot.style_linebr)
plot(show_fib_condition ? fib_618 : na, "Fib 61.8%", color.new(color.orange, 70), linewidth=1, style=plot.style_linebr)
plot(show_fib_condition ? fib_786 : na, "Fib 78.6%", color.new(color.orange, 70), linewidth=1, style=plot.style_linebr)

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿ“ˆ ENHANCED PERFORMANCE METRICS DISPLAY
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Enhanced Information Table
var table info_table = table.new(position.top_right, 3, 12, bgcolor=color.new(color.white, 85), border_width=1)

if barstate.islast
    table.cell(info_table, 0, 0, "๐Ÿ“Š ELITE STRATEGY PRO", text_color=color.black, text_size=size.small)
    
    // Risk Management Info
    table.cell(info_table, 0, 1, "Risk-Reward Ratio:", text_color=color.black, text_size=size.tiny)
    table.cell(info_table, 1, 1, str.tostring(rr_ratio, "#.##"), text_color=color.blue, text_size=size.tiny)
    
    // Commission Info
    table.cell(info_table, 0, 2, "Commission:", text_color=color.black, text_size=size.tiny)
    commission_text = enable_commission ? (commission_type_input == "Percentage" ? str.tostring(commission_rate, "#.##") + "%" : "$" + str.tostring(sl_fixed_usd, "#.##")) : "Disabled"
    table.cell(info_table, 1, 2, commission_text, text_color=enable_commission ? color.red : color.gray, text_size=size.tiny)
    
    // Stop Loss Type
    table.cell(info_table, 0, 3, "Stop Loss Type:", text_color=color.black, text_size=size.tiny)
    table.cell(info_table, 1, 3, sl_type, text_color=color.purple, text_size=size.tiny)
    
    // EMA Period
    table.cell(info_table, 0, 4, "EMA Period:", text_color=color.black, text_size=size.tiny)
    table.cell(info_table, 1, 4, str.tostring(ema_length), text_color=color.blue, text_size=size.tiny)
    
    // Current Trend
    table.cell(info_table, 0, 5, "Current Trend:", text_color=color.black, text_size=size.tiny)
    trend_text = uptrend ? "๐ŸŸข BULLISH" : downtrend ? "๐Ÿ”ด BEARISH" : "โšช NEUTRAL"
    trend_color = uptrend ? color.green : downtrend ? color.red : color.gray
    table.cell(info_table, 1, 5, trend_text, text_color=trend_color, text_size=size.tiny)
    
    // ATR
    table.cell(info_table, 0, 6, "ATR:", text_color=color.black, text_size=size.tiny)
    table.cell(info_table, 1, 6, str.tostring(atr, "#.####"), text_color=color.blue, text_size=size.tiny)
    
    // Fibonacci Range
    table.cell(info_table, 0, 7, "Fib Range:", text_color=color.black, text_size=size.tiny)
    table.cell(info_table, 1, 7, str.tostring(fib_range, "#.####"), text_color=color.orange, text_size=size.tiny)
    
    // Current Position Info
    if strategy.position_size != 0
        current_pnl = strategy.position_size > 0 ? (close - entry_price) / entry_price * 100 : (entry_price - close) / entry_price * 100
        table.cell(info_table, 0, 8, "Current P&L:", text_color=color.black, text_size=size.tiny)
        pnl_color = current_pnl > 0 ? color.green : color.red
        table.cell(info_table, 1, 8, str.tostring(current_pnl, "#.##") + "%", text_color=pnl_color, text_size=size.tiny)
        
        // Risk Amount
        risk_amount = strategy.position_size > 0 ? entry_price - stop_loss : stop_loss - entry_price
        table.cell(info_table, 0, 9, "Risk per Share:", text_color=color.black, text_size=size.tiny)
        table.cell(info_table, 1, 9, str.tostring(risk_amount, "#.####"), text_color=color.orange, text_size=size.tiny)
        
        // Reward Amount
        reward_amount = strategy.position_size > 0 ? take_profit - entry_price : entry_price - take_profit
        table.cell(info_table, 0, 10, "Reward per Share:", text_color=color.black, text_size=size.tiny)
        table.cell(info_table, 1, 10, str.tostring(reward_amount, "#.####"), text_color=color.green, text_size=size.tiny)

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// ๐Ÿ”” ENHANCED ALERT CONDITIONS
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// Alert conditions
alertcondition(long_condition, title="๐ŸŸข Elite Long Entry Pro", message="Elite Engulfing Strategy PRO: LONG signal detected with commission calculation.")

alertcondition(short_condition, title="๐Ÿ”ด Elite Short Entry Pro", message="Elite Engulfing Strategy PRO: SHORT signal detected with commission calculation.")

// Dynamic alerts with detailed information
if long_condition
    alert_msg = "๐ŸŸข LONG SIGNAL: Elite Engulfing Pro | Price: " + str.tostring(close, "#.####") + " | RR: " + str.tostring(rr_ratio, "#.##") + " | SL Type: " + sl_type + " | Commission: " + (enable_commission ? str.tostring(commission_rate, "#.##") + "%" : "Disabled")
    alert(alert_msg, alert.freq_once_per_bar)

if short_condition
    alert_msg = "๐Ÿ”ด SHORT SIGNAL: Elite Engulfing Pro | Price: " + str.tostring(close, "#.####") + " | RR: " + str.tostring(rr_ratio, "#.##") + " | SL Type: " + sl_type + " | Commission: " + (enable_commission ? str.tostring(commission_rate, "#.##") + "%" : "Disabled")
    alert(alert_msg, alert.freq_once_per_bar)