동적 시간 필터링 지원 및 저항 추적 손절매 거래 시스템

ATR EMA SMA TP SL TF
생성 날짜: 2025-08-21 09:20:08 마지막으로 수정됨: 2025-08-21 09:20:08
복사: 1 클릭수: 203
avatar of ianzeng123 ianzeng123
2
집중하다
319
수행원

동적 시간 필터링 지원 및 저항 추적 손절매 거래 시스템 동적 시간 필터링 지원 및 저항 추적 손절매 거래 시스템

개요

다이내믹 타임 필터링 스포트 레지스포트 트래킹 스톱트레이딩 시스템은 정밀한 입시 신호, 지능형 시간 필터링 및 적응형 위험 관리를 결합한 고급 정량화 거래 전략이다. 이 시스템은 특정 시간 창 내에서 높은 확률의 거래 기회를 식별하려는 거래자를 위해 고안되었으며, 거래 성능을 최적화하기 위해 다이내믹 트래킹 스포트 및 부분 포지션 관리 기술을 사용합니다. 전략의 핵심은 지지 및 저항의 동적인 식별을 통해 거래 시간 필터링과 거래량 확인을 결합하여 정확한 거래 신호를 제공하는 것입니다.

전략 원칙

이 전략의 기본 원칙은 세 가지 핵심 요소의 조화 작용에 기반합니다: 정확한 입학, 최적의 시간 및 상태 관리.

입학 시스템: 전략은 역동적으로 중요한 가격 수준을 식별하여 역전 기회를 찾습니다. 그것은 지원과 저항을 계산하기 위해 구성 가능한 회귀 기간을 사용하며, 가격이 이러한 중요한 영역과 상호 작용할 때 진입 신호를 유발합니다. 진입 조건에는 가격과 지원 / 저항 수준과의 상호 작용, 거래량 확인 및 선택 가능한 트렌드 필터 확인이 포함됩니다. 가격이 지원 부위를 접촉하고 거래량이 평균보다 높을 때 거래량이 평균보다 높을 때, 시스템은 여러 신호를 생성합니다.

