다단계 목표 및 트레일링 스톱 로스 전략

HEIKIN ASHI HA TARGET ZONE Trailing Stop PYRAMIDING BREAK-EVEN risk management
생성 날짜: 2025-03-31 16:20:21 마지막으로 수정됨: 2025-03-31 16:20:21
복사: 1 클릭수: 309
avatar of ianzeng123 ianzeng123
2
집중하다
319
수행원

다단계 목표 및 트레일링 스톱 로스 전략 다단계 목표 및 트레일링 스톱 로스 전략

개요

다단계 목표 및 트레이드 중지 전략은 하이엔시 차트 모형을 기반으로 한 트렌드 추적 시스템으로 시장의 동력을 포착하고 수익을 보호하도록 설계되었습니다. 이 전략은 초기 입문과 2차 입문 (피라미드형 상장) 을 허용하며, 각 입문에는 독립적인 수익 목표 및 중지 설정이 있습니다.

전략 원칙

이 전략은 다음과 같은 몇 가지 핵심 원칙에 기반을 두고 있습니다.

  1. 하이엔시 트 신호: 하이엔안시 그래프를 사용하여 시장 소음을 필터링하고 트렌드를 식별한다. 다중 헤드 신호는 현재 HA 종료 가격이 HA 개시 가격보다 높고 이전 HA 종료 가격보다 높을 때 유발됩니다. 공중 헤드 신호는 그 반대입니다.

  2. 이중 입학 시스템:

    • 첫 번째 진입: 초기 HA 신호에 따라 미리 정의된 목표 및 스톱 레벨을 설정합니다.
    • 2차 진입: 첫 번째 목표가 달성된 후 시장이 유리한 HA 신호를 계속 표시하면 추가 진입이 허용됩니다.
  3. 과 손해 균형 보호첫 번째 목표가 달성되면, 전략은 자동으로 스톱 로즈 레벨을 입시 가격으로 이동하여 거래가 손실되지 않도록합니다.

  4. 목표 지역 개념: 가격이 목표 수준에 가까울 때 (예정된 하락값 내에서), 전략은 “목표 영역”을 시작하여 더 많은 잠재적인 수익을 잡기 위해 목표 수준을 높인다.

  5. 후속 손실 메커니즘:

    • 첫 번째 입점 추적: 초기 목표가 달성 된 후, 스톱 손실 지점은 최고 / 최저 가격의 이동을 따라 고정 거리를 유지합니다.
    • 2차 입점 추적: 부채 부문에 대한 개별 추적 중지 매개 변수가 있다
  6. 상태 추적전략: 거래 방향, 가격 극치, 첫 번째 목표가 달성되었는지, 현재 목표 영역에 있는지 등을 추적하기 위해 여러 변수를 유지합니다.

전략적 이점

  1. 전체적인 위험 관리이 전략은 사전 상쇄, 상쇄 균형 보호 및 후속 상쇄를 통해 여러 층의 위험 관리를 제공하여 자본을 급격한 하락으로부터 보호합니다.

  2. 피라미드 형태의 투자 기회: 두 번째 입장을 허용함으로써, 전략은 확인된 추세에서 입장을 늘리고 수익 가능성을 높일 수 있으며, 첫 번째 거래가 이미 적립점으로 고정되어 있기 때문에 전반적인 위험을 증가시키지 않습니다.

  3. 동적인 수익 포획: 타겟 지역 및 타겟 증가 기능은 전략이 강세를 보이는 시장에서 수익 목표를 자동으로 확장할 수 있도록 해줍니다.

  4. 높이는 사용자 정의: 전략은 시장 조건, 거래 품종 특성과 개인 위험 선호도에 따라 조정할 수 있도록 광범위한 파라미터 설정을 제공합니다.

  5. 자동화 실행: 매개 변수 설정이 완료되면, 전략은 모든 입출장, 출장 및 중지 손실 조정을 실행하여 감정 거래의 영향을 제거한다.

  6. 시각적 피드백전략: 전략은 목표 수준, 정지 수준 및 현재 상태 지표를 보여주는 명확한 시각적 구성 요소를 포함하고 있으며, 거래자가 거래 진행을 쉽게 모니터링 할 수 있습니다.

