Dynamic Time-Filtered Support-Resistance Trading System with Trailing Stop Loss

ATR EMA SMA TP SL TF
Created on: 2025-08-21 09:20:08 Modified on: 2025-08-21 09:20:08
Copy: 1 Number of hits: 203
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Dynamic Time-Filtered Support-Resistance Trading System with Trailing Stop Loss  Dynamic Time-Filtered Support-Resistance Trading System with Trailing Stop Loss

Overview

The Dynamic Time-Filtered Support-Resistance Trading System with Trailing Stop Loss is an advanced algorithmic trading strategy that combines precise entry signals, intelligent time-based filtering, and adaptive risk management. Designed for traders seeking to identify high-probability trading opportunities within specific time windows, the system employs dynamic trailing stops and partial position management techniques to optimize trading performance. The core of the strategy lies in the dynamic identification of support and resistance levels, combined with time filtering and volume confirmation to provide precise trading signals.

Strategy Principles

The fundamental principles of this strategy are built on the synergistic operation of three core elements: precise entry, optimal timing, and state management.

Entry System: The strategy seeks reversal opportunities by dynamically identifying key price levels. It uses a configurable lookback period to calculate support and resistance zones and triggers entry signals when price interacts with these critical areas. Entry conditions include price interaction with support/resistance levels, volume confirmation, and optional trend filter confirmation. When price touches support and closes above the support buffer with above-average volume, the system generates a long signal. Similarly, when price touches resistance and closes below the resistance buffer with above-average volume, the system generates a short signal.

Time Filtering System: The strategy implements a comprehensive time filtering system allowing traders to define optimal trading periods. This includes: - 12-hour format trading window settings - Multi-timezone support (UTC, EST, PST, CST) - Day-of-week filtering (trade only weekdays, weekends, or both) - Automatic lunch hour avoidance (typically 12:00-13:00) - Visual time indicators (background coloring showing active/inactive trading periods)

Risk Management System: The strategy employs a three-tier risk management approach: 1. Multi-Level Take Profit System: Sets two profit targets (TP1 and TP2) with optional partial position closure at TP1 2. Dynamic Trailing Stop Technology: Offers three operating modes (Conservative, Balanced, Aggressive) that automatically adjust based on current market volatility 3. Intelligent Position Sizing: Allows traders to configure entry quantities and partial close quantities with clear position tracking and P&L monitoring

Strategy Advantages

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

  1. Comprehensive Entry Signals: Combines price action, volume confirmation, and trend alignment to enhance the reliability of trading signals. The system looks for high-probability reversal points near key support and resistance levels, reducing the risk of false breakouts.

  2. Flexible Time Filtering System: Allows traders to focus on optimal trading periods while avoiding low-liquidity or high-volatility market environments. This helps improve trading efficiency and reduces the likelihood of trading during unfavorable market conditions. Supports multi-timezone trading and customizable trading hour settings, making it suitable for traders worldwide.

  3. Advanced Risk Management Features: Dynamic trailing stop system adjusts automatically with market volatility, helping to protect profits and let winning positions run. Multiple take-profit targets and partial closing options allow for profit locking at different price levels.

  4. Comprehensive Visual Feedback: The system provides detailed chart elements and a real-time dashboard to help traders visually understand market conditions and strategy performance. Entry zone highlighting, dynamic risk/reward lines, and trailing stop visualization make the trading decision process more transparent.

  5. High Customizability: From core strategy parameters to time filtering controls and risk management options, the strategy offers extensive customization capabilities to adapt to different trading styles and market conditions.

Strategy Risks

Despite its many advantages, the strategy also presents several potential risks:

  1. Parameter Optimization Risk: The strategy relies on multiple parameter settings, such as lookback period, ATR multipliers, and trend filter settings. These parameters need to be carefully optimized and periodically adjusted to adapt to different market environments. Over-optimization of parameters may lead to overfitting and poor performance in future market conditions.

  2. Market Condition Sensitivity: In highly volatile or low-liquidity markets, support and resistance levels may not be as reliable as expected. During extreme market conditions, prices may rapidly break through key levels, causing stop losses to be triggered.

  3. Time Filtering Limitations: While time filtering can help avoid unfavorable trading periods, it may also cause the strategy to miss some high-quality trading opportunities. Markets don’t always follow predetermined time patterns, especially during significant events or breaking news.

  4. Trailing Stop Traps: In choppy markets, dynamic trailing stops may trigger prematurely, ending potentially profitable trades early. Different trailing stop settings (Conservative, Balanced, Aggressive) perform differently in various market environments.

  5. Signal Conflicts: Mixed signals may occur when price approaches multiple support and resistance levels or when time filtering conflicts with entry signals. This may require additional judgment or more complex decision rules.

