유연한 다중 기간 이동 평균 교차 전략 고급판

MA SMA EMA WMA HMA SMMA
생성 날짜: 2024-11-28 15:18:47 마지막으로 수정됨: 2024-11-28 15:18:47
복사: 0 클릭수: 516
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

유연한 다중 기간 이동 평균 교차 전략 고급판

개요

이 전략은 여러 평균선과 여러 시간 주기 기반의 고급 정량 거래 시스템입니다. 그것은 거래자가 다양한 유형의 이동 평균을 선택 할 수 있도록 유연하게 허용합니다 (SMA, EMA, WMA, HMA 및 SMMA 포함) 그리고 시장 상황에 따라 일선, 주선 또는 달선과 같은 여러 시간 주기에서 자유롭게 교환 할 수 있습니다. 전략의 핵심 논리는 매출 가격과 선택한 평균선의 위치 관계를 비교하여 매출 신호를 결정하는 것이며, 다른 시간 주기 반복 검사를 결합하여 거래의 정확성을 향상시킵니다.

전략 원칙

전략은 모듈화 설계로, 주로 네 개의 핵심 구성 요소를 포함합니다: 평행선 유형 선택 모듈, 시간 주기 선택 모듈, 신호 생성 모듈 및 포지션 관리 모듈. 종료 가격 위에 선택된 평행선을 통과하면, 시스템은 다음 거래 주기 시작할 때 여러 신호를 냅니다. 종료 가격 아래 평행선을 통과하면, 시스템은 다음 거래 주기 시작할 때 평행 신호를 냅니다. 전략은 request.security 함수를 통해 주기 간 데이터 계산을 구현하여 다양한 프레임 타임의 신호 정확성을 보장합니다.

전략적 이점

  1. 높은 유연성: 다양한 평균선 유형과 시간 주기 조합을 지원하여 다양한 시장 환경에 적응
  2. 리스크 관리가 완벽하다: 자동으로 주기 종료 검사 시스템을 통해 공백과 기회를 놓치지 않도록 한다.
  3. 합리적인 자금 관리: 포지션 퍼센티지 관리 방식을 사용하여 위험을 효과적으로 제어하십시오.
  4. 신호 안정성: 여러 확인 메커니즘을 통해 가짜 신호의 영향을 줄인다.
  5. 광범위한 적응성: 다양한 거래 유형과 시장 환경에 적용할 수 있습니다.

전략적 위험

  1. 지연성 위험: 평균선 지표 자체는 지연성을 가지고 있으며, 진출 및 출전 시간을 지연시킬 수 있습니다.
  2. 흔들림 시장 위험: 수평 변동 시장에서 빈번한 가짜 브레이크 신호가 발생할 수 있습니다.
  3. 초주기 위험: 다른 시간 주기의 신호가 모순될 수 있으며, 효과적인 신호 우선 순위를 설정해야 한다.
  4. 자금 관리 위험: 고정 비율 지위는 특정 시장 조건에서 너무 급진적일 수 있습니다.

전략 최적화 방향

  1. 변동성 지표 도입: ATR 또는 Bollinger Bands와 같은 변동성 지표를 추가하여 포지션 크기를 동적으로 조정하는 것이 좋습니다.
  2. 트렌드 필터를 추가: 장기 주기 트렌드 판단 메커니즘을 추가하여 주 트렌드 방향으로만 포지션을 열 수 있습니다.
  3. 최적화된 신호 확인 메커니즘: 트래픽량과 같은 보조 지표의 도입을 고려하여 신호 신뢰도를 높인다.
  4. 손해 차단 기능 개선: 손해 추적 기능을 추가하여 수익을 더 잘 보호할 수 있습니다.
  5. 시장의 감정 지표를 증가 시키십시오: RSI 또는 MACD와 같은 지표를 도입하여 시장의 과매매를 판단하십시오.

요약하다