전략적 위험

  1. 매개변수 민감도전략 성능은 파라미터 설정에 크게 의존한다. 부적절한 목표 또는 스톱 손실 파라미터는 좋은 거래를 조기 종료하거나 과도한 하락 위험을 감수할 수 있다. 역사 회귀 및 시장 특정 파라미터를 최적화함으로써이 위험을 줄일 수 있다.

  2. 미끄러짐 위험: 특히 후속 손해 중단 실행 기간 동안 시장의 격차 또는 유동성이 부족하면 실제 실행 가격이 이상적인 중단 수준과 차이가 발생할 수 있습니다. 미끄러짐 보퍼를 추가하거나 더 보수적인 후속 매개 변수를 사용하는 것이 위험을 줄일 수 있습니다.

  3. 재입장 과잉 거래: 2차 진입을 허용하면 불안정한 시장에서 과도한 거래가 발생할 수 있습니다. 추가 필터링 조건이나 2차 진입 시간 제한을 적용하면 이러한 상황이 줄어들 수 있습니다.

  4. 시장 전환 위험: 전략은 트렌드 시장에서 잘 작동하지만, 간격적인 흔들림 시장 또는 갑작스러운 전환 시장에서 좋지 않을 수 있습니다. 전략과 시장 상태 필터를 결합하여 사용하면 전체 효과를 높일 수 있습니다.

  5. 계산 밀도: 여러 변수와 상태를 추적하는 전략은 일부 플랫폼에서 실행 지연을 초래할 수 있습니다. 코드를 최적화하고 일부 계산을 단순화하면 성능을 향상시킬 수 있습니다.

전략 최적화 방향

  1. 트렌드 필터를 추가합니다.: 통합 트렌드 지표 (예를 들어 이동 평균, ADX 또는 트렌드 강도 지표) 는 입문 품질을 향상시키고 확인된 트렌드 방향으로만 거래 할 수 있습니다. 이것은 흔들리는 시장에서 잘못된 신호를 줄일 것입니다.

  2. 시간 필터링 조건: 두 번째 진입을 위한 시간 창 또는 냉각 기간을 추가하여 짧은 시간에 과도한 거래 또는 동일한 트렌드를 자주 입출하는 것을 방지한다.

  3. 변동성 조정: 시장의 변동성 (예: ATR) 에 따라 목표와 스톱로드 파라미터를 동적으로 조정하여 전략이 다른 시장 조건에 적응하도록합니다. 이것은 스톱로드 및 목표 수준을 현재 시장 특성에 더 잘 맞게 만들 것입니다.

  4. 하이엔시 논리 개선: 현재 HA 판단은 비교적 간단하며, 다중 HA 그래프 형태 또는 HA 동력 지표를 고려하여 신호 품질을 향상시킬 수 있다.

  5. 일부 수익 잠금 추가: 분기 수익 잠금 기능을 구현하여 특정 수익 수준에 도달했을 때 일부 포지션을 청산하는 동시에 나머지 부분을 계속 운영하여 수익 보호와 잠재적 인 수익을 극대화 할 수 있습니다.

  6. 목표 영역 논리를 최적화합니다.: 현재 타겟 지역은 고정 증가 걸음 길이를 사용합니다. 시장의 변동성이나 최근 가격 움직임에 기반한 동적 목표 조정 알고리즘을 고려하여 시장 조건 변화에 더 잘 적응 할 수 있습니다.

요약하다

다단계 목표 및 후속 손실 전략은 하이엔시 트렌드 식별, 동적 목표 관리, 2차 진입 기회 및 다단계 위험 통제를 결합한 포괄적 인 거래 시스템입니다. 이 전략의 주요 장점은 유연한 수익 확장 메커니즘과 엄격한 위험 관리 프레임 워크로 인해 트렌디 시장에서 눈에 띄는 움직임을 잡을 수 있습니다.

이 전략은 강력한 프레임워크를 제공하지만, 그 효과는 여전히 적절한 파라미터 조정과 시장 조건에 달려 있습니다. 시장 상태 필터, 변동성 조정 메커니즘 및 더 복잡한 입문 확인 논리를 추가하여 전략은 더욱 안정성과 적응력을 강화 할 수 있습니다. 궁극적으로, 이 전략은 균형을 이루는 을 나타냅니다.