Strategy Optimization Directions

Based on the code analysis, here are potential optimization directions:

  1. Adaptive Parameter Adjustment: Implement a mechanism to automatically adjust key parameters, such as lookback period and ATR multipliers, based on recent market volatility and trading performance. This can help the strategy better adapt to different market environments without manual intervention.

  2. Enhanced Market Structure Analysis: Integrate more sophisticated price structure recognition methods, such as identifying higher-level support and resistance areas, recognizing trend channels, or price patterns. This can improve the quality and reliability of entry signals.

  3. Optimize Time Filtering Logic: Use data analysis to identify optimal trading times for specific markets and automatically adjust trading time windows based on historical performance. Consider incorporating filtering for seasonal patterns and market-specific events like economic data releases.

  4. Improved Risk Management Mechanisms: Design a smarter position sizing system that dynamically adjusts position size based on historical volatility, current market conditions, and strategy performance. Implement a tiered scaling-out strategy for profitable trades based on profit percentage.

  5. Integration of Machine Learning Models: Use machine learning algorithms to predict the reliability of support and resistance levels or estimate the probability of success for entry signals under specific market conditions. This can help filter out potentially low-quality trading signals.

Summary

The Dynamic Time-Filtered Support-Resistance Trading System with Trailing Stop Loss is a comprehensive trading strategy that combines precise entry signals, intelligent time filtering, and adaptive risk management. It works by seeking high-probability reversal opportunities at key support and resistance levels while using time filtering and volume confirmation to enhance trade quality.

The strategy’s main strengths lie in its comprehensive time filtering system, dynamic trailing stop technology, and highly visual user interface. These features together create a powerful and flexible trading tool suitable for various market conditions and trading styles.

However, to fully leverage the potential of this strategy, traders need to carefully optimize parameters, understand its performance characteristics in different market environments, and potentially customize it for specific markets and personal trading goals. By implementing the suggested optimization measures, the strategy’s performance and robustness can be further enhanced, providing traders with a more reliable tool for market analysis and trade execution.

Strategy source code
/*backtest
start: 2025-08-13 00:00:00
end: 2025-08-20 00:00:00
period: 10m
basePeriod: 10m
exchanges: [{"eid":"Futures_OKX","currency":"ETH_USDT","balance":5000}]
*/

//@version=5
strategy("FlowStateTrader", overlay=true)

// Input Parameters
lookbackPeriod = input.int(20, "Lookback Period for Key Levels", minval=5, maxval=100)
atrPeriod = input.int(14, "ATR Period", minval=5, maxval=50)
atrMultiplierSL = input.float(1.5, "SL ATR Multiplier", minval=0.5, maxval=5.0, step=0.1)
atrMultiplierTP1 = input.float(1.5, "TP1 ATR Multiplier", minval=0.5, maxval=5.0, step=0.1)
atrMultiplierTP2 = input.float(2.0, "TP2 ATR Multiplier", minval=0.5, maxval=5.0, step=0.1)
rewardToRisk = input.float(2.0, "Reward to Risk Ratio", minval=1.0, maxval=5.0, step=0.1)

// Trend Filter Settings
enableTrendFilter = input.bool(true, "Enable Trend Filter")
trendMAPeriod = input.int(20, "Trend MA Period", minval=5, maxval=200)
trendMAType = input.string("EMA", "Trend MA Type", options=["EMA", "SMA"])

// TIME FILTER SETTINGS
enableTimeFilter = input.bool(false, "Enable Time-Based Filter", tooltip="Filter trades based on specific time windows")