시간 필터링 시스템: 전략은 종합적인 시간 필터링 시스템을 구현하여 거래자가 최적의 거래 시간을 정의할 수 있습니다. 여기에는 다음이 포함됩니다:

  • 12 시간 포맷의 거래 시간 창 설정
  • 다중 시간대 지원 (UTC, EST, PST, CST)
  • 주일 필터 (일부일간 거래, 주말 거래 또는 둘 다)
  • 점심시간을 자동으로 피하는 것 (일반적으로 12시부터 13시까지)
  • 시각화 시간 표시기 ((그라운드 컬러로 활동/활동하지 않은 거래 시간을 표시)

위험 관리 시스템: 이 전략은 3단계 위험 관리 방식을 채택합니다.

  1. 다단계 차단 시스템: 두 개의 정지 목표 (TP1 및 TP2) 를 설정하고, TP1 부분에서 평점 지점을 선택할 수 있습니다.
  2. 동적 추적 중지 기술3가지의 운영 모드를 제공함: 보수적, 균형적, 급진적, 현재 시장의 변동성에 따라 자동으로 조정함
  3. 지능형 창고 관리: 거래자가 입점 수와 일부 평점 수를 구성할 수 있도록 하고, 포지션 상태와 적자를 명확하게 추적할 수 있다.

전략적 이점

코드의 심층적인 분석을 통해 이 전략은 다음과 같은 장점을 가지고 있습니다:

  1. 통합 입구 신호가격 행동, 거래량 확인 및 동향 일관성을 결합하여 거래 신호의 신뢰도를 높인다. 시스템은 중요한 지지점과 저항점 근처의 높은 확률의 역전점을 찾고, 가짜 돌파의 위험을 줄인다.

  2. 유연한 시간 필터링 시스템: 거래자가 최적의 거래 시간에 집중할 수 있도록 허용하고, 낮은 유동성 또는 높은 변동성 시장 환경을 피한다. 이것은 거래 효율을 높이고, 불리한 시장 조건에서 거래할 가능성을 줄이는 데 도움이 된다.

  3. 고급 위험 관리 기능: 동적 추적 스톱 손실 시스템은 시장의 변동에 따라 자동으로 조정하여 수익을 보호하고 수익성있는 위치를 계속 작동하도록 도와줍니다. 다단계 스톱 목표 및 일부 평점 옵션은 다른 가격 수준에서 수익을 고정 할 수 있습니다.

  4. 전체적인 시각적 피드백이 시스템은 상세한 차트 요소와 실시간 대지판을 제공하여 거래자가 시장 상태와 전략 성과를 직관적으로 이해할 수 있도록 도와줍니다. 입수 구역의 주요 표시, 동적 위험 / 수익 라인 및 추적 중지 손실 시각화는 거래 의사 결정 과정을 더 투명하게 만듭니다.

  5. 고도의 사용자 정의핵심 전략 변수에서 시간 필터 제어 및 위험 관리 옵션에 이르기까지, 전략은 다양한 거래 스타일과 시장 조건에 맞게 광범위한 사용자 정의 기능을 제공합니다.

전략적 위험

이 전략은 많은 장점이 있지만 몇 가지 잠재적인 위험도 있습니다.

  1. 매개변수 최적화 위험전략은 회귀 기간, ATR 곱하기, 트렌드 필터 설정과 같은 여러 파라미터 설정에 의존합니다. 이러한 파라미터는 다른 시장 환경에 적응하기 위해 신중하게 최적화되고 정기적으로 조정해야합니다. 파라미터의 과도한 최적화는 과다 적응으로 이어질 수 있으며 미래의 시장 조건에서 좋지 않은 성능을 발휘 할 수 있습니다.

  2. 시장 조건 민감성: 높은 변동성 또는 낮은 유동성 시장에서 지지 및 저항 수준은 예상보다 덜 신뢰할 수 있습니다. 극단적 인 시장 조건에서 가격이 신속하게 중요한 수준을 돌파하여 스톱 손실이 유발 될 수 있습니다.

  3. 시간 필터 제한시간 필터링은 불리한 거래 시간을 피하는 데 도움이 되지만, 일부 고품질 거래 기회를 놓치게 할 수도 있습니다. 시장은 항상 미리 정해진 시간 패턴을 따르지 않습니다. 특히 중요한 사건이나 급격한 뉴스 기간 동안.

  4. 정지 함정을 추적합니다.동적 추적 스톱은 불안정한 시장에서 조기 발동될 수 있으며, 이로 인해 수익성이 있는 거래가 조기 종료될 수 있습니다. 다양한 추적 스톱 설정 (보수적, 균형적, 급진적) 은 다른 시장 환경에서 다르게 작동합니다.

  5. 신호 충돌: 가격들이 여러 개의 지원 및 저항 수준에 접근하거나, 시간 필터링이 입시 신호와 충돌할 때, 혼합 신호가 발생할 수 있다. 이것은 추가적인 판단이나 더 복잡한 의사결정 규칙이 필요하다.

전략 최적화 방향

코드 분석을 바탕으로 다음과 같은 최적화 방향이 있습니다.

  1. 적응 변수 조정: 최근 시장의 변동성과 거래 성과에 따라 회귀 기간과 ATR 곱하기와 같은 중요한 매개 변수를 자동으로 조정하는 메커니즘을 구현하십시오. 이것은 수동 개입없이 다양한 시장 환경에 더 잘 적응하는 전략을 도울 수 있습니다.

  2. 시장 구조 분석 강화더 복잡한 가격 구조를 식별하는 방법을 통합합니다. 예를 들어, 더 높은 수준의 지원 및 저항 영역을 식별하고, 트렌드 채널 또는 가격 형태를 식별합니다. 이것은 입시 신호의 품질과 신뢰성을 향상시킬 수 있습니다.

  3. 시간 필터링 논리를 최적화: 데이터 분석을 통해 특정 시장의 최적의 거래 시간을 찾아내고, 역사적 성과에 따라 거래 시간 창을 자동으로 조정한다. 계절적 패턴과 시장 특정 이벤트 (경제 데이터 발표와 같은) 에 대한 통합 필터를 고려한다.

  4. 위험 관리 시스템을 개선합니다.: 더 지능적인 포지션 관리 시스템을 설계하여 역사적 변동성, 현재 시장 조건 및 전략 수행에 따라 포지션 크기를 동적으로 조정합니다. 수익성 거래에서 수익률에 기반한 계단 평형 포지션 전략을 추가하십시오.

  5. 통합 기계 학습 모델: 기계 학습 알고리즘을 사용하여 지지점과 저항점의 신뢰성을 예측하거나 특정 시장 조건에서 진입 신호의 성공 가능성을 추정합니다. 이는 잠재적인 저품질 거래 신호를 필터링하는 데 도움이 될 수 있습니다.

요약하다

동적 시간 필터링 지지부진 추적 스톱 손실 거래 시스템은 정확한 입시 신호, 지능적인 시간 필터링 및 자율적 위험 관리를 결합한 기능이 풍부한 거래 전략입니다. 그것은 중요한 지지부진과 저항 부위에서 높은 확률의 역전 기회를 찾아 시간 필터링과 거래량 확인을 사용하여 거래 품질을 향상시킵니다.

이 전략의 주요 장점은 종합적인 시간 필터링 시스템, 동적 추적 스톱 기술 및 고도로 시각화된 사용자 인터페이스에 있습니다. 이러한 기능은 함께 다양한 시장 조건과 거래 스타일에 적합한 강력하고 유연한 거래 도구를 만듭니다.

그러나, 이 전략의 잠재력을 최대한 발휘하기 위해, 거래자는 신중하게 매개 변수를 최적화해야 하며, 다른 시장 환경에서의 그 성능 특성을 이해해야 하며, 특정 시장과 개인 거래 목표에 따라 맞춤형 조정이 필요할 수 있다. 권장된 최적화 조치를 실행함으로써 전략의 성능과 거침이 더욱 강화될 수 있으며, 거래자에게 더 신뢰할 수 있는 시장 분석 및 거래 실행 도구를 제공할 수 있다.

전략 소스 코드
/*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)