전략 소스 코드
/*backtest
start: 2024-03-31 00:00:00
end: 2025-03-29 08:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=6
strategy("Algo Trading v1 | SUNNY GUHA By OIESU", overlay=true, margin_long=100, margin_short=100, pyramiding=100)

// ———— USER INPUTS ———— //
// First Entry Settings
float initialTarget  = input.float(10000, "First Entry: Target ($)", minval=1, tooltip="First target level")
float initialStopLoss = input.float(3000, "First Entry: Stop Loss ($)", minval=1, tooltip="Initial stop loss distance")
bool  useTrailFirst = input.bool(true, "First Entry: Enable Trail", tooltip="Enable trailing features after first target hit")
float profitTrailStepFirst = input.float(1500, "First Entry: Trail Amount ($)", minval=1, tooltip="Trail amount after first target hit")
bool  useTargetZoneFirst = input.bool(true, "First Entry: Enable Target Zone", tooltip="Enable target zone feature")
float targetZoneThresholdFirst = input.float(1000, "First Entry: Target Zone Threshold ($)", minval=1, tooltip="Distance to activate target zone")
float targetIncreaseStepFirst = input.float(2000, "First Entry: Target Increase ($)", minval=1, tooltip="Amount to increase target")

// Second Entry Settings
bool  enableSecondEntries = input.bool(true, "Enable Second Entries", tooltip="Allow re-entries after first target hit")
float secondTarget = input.float(5000, "Second Entry: Target ($)", minval=1, tooltip="Target for second entries")
float secondStopLoss = input.float(2000, "Second Entry: Stop Loss ($)", minval=1, tooltip="Stop loss for second entries")
bool  useTrailSecond = input.bool(true, "Second Entry: Enable Trail", tooltip="Enable trailing for second entries")
float profitTrailStepSecond = input.float(1500, "Second Entry: Trail Amount ($)", minval=1, tooltip="Trail amount for second entries")
bool  useTargetZoneSecond = input.bool(true, "Second Entry: Enable Target Zone", tooltip="Enable target zone")
float targetZoneThresholdSecond = input.float(1000, "Second Entry: Target Zone Threshold ($)", minval=1)
float targetIncreaseStepSecond = input.float(2000, "Second Entry: Target Increase ($)", minval=1)

// ———— HEIKIN-ASHI CALCULATIONS ———— //
var float haOpen   = na
var float haClose  = na
var float haHigh   = na
var float haLow    = na

haClose := (open + high + low + close)/4
haOpen  := na(haOpen[1]) ? (open + close)/2 : (haOpen[1] + haClose[1])/2
haHigh  := math.max(high, math.max(haOpen, haClose))
haLow   := math.min(low, math.min(haOpen, haClose))

// ———— TRACKING VARIABLES ———— //
var float highestPrice     = na  // Tracks highest price for long positions
var float lowestPrice      = na  // Tracks lowest price for short positions
var float basePrice        = na  // Entry price for position
var float targetLevel      = na  // Current target level
var float stopLevel        = na  // Current stop level
var bool  firstTargetHit   = false  // Indicates if first target was hit
var string tradeDirection  = "none"  // Current trade direction
var bool   isSecondEntry   = false   // Tracks if current position is a second entry
var bool   inTargetZone    = false   // Tracks if price is in target zone

// ———— SIGNAL DETECTION ———— //
bullish = haClose > haOpen and haClose > haClose[1]
bearish = haClose < haOpen and haClose < haClose[1]

// Entry conditions - only allow second entries if enabled and after first target hit
longCondition  = bullish and (tradeDirection != "long" or (enableSecondEntries and firstTargetHit))
shortCondition = bearish and (tradeDirection != "short" or (enableSecondEntries and firstTargetHit))

// Position Management - Long Positions
if strategy.position_size > 0
    highestPrice := math.max(high, nz(highestPrice, high))

    if isSecondEntry
        // Second Entry Management
        inTargetZone := useTargetZoneSecond and high >= targetLevel - targetZoneThresholdSecond

        if inTargetZone and useTargetZoneSecond
            targetLevel := targetLevel + targetIncreaseStepSecond

        if useTrailSecond
            stopLevel := math.max(stopLevel, highestPrice - profitTrailStepSecond)

        if low <= stopLevel
            strategy.close_all("Second Entry Stop")
            basePrice := na
            targetLevel := na
            stopLevel := na
            highestPrice := na
            lowestPrice := na
            firstTargetHit := false
            isSecondEntry := false
            inTargetZone := false
            tradeDirection := "none"
    else
        // First Entry Management - improved profit locking
        if not firstTargetHit and high >= basePrice + initialTarget
            // First target hit - ALWAYS lock profit at break-even
            firstTargetHit := true
            stopLevel := basePrice  // Move stop to break-even
            targetLevel := useTrailFirst ? high + targetIncreaseStepFirst : basePrice + initialTarget
        else if firstTargetHit
            // Only modify target if trailing is enabled
            if useTrailFirst
                inTargetZone := useTargetZoneFirst and high >= targetLevel - targetZoneThresholdFirst
                if inTargetZone and useTargetZoneFirst
                    targetLevel := targetLevel + targetIncreaseStepFirst
                // Trail stop-loss but never below break-even
                stopLevel := math.max(basePrice, highestPrice - profitTrailStepFirst)
        else
            // Before first target hit
            targetLevel := basePrice + initialTarget
            stopLevel := basePrice - initialStopLoss

        // Exit on stop hit - this could only be at break-even or better after first target
        if low <= stopLevel
            strategy.close_all("First Entry Stop")
            basePrice := na
            targetLevel := na
            stopLevel := na
            highestPrice := na
            lowestPrice := na
            firstTargetHit := false
            isSecondEntry := false
            inTargetZone := false
            tradeDirection := "none"

// Position Management - Short Positions
if strategy.position_size < 0
    lowestPrice := math.min(low, nz(lowestPrice, low))

    if isSecondEntry
        // Second Entry Management
        inTargetZone := useTargetZoneSecond and low <= targetLevel + targetZoneThresholdSecond

        if inTargetZone and useTargetZoneSecond
            targetLevel := targetLevel - targetIncreaseStepSecond

        if useTrailSecond
            stopLevel := math.min(stopLevel, lowestPrice + profitTrailStepSecond)

        if high >= stopLevel
            strategy.close_all("Second Entry Stop")
            basePrice := na
            targetLevel := na
            stopLevel := na
            highestPrice := na
            lowestPrice := na
            firstTargetHit := false
            isSecondEntry := false
            inTargetZone := false
            tradeDirection := "none"
    else
        // First Entry Management - improved profit locking
        if not firstTargetHit and low <= basePrice - initialTarget
            // First target hit - ALWAYS lock profit at break-even
            firstTargetHit := true
            stopLevel := basePrice  // Move stop to break-even
            targetLevel := useTrailFirst ? low - targetIncreaseStepFirst : basePrice - initialTarget
        else if firstTargetHit
            // Only modify target if trailing is enabled
            if useTrailFirst
                inTargetZone := useTargetZoneFirst and low <= targetLevel + targetZoneThresholdFirst
                if inTargetZone and useTargetZoneFirst
                    targetLevel := targetLevel - targetIncreaseStepFirst
                // Trail stop-loss but never above break-even
                stopLevel := math.min(basePrice, lowestPrice + profitTrailStepFirst)
        else
            // Before first target hit
            targetLevel := basePrice - initialTarget
            stopLevel := basePrice + initialStopLoss

        // Exit on stop hit - this could only be at break-even or better after first target
        if high >= stopLevel
            strategy.close_all("First Entry Stop")
            basePrice := na
            targetLevel := na
            stopLevel := na
            highestPrice := na
            lowestPrice := na
            firstTargetHit := false
            isSecondEntry := false
            inTargetZone := false
            tradeDirection := "none"

// New Position Entry
if strategy.position_size == 0
    if longCondition
        tradeDirection := "long"
        basePrice := close
        targetLevel := basePrice + (firstTargetHit ? secondTarget : initialTarget)
        stopLevel := basePrice - (firstTargetHit ? secondStopLoss : initialStopLoss)
        highestPrice := high
        isSecondEntry := firstTargetHit
        strategy.entry("Long", strategy.long)
    else if shortCondition
        tradeDirection := "short"
        basePrice := close
        targetLevel := basePrice - (firstTargetHit ? secondTarget : initialTarget)
        stopLevel := basePrice + (firstTargetHit ? secondStopLoss : initialStopLoss)
        lowestPrice := low
        isSecondEntry := firstTargetHit
        strategy.entry("Short", strategy.short)

// ———— VISUALIZATION ———— //
// Entry signals
plotshape(longCondition and (strategy.position_size == 0),     title="Buy", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)

plotshape(shortCondition and (strategy.position_size == 0),     title="Sell", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)

// Target and stop levels with clearer colors
plot(targetLevel, title="Target Level", color=color.orange, linewidth=2)
plot(stopLevel, title="Stop Level", color=color.red, linewidth=2)

// Break-even level - shown prominently after first target hit
plot(strategy.position_size != 0 and firstTargetHit ? basePrice : na,     title="Break-Even Level", color=color.green, linewidth=2, style=plot.style_linebr)

// Debug plots for state tracking
plotchar(firstTargetHit, title="First Target Hit", char="T", location=location.top, color=color.yellow, size=size.tiny)
plotchar(isSecondEntry, title="Second Entry", char="2", location=location.top, color=color.white, size=size.tiny)
plotchar(useTrailFirst and firstTargetHit, title="Trail Active", char="→", location=location.top, color=color.blue, size=size.tiny)
plotchar(inTargetZone, title="Target Zone", char="Z", location=location.top, color=color.fuchsia, size=size.tiny)