이 전략은 완벽하게 설계된, 논리적으로 명확한 거래 시스템이며, 유연한 파라미터 설정과 여러 확인 메커니즘을 통해 거래자에게 신뢰할 수있는 거래 도구를 제공합니다. 전략의 모듈 디자인은 강력한 확장성을 갖출 수 있도록 해줍니다. 지속적인 최적화를 통해 성능을 더욱 향상시킬 수 있습니다.

전략 소스 코드
/*backtest
start: 2019-12-23 08:00:00
end: 2024-11-27 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("Flexible Moving Average Strategy", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Input to select the review frequency (Daily, Weekly, Monthly)
check_frequency = input.string("Weekly", title="Review Frequency", options=["Daily", "Weekly", "Monthly"])

// Input to select the Moving Average method (SMA, EMA, WMA, HMA, SMMA)
ma_method = input.string("EMA", title="Moving Average Method", options=["SMA", "EMA", "WMA", "HMA", "SMMA"])

// Input to select the length of the Moving Average
ma_length = input.int(30, title="Moving Average Length", minval=1)

// Input to select the timeframe for Moving Average calculation
ma_timeframe = input.string("W", title="Moving Average Timeframe", options=["D", "W", "M"])

// Calculate all Moving Averages on the selected timeframe
sma_value = request.security(syminfo.tickerid, ma_timeframe, ta.sma(close, ma_length), lookahead=barmerge.lookahead_off)
ema_value = request.security(syminfo.tickerid, ma_timeframe, ta.ema(close, ma_length), lookahead=barmerge.lookahead_off)
wma_value = request.security(syminfo.tickerid, ma_timeframe, ta.wma(close, ma_length), lookahead=barmerge.lookahead_off)
hma_value = request.security(syminfo.tickerid, ma_timeframe, ta.hma(close, ma_length), lookahead=barmerge.lookahead_off)
smma_value = request.security(syminfo.tickerid, ma_timeframe, ta.rma(close, ma_length), lookahead=barmerge.lookahead_off) // Smoothed Moving Average (SMMA)

// Select the appropriate Moving Average based on user input
ma = ma_method == "SMA" ? sma_value : 
     ma_method == "EMA" ? ema_value :
     ma_method == "WMA" ? wma_value :
     ma_method == "HMA" ? hma_value :
     smma_value  // Default to SMMA

// Variable initialization
var float previous_close = na
var float previous_ma = na
var float close_to_compare = na
var float ma_to_compare = na

// Detect the end of the period (Daily, Weekly, or Monthly) based on the selected frequency
var bool is_period_end = false

if check_frequency == "Daily"
    is_period_end := ta.change(time('D')) != 0
else if check_frequency == "Weekly"
    is_period_end := ta.change(time('W')) != 0
else if check_frequency == "Monthly"
    is_period_end := ta.change(time('M')) != 0

// Store the close and Moving Average values at the end of the period
if is_period_end
    previous_close := close[0]  // Closing price of the last day of the period
    previous_ma := ma[0]  // Moving Average value at the end of the period

// Strategy logic
is_period_start = is_period_end

// Check if this is the first bar of the backtest
is_first_bar = barstate.isfirst

if (is_period_start or is_first_bar)
    // If the previous period values are not available, use current values
    close_to_compare := not na(previous_close) ? previous_close : close[0]
    ma_to_compare := not na(previous_ma) ? previous_ma : ma[0]
    
    if close_to_compare < ma_to_compare
        // Close price below the MA -> Sell
        if strategy.position_size > 0
            strategy.close("Long")
    else
        // Close price above the MA -> Buy/Hold
        if strategy.position_size == 0
            strategy.entry("Long", strategy.long)

// Close all positions at the end of the backtest period
if barstate.islastconfirmedhistory
    strategy.close_all(comment="Backtest End")

// Plot the previous period's close price for comparison
plot(previous_close, color=color.red, title="Previous Period Close", style=plot.style_stepline)
plot(close_to_compare, color=color.blue, title="Close to Compare", style=plot.style_line)

// Plot the selected Moving Average
plot(ma, color=color.white, title="Moving Average", style=plot.style_line, linewidth=3)