// 12-hour format time inputs
startHour12 = input.int(9, "Start Hour (1-12)", minval=1, maxval=12, tooltip="Trading start hour in 12-hour format")
startAMPM = input.string("AM", "Start AM/PM", options=["AM", "PM"])
endHour12 = input.int(4, "End Hour (1-12)", minval=1, maxval=12, tooltip="Trading end hour in 12-hour format") 
endAMPM = input.string("PM", "End AM/PM", options=["AM", "PM"])

// Timezone selection
timeZone = input.string("UTC", "Time Zone", options=["UTC", "EST", "PST", "CST"], tooltip="Time zone for trading hours")

// Additional controls
avoidLunchHour = input.bool(true, "Avoid Lunch Hour (12:00-1:00 PM)", tooltip="Skip trading during typical lunch break")
weekendsOnly = input.bool(false, "Weekends Only", tooltip="Only trade on weekends")
weekdaysOnly = input.bool(false, "Weekdays Only", tooltip="Only trade on weekdays")

// Strategy Settings
entryQty = input.int(10, "Entry Quantity (Contracts)", minval=1, maxval=1000)
enablePartialClose = input.bool(true, "Enable Partial Close at TP1")
partialCloseQty = input.int(1, "Contracts to Close at TP1", minval=1, maxval=100)
enableAlerts = input.bool(true, "Enable Strategy Alerts")

// Dashboard Settings
dashboardSize = input.string("Medium", "Dashboard Size", options=["Small", "Medium", "Large"], tooltip="Control the size of the information dashboard")
enableScorecard = input.bool(true, "Enable Performance Scorecard", tooltip="Show performance metrics in lower right corner")

// Trailing Stop Settings
enableTrailingStop = input.bool(true, "Enable Trailing Stop")
trailMode = input.string("Balanced", "Trailing Stop Mode", options=["Conservative", "Balanced", "Aggressive"], tooltip="Conservative: Protect more profit | Balanced: Good middle ground | Aggressive: Let winners run longer")

// Set trailing parameters based on mode
trailActivationMultiplier = trailMode == "Conservative" ? 0.8 : trailMode == "Balanced" ? 1.0 : 1.2
trailDistanceMultiplier = trailMode == "Conservative" ? 0.6 : trailMode == "Balanced" ? 0.8 : 1.0

// TIME FILTER FUNCTIONS
// Convert 12-hour format to 24-hour format
convertTo24Hour(hour12, ampm) =>
    var int hour24 = na
    if ampm == "AM"
        hour24 := hour12 == 12 ? 0 : hour12
    else // PM
        hour24 := hour12 == 12 ? 12 : hour12 + 12
    hour24

// Convert timezone to UTC offset
getUTCOffset(tz) =>
    var int offset = na
    if tz == "UTC"
        offset := 0
    else if tz == "EST"
        offset := -5  // EST is UTC-5
    else if tz == "CST" 
        offset := -6  // CST is UTC-6
    else if tz == "PST"
        offset := -8  // PST is UTC-8
    offset

getCurrentHour() =>
    hour(time, "UTC")

getCurrentDayOfWeek() =>
    dayofweek(time)

isWeekend() =>
    currentDay = getCurrentDayOfWeek()
    currentDay == dayofweek.saturday or currentDay == dayofweek.sunday

isWeekday() =>
    not isWeekend()

isInTradingWindow() =>
    if not enableTimeFilter
        true
    else
        // Convert 12-hour inputs to 24-hour UTC
        startHour24 = convertTo24Hour(startHour12, startAMPM)
        endHour24 = convertTo24Hour(endHour12, endAMPM)
        utcOffset = getUTCOffset(timeZone)
        
        // Convert local time to UTC
        startHourUTC = (startHour24 - utcOffset + 24) % 24
        endHourUTC = (endHour24 - utcOffset + 24) % 24
        
        currentHour = getCurrentHour()
        
        // Handle trading window logic
        var bool inWindow = false
        
        // Handle same-day window vs overnight window
        if startHourUTC <= endHourUTC
            // Same day window (e.g., 9 AM to 4 PM)
            inWindow := currentHour >= startHourUTC and currentHour <= endHourUTC
        else
            // Overnight window (e.g., 10 PM to 6 AM)
            inWindow := currentHour >= startHourUTC or currentHour <= endHourUTC
        
        // Apply day-of-week filters
        if weekendsOnly and not isWeekend()
            inWindow := false
        if weekdaysOnly and not isWeekday()
            inWindow := false
            
        // Apply lunch hour filter (12:00-1:00 PM in selected timezone)
        if avoidLunchHour and inWindow
            lunchStart24 = 12  // 12 PM
            lunchEnd24 = 13    // 1 PM
            lunchStartUTC = (lunchStart24 - utcOffset + 24) % 24
            lunchEndUTC = (lunchEnd24 - utcOffset + 24) % 24
            
            // Check if current hour falls in lunch period
            if lunchStartUTC <= lunchEndUTC
                // Normal case: lunch doesn't cross midnight
                if currentHour >= lunchStartUTC and currentHour < lunchEndUTC
                    inWindow := false
            else
                // Edge case: lunch period crosses midnight (shouldn't happen but safety check)
                if currentHour >= lunchStartUTC or currentHour < lunchEndUTC
                    inWindow := false
        
        inWindow

