RSI 동적 다이버전스 정량적 전략

RSI ATR SL/TP risk management DIVERGENCE Pivot
생성 날짜: 2025-04-25 14:57:31 마지막으로 수정됨: 2025-04-25 14:57:31
복사: 0 클릭수: 455
avatar of ianzeng123 ianzeng123
2
집중하다
319
수행원

RSI 동적 다이버전스 정량적 전략 RSI 동적 다이버전스 정량적 전략

개요

RSI 이중 축 오차량화 전략은 가격행동과 상대적으로 강한 지수 ((RSI) 와의 정기적 인 우세 및 하향 오차를 탐지하여 잠재적인 역전 기회를 식별하는 고급 거래 전략입니다. 이 전략은 자동화 된 축점 탐지 알고리즘을 사용하여 두 가지 다른 스톱/스트로프 관리 방법을 결합하여 오차 신호가 확인되면 자동으로 위치를 설정합니다. 전략의 핵심은 가격과 RSI 지표 사이의 오차 현상을 확인하는 정확한 수학 계산을 통해 전략의 핵심이며, 동적 위험 관리 메커니즘을 사용하여 모든 거래가 예상된 위험-이익 비율을 따르도록 보장합니다.

전략 원칙

  1. RSI 계산 모듈: 와일더 평형 방식을 사용하여 14주기 ((조정가능) RSI 값을 계산하고, 종점 가격을 기본 입력 소스로 사용한다 (설정가능).
  2. 중심점 검출:
    • RSI 지표의 지역적 높음과 낮음을 탐지하기 위해 좌우로 5주기마다 (변화 가능한) 슬라이딩 창을 사용합니다.
    • ta.barssince 함수를 사용하여 축점 사이의 간격이 5~60 K선 (변화 가능한 범위)
  3. 확인 논리에서 벗어난 것:
    • “가격 혁신이 낮고 RSI가 더 높은 하락점을 형성한다”
    • 하락의 반발: 가격 혁신이 높고 RSI는 더 낮은 고점을 형성한다
  4. 거래 실행 시스템:
    • 이중 모드 스톱 메커니즘을 사용한다: 최근 20주기 ((조정가능) 변동점 또는 ATR 변동의 폭에 따라
    • 동적 스톱 계산: 리스크 금액에 따라 미리 설정된 리턴 리스크 비율을 곱한 (부정 2: 1)
  5. 시각화 시스템: 모든 유효한 이탈 신호를 도표에 표시하고, 실시간으로 현재 포지션의 스톱로스 (붉은) 와 스톱로스 (녹색) 수평선을 표시한다.

우위 분석

  1. 다차원 검증 메커니즘: 가격과 RSI가 특정 형태를 동시에 충족해야 함을 요구하며, 시간 간격은 기본 범위 내에서, 가짜 신호의 가능성을 크게 감소시킵니다.
  2. 자율적 위험 관리:
    • 변동점 모델은 유동시장에 적합하며, 파동대 상황을 효과적으로 파악할 수 있습니다.
    • ATR 모드는 불안정한 시장에 적합하며, 변동에 따라 자동으로 중지량을 조정합니다.
  3. 매개 변수 고도 조정: 모든 핵심 매개 변수 (RSI 주기, 축 검출 범위, 리스크 수익률 등) 는 시장 특성에 따라 조정할 수 있습니다.
  4. 과학적인 자금 관리: 단일 거래의 과도한 위험 노출을 방지하기 위해 10%의 포지션 비율을 기본으로 사용합니다.
  5. 실시간 시각적 피드백: 그래프 표기 및 동적 스톱/스트롭 라인을 통해 직관적인 거래 의사 결정 지원을 제공합니다.

위험 분석

  1. 뒤떨어진 위험: RSI가 뒤떨어진 지표로서, 급격한 일방적인 상황에서 지연 신호가 발생할 수 있습니다. 완화 옵션: 트렌드 필터를 결합하거나 RSI 주기를 단축하십시오.
  2. 흔들림 시장 위험: 명확한 추세가 없을 때 연속적인 가짜 신호가 발생할 수 있다. 완화 방안: ATR 모드를 활성화하고 대폭수를 증가시키거나, 부가적인 변동률 필터.
  3. 매개 변수 과합 위험: 특정 매개 변수 조합은 역사적 데이터에서 잘 작동하지만 실 디스크에서 실패할 수 있다. 완화方案: 여러 주기의 여러 품종의 스트레스 테스트를 실시한다.
  4. 극한 시장 위험: 폭파 틈은 중단 손실을 초래할 수 있다. 완화 방안: 주요 경제 사건 전후 거래를 피하거나, 옵션 제어를 사용한다.
  5. 시간 프레임 의존성: 다른 시간 주기에서 성능 차이가 크다. 완화方案: 목표 시간 프레임에 충분히 회수 최적화한다.

최적화 방향

  1. 복합 지표 검증: MACD 또는 거래량 지표를 추가하여 2차 확인으로 신호 품질을 향상시킨다.
  2. 동적 변수 조정: 시장의 변동에 따라 RSI 주기와 ATR 곱수를 자동으로 조정한다.
  3. 기계 학습 최적화: 유전 알고리즘을 사용하여 핵심 파라미터 조합을 최적화한다.
  4. 다중 시간 프레임 분석: 더 높은 시간 프레임의 트렌드 방향을 필터링한다.
  5. 포지션 동적 관리: 변동률에 따라 포지션 크기를 조정하여 위험 균형을 달성한다.
  6. 이벤트 필터: 경제 달력 데이터를 통합하여 중요한 데이터 발표 전후 거래를 피하십시오.

요약하다

RSI 이중 축의 이탈량화 전략은 체계화된 이탈 식별과 엄격한 위험 관리를 통해 구조화된 역전 거래 방법을 제공한다. 그것의 핵심 가치는 전통적인 기술 분석 개념을 측정 가능한 거래 규칙으로 변환하고, 쌍방식 중지 손해 메커니즘을 통해 다른 시장 환경에 적응하는 것이다. 전략의 우수한 성능은 세 가지 핵심 요소가 필요합니다. 적절한 매개 변수 최적화, 엄격한 위험 제어 및 일관된 실행 규율. 이 전략은 다소 변동적이지만 추세가 극단적이지 않은 시장 환경에 특히 적합하며, 중간 수준의 거래자가 양자 트레이딩으로 전환하는 훌륭한 모델이다.

전략 소스 코드
/*backtest
start: 2024-04-25 00:00:00
end: 2025-04-23 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"DOGE_USDT"}]
*/

//@version=6
strategy("RSI Divergence Strategy - AliferCrypto", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// === RSI Settings ===
rsiLength      = input.int(14, minval=1, title="RSI Length", group="RSI Settings", tooltip="Number of periods for RSI calculation")
rsiSource      = input.source(close, title="RSI Source", group="RSI Settings", tooltip="Price source used for RSI calculation")

// === Divergence Settings ===
lookLeft       = input.int(5, minval=1, title="Pivot Lookback Left", group="Divergence Settings", tooltip="Bars to the left for pivot detection")
lookRight      = input.int(5, minval=1, title="Pivot Lookback Right", group="Divergence Settings", tooltip="Bars to the right for pivot detection")
rangeLower     = input.int(5, minval=1, title="Min Bars Between Pivots", group="Divergence Settings", tooltip="Minimum bars between pivots to validate divergence")
rangeUpper     = input.int(60, minval=1, title="Max Bars Between Pivots", group="Divergence Settings", tooltip="Maximum bars between pivots to validate divergence")

// === SL/TP Method ===
method         = input.string("Swing", title="SL/TP Method", options=["Swing", "ATR"], group="SL/TP Settings", tooltip="Choose between swing-based or ATR-based stop and target")

// === Swing Settings ===
swingLook      = input.int(20, minval=1, title="Swing Lookback (bars)", group="Swing Settings", tooltip="Bars to look back for swing high/low")
swingMarginPct = input.float(1.0, minval=0.0, title="Swing Margin (%)", group="Swing Settings", tooltip="Margin around swing levels as percentage of price")
rrSwing        = input.float(2.0, title="R/R Ratio (Swing)", group="Swing Settings", tooltip="Risk/reward ratio when using swing-based method")

// === ATR Settings ===
atrLen         = input.int(14, minval=1, title="ATR Length", group="ATR Settings", tooltip="Number of periods for ATR calculation")
atrMult        = input.float(1.5, minval=0.1, title="ATR SL Multiplier", group="ATR Settings", tooltip="Multiplier for ATR-based stop loss calculation")
rrAtr          = input.float(2.0, title="R/R Ratio (ATR)", group="ATR Settings", tooltip="Risk/reward ratio when using ATR-based method")

// === RSI Calculation ===
_d    = ta.change(rsiSource)
up    = ta.rma(math.max(_d, 0), rsiLength)
down  = ta.rma(-math.min(_d, 0), rsiLength)
rsi   = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))

// === Divergence Detection ===
defPl      = not na(ta.pivotlow(rsi, lookLeft, lookRight))
defPh      = not na(ta.pivothigh(rsi, lookLeft, lookRight))
rsiAtRR   = rsi[lookRight]
barsPl    = ta.barssince(defPl)
barsPl1   = barsPl[1]
inRangePL = barsPl1 >= rangeLower and barsPl1 <= rangeUpper
barsPh    = ta.barssince(defPh)
barsPh1   = barsPh[1]
inRangePH = barsPh1 >= rangeLower and barsPh1 <= rangeUpper
prevPlRsi   = ta.valuewhen(defPl, rsiAtRR, 1)
prevPhRsi   = ta.valuewhen(defPh, rsiAtRR, 1)
prevPlPrice = ta.valuewhen(defPl, low[lookRight], 1)
prevPhPrice = ta.valuewhen(defPh, high[lookRight], 1)
bullCond    = defPl and low[lookRight] < prevPlPrice and rsiAtRR > prevPlRsi and inRangePL
bearCond    = defPh and high[lookRight] > prevPhPrice and rsiAtRR < prevPhRsi and inRangePH

plotshape(bullCond, title="Bullish Divergence", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny)
plotshape(bearCond, title="Bearish Divergence", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny)

// === Entries ===
if bullCond
    strategy.entry("Long", strategy.long)
if bearCond
    strategy.entry("Short", strategy.short)

// === Pre-calculate SL/TP components ===
swingLow    = ta.lowest(low, swingLook)
swingHigh   = ta.highest(high, swingLook)
atrValue    = ta.atr(atrLen)

// === SL/TP Calculation & Exits ===
var float slPrice = na
var float tpPrice = na
var float rr      = na

// Long exits
if strategy.position_size > 0
    entryPrice = strategy.position_avg_price
    if method == "Swing"
        slPrice := swingLow * (1 - swingMarginPct / 100)
        rr      := rrSwing
    else
        slPrice := entryPrice - atrValue * atrMult
        rr      := rrAtr
    risk     = entryPrice - slPrice
    tpPrice  := entryPrice + risk * rr
    strategy.exit("Exit Long", from_entry="Long", stop=slPrice, limit=tpPrice)

// Short exits
if strategy.position_size < 0
    entryPrice = strategy.position_avg_price
    if method == "Swing"
        slPrice := swingHigh * (1 + swingMarginPct / 100)
        rr      := rrSwing
    else
        slPrice := entryPrice + atrValue * atrMult
        rr      := rrAtr
    risk     = slPrice - entryPrice
    tpPrice  := entryPrice - risk * rr
    strategy.exit("Exit Short", from_entry="Short", stop=slPrice, limit=tpPrice)

// === Plot SL/TP Levels ===
plot(strategy.position_size != 0 ? slPrice : na, title="Stop Loss", style=plot.style_linebr, color=color.red)
plot(strategy.position_size != 0 ? tpPrice : na, title="Take Profit", style=plot.style_linebr, color=color.green)

// === Alerts ===
alertcondition(bullCond, title="Bull RSI Divergence", message="Bullish RSI divergence detected")
alertcondition(bearCond, title="Bear RSI Divergence", message="Bearish RSI divergence detected")