// Combined time filter
isGoodTradingTime() =>
    isInTradingWindow()

// ATR and Volume Calculation
atr = ta.atr(atrPeriod)
volumeSMA = ta.sma(volume, atrPeriod)

// Trend Filter
trendMA = enableTrendFilter ? (trendMAType == "EMA" ? ta.ema(close, trendMAPeriod) : ta.sma(close, trendMAPeriod)) : na
isBullishTrend = enableTrendFilter ? close > trendMA : true
isBearishTrend = enableTrendFilter ? close < trendMA : true

// Key Levels Identification (Support & Resistance Zones)
support = ta.lowest(low, lookbackPeriod)
resistance = ta.highest(high, lookbackPeriod)
supportBuffer = support - atr * 0.5
resistanceBuffer = resistance + atr * 0.5

// Define Entry Conditions (with time filter)
isBullishEntry = (close > supportBuffer) and (low <= support) and (volume > volumeSMA) and isBullishTrend and isGoodTradingTime()
isBearishEntry = (close < resistanceBuffer) and (high >= resistance) and (volume > volumeSMA) and isBearishTrend and isGoodTradingTime()

// Calculate Stop Loss and Take Profit Levels
bullishSL = support - atr * atrMultiplierSL
bullishTP1 = support + atr * rewardToRisk * atrMultiplierTP1
bullishTP2 = support + atr * rewardToRisk * atrMultiplierTP2

bearishSL = resistance + atr * atrMultiplierSL
bearishTP1 = resistance - atr * rewardToRisk * atrMultiplierTP1
bearishTP2 = resistance - atr * rewardToRisk * atrMultiplierTP2

// Strategy Position Management
var float longEntryPrice = na
var float shortEntryPrice = na
var bool tp1HitLong = false
var bool tp1HitShort = false

// Trailing Stop Variables
var float longTrailStop = na
var float shortTrailStop = na
var bool longTrailActive = false
var bool shortTrailActive = false

// Calculate position sizing
finalQty = entryQty

// Long Entry
if isBullishEntry and strategy.position_size == 0
    strategy.entry("Long", strategy.long, qty=finalQty)
    longEntryPrice := close
    tp1HitLong := false
    // Reset trailing stop variables
    longTrailStop := na
    longTrailActive := false
    if enableAlerts
        alert("Long Entry Signal at " + str.tostring(close) + " - Qty: " + str.tostring(finalQty), alert.freq_once_per_bar)

// Short Entry
if isBearishEntry and strategy.position_size == 0
    strategy.entry("Short", strategy.short, qty=finalQty)
    shortEntryPrice := close
    tp1HitShort := false
    // Reset trailing stop variables
    shortTrailStop := na
    shortTrailActive := false
    if enableAlerts
        alert("Short Entry Signal at " + str.tostring(close) + " - Qty: " + str.tostring(finalQty), alert.freq_once_per_bar)

// Long Position Management
if strategy.position_size > 0
    // Calculate current profit
    currentProfit = close - strategy.position_avg_price
    profitInATR = currentProfit / atr
    
    // Trailing Stop Logic
    if enableTrailingStop and profitInATR >= trailActivationMultiplier
        // Activate trailing stop
        if not longTrailActive
            longTrailActive := true
            longTrailStop := close - atr * trailDistanceMultiplier
        else
            // Update trailing stop (only move up, never down)
            newTrailStop = close - atr * trailDistanceMultiplier
            longTrailStop := math.max(longTrailStop, newTrailStop)
    
    // Determine which stop loss to use
    effectiveStopLoss = enableTrailingStop and longTrailActive ? longTrailStop : bullishSL
    
    // Stop Loss (either original or trailing)
    strategy.exit("Long SL", "Long", stop=effectiveStopLoss)
    
    // Take Profit 1 (Partial Close by Contracts)
    if enablePartialClose and not tp1HitLong and high >= bullishTP1 and strategy.position_size >= partialCloseQty
        strategy.close("Long", qty=partialCloseQty, comment="Long TP1", immediately=true)
        tp1HitLong := true
    
    // Take Profit 2 (Close Remaining Position) or Full Close if Partial is Disabled
    if (enablePartialClose and tp1HitLong and high >= bullishTP2) or (not enablePartialClose and high >= bullishTP1)
        strategy.close("Long", comment=enablePartialClose ? "Long TP2" : "Long TP1", immediately=true)

// Short Position Management
if strategy.position_size < 0
    // Calculate current profit (for shorts, profit when price goes down)
    currentProfit = strategy.position_avg_price - close
    profitInATR = currentProfit / atr
    
    // Trailing Stop Logic
    if enableTrailingStop and profitInATR >= trailActivationMultiplier
        // Activate trailing stop
        if not shortTrailActive
            shortTrailActive := true
            shortTrailStop := close + atr * trailDistanceMultiplier
        else
            // Update trailing stop (only move down, never up)
            newTrailStop = close + atr * trailDistanceMultiplier
            shortTrailStop := math.min(shortTrailStop, newTrailStop)
    
    // Determine which stop loss to use
    effectiveStopLoss = enableTrailingStop and shortTrailActive ? shortTrailStop : bearishSL
    
    // Stop Loss (either original or trailing)
    strategy.exit("Short SL", "Short", stop=effectiveStopLoss)
    
    // Take Profit 1 (Partial Close by Contracts)
    if enablePartialClose and not tp1HitShort and low <= bearishTP1 and math.abs(strategy.position_size) >= partialCloseQty
        strategy.close("Short", qty=partialCloseQty, comment="Short TP1", immediately=true)
        tp1HitShort := true
    
    // Take Profit 2 (Close Remaining Position) or Full Close if Partial is Disabled
    if (enablePartialClose and tp1HitShort and low <= bearishTP2) or (not enablePartialClose and low <= bearishTP1)
        strategy.close("Short", comment=enablePartialClose ? "Short TP2" : "Short TP1", immediately=true)

// Reset flags when position closes
if strategy.position_size == 0
    tp1HitLong := false
    tp1HitShort := false
    // Reset trailing stop variables
    longTrailStop := na
    shortTrailStop := na
    longTrailActive := false
    shortTrailActive := false

// Visualization - Entry Zones
var box bullishBox = na
var box bearishBox = na
var label bullishZoneLabel = na
var label bearishZoneLabel = na

// Bullish Entry Zone


// Bearish Entry Zone


// Visualization - Risk/Reward Lines for Active Positions
var line longTP1Line = na
var line longTP2Line = na
var line longSLLine = na
var line shortTP1Line = na
var line shortTP2Line = na
var line shortSLLine = na

// Labels for TP/SL Values


// Short Position Lines and Labels


// Support and Resistance Lines
plot(support, "Support", color=color.green, linewidth=1, style=plot.style_line)
plot(resistance, "Resistance", color=color.red, linewidth=1, style=plot.style_line)

// Plot Trend MA if enabled
plot(enableTrendFilter ? trendMA : na, "Trend MA", color=color.blue, linewidth=2)

// Plot Trailing Stops if active
plot(strategy.position_size > 0 and longTrailActive ? longTrailStop : na, "Long Trail Stop", color=color.orange, linewidth=2, style=plot.style_stepline)
plot(strategy.position_size < 0 and shortTrailActive ? shortTrailStop : na, "Short Trail Stop", color=color.orange, linewidth=2, style=plot.style_stepline)