이중 이동 평균 추세 추적 및 ATR 위험 제어 적응형 거래 전략

SMA ATR TP SL HTF
생성 날짜: 2024-11-29 14:56:43 마지막으로 수정됨: 2024-11-29 14:56:43
복사: 0 클릭수: 522
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

이중 이동 평균 추세 추적 및 ATR 위험 제어 적응형 거래 전략

개요

이 전략은 클래식 쌍방평선 트렌드 추적과 ATR 동적 리드 컨트롤을 결합한 적응형 거래 시스템이다. 이 전략은 두 가지 거래 모드를 제공합니다. 기본 모드는 간단한 쌍방평선 교차를 사용하여 트렌드 추적을 수행하며, 고급 모드는 더 높은 시간 프레임의 트렌드 필터링과 ATR 기반의 동적 스톱 메커니즘을 추가합니다.

전략 원칙

전략 1 (기본 모드) 는 21일과 49일 쌍평균 시스템으로, 빠른 평균이 느린 평균을 상향으로 통과할 때 다중 신호를 발생시킨다. 수익 목표는 비율 또는 점수 방식을 선택할 수 있으며, 수익을 잠금하기 위해 선택 가능한 모바일 중지 기능을 제공한다. 전략 2 (고급 모드) 는 쌍평균 시스템의 기초에 일선 레벨의 트렌드 필터를 추가하고, 가격이 더 높은 시간 프레임 평평균 위에 있을 때만 입장이 허용된다. 동시에 14ATR 주기를 기반으로 한 동적 중지 손실을 도입하고, 시장의 변동성에 따라 손해 중지 거리가 자동으로 조정되며, 수익을 보호하는 일부 수익 종료 기능을 제공한다.

전략적 이점

  1. 전략은 매우 적응성이 강하며 거래자의 경험 수준과 시장 환경에 따라 유연하게 전환할 수 있습니다.
  2. 고급 모드에서 다중 시간 프레임 분석은 신호 품질을 향상시킵니다.
  3. ATR 동적 상쇄는 다양한 시장 변동 조건에 적응할 수 있습니다.
  4. 일부 수익 메커니즘은 수익 보호와 추세 유지의 균형을 맞추고 있습니다.
  5. 다양한 시장 특성에 따라 최적화 할 수있는 유연한 매개 변수 구성

전략적 위험

  1. 이중 평선 시스템은 흔들리는 시장에서 자주 잘못된 신호를 발생시킬 수 있습니다.
  2. 트렌드 필터링으로 인해 신호가 지연되고 거래 기회가 놓쳐질 수 있습니다.
  3. ATR 정지는 변동률 변동에 있어서 적절하지 않을 수 있다
  4. 일부 수익은 조기 하락으로 큰 수익에 영향을 미칠 수 있다.

전략 최적화 방향

  1. 거래량과 변동률 지표의 필터링을 증가시킬 수 있습니다.
  2. 시장 상황에 따라 수평 주기를 자동으로 조정하는 동적 변수 적응 장치를 도입하는 것을 고려하십시오.
  3. ATR 계산 사이클을 최적화하여 민감성과 안정성을 균형을 맞추기
  4. 시장 상태를 인식하는 모듈을 추가하여 최적의 전략 모드를 자동으로 선택합니다.
  5. 더 많은 손실을 방지할 수 있는 옵션을 도입합니다. 예를 들어, 추적 손실, 시간 손실

요약하다

이것은 합리적으로 설계된, 완벽하게 기능하는 거래 전략 시스템이다. 쌍방향 트렌드 추적과 ATR 풍력 제어의 결합을 통해 전략의 신뢰성을 보장하고, 또한 좋은 위험 관리를 제공한다. 쌍방향 디자인은 다양한 수준의 거래자의 요구를 충족시키고, 풍부한 매개 변수 설정은 충분한 최적화 공간을 제공합니다. 거래자는 실제에서 보수적인 매개 변수에서 시작하여 최적화를 단계적으로 조정하여 최적의 효과를 얻도록 권장한다.

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

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © shaashish1

//@version=5
strategy("Dual Strategy Selector V2 - Cryptogyani", overlay=true, pyramiding=0, 
         default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=100000)

//#region STRATEGY SELECTION
strategyOptions = input.string(title="Select Strategy", defval="Strategy 1", options=["Strategy 1", "Strategy 2"], group="Strategy Selection")
//#endregion STRATEGY SELECTION

// ####################### STRATEGY 1: Original Logic ########################
//#region STRATEGY 1 INPUTS
s1_fastMALen = input.int(defval=21, title="Fast SMA Length (S1)", minval=1, group="Strategy 1 Settings", inline="S1 MA")
s1_slowMALen = input.int(defval=49, title="Slow SMA Length (S1)", minval=1, group="Strategy 1 Settings", inline="S1 MA")
s1_takeProfitMode = input.string(defval="Percentage", title="Take Profit Mode (S1)", options=["Percentage", "Pips"], group="Strategy 1 Settings")
s1_takeProfitPerc = input.float(defval=7.0, title="Take Profit % (S1)", minval=0.05, step=0.05, group="Strategy 1 Settings") / 100
s1_takeProfitPips = input.float(defval=50, title="Take Profit Pips (S1)", minval=1, step=1, group="Strategy 1 Settings")
s1_trailingTakeProfitEnabled = input.bool(defval=false, title="Enable Trailing (S1)", group="Strategy 1 Settings")
//#endregion STRATEGY 1 INPUTS

// ####################### STRATEGY 2: Enhanced with Recommendations ########################
//#region STRATEGY 2 INPUTS
s2_fastMALen = input.int(defval=20, title="Fast SMA Length (S2)", minval=1, group="Strategy 2 Settings", inline="S2 MA")
s2_slowMALen = input.int(defval=50, title="Slow SMA Length (S2)", minval=1, group="Strategy 2 Settings", inline="S2 MA")
s2_atrLength = input.int(defval=14, title="ATR Length (S2)", group="Strategy 2 Settings", inline="ATR")
s2_atrMultiplier = input.float(defval=1.5, title="ATR Multiplier for Stop-Loss (S2)", group="Strategy 2 Settings", inline="ATR")
s2_partialTakeProfitPerc = input.float(defval=50.0, title="Partial Take Profit % (S2)", minval=10, maxval=100, step=10, group="Strategy 2 Settings")
s2_timeframeTrend = input.timeframe(defval="1D", title="Higher Timeframe for Trend Filter (S2)", group="Strategy 2 Settings")
//#endregion STRATEGY 2 INPUTS

// ####################### GLOBAL VARIABLES ########################
var float takeProfitPrice = na
var float stopLossPrice = na
var float trailingStopPrice = na
var float fastMA = na
var float slowMA = na
var float higherTimeframeTrendMA = na
var bool validOpenLongPosition = false

// Precalculate higher timeframe values (global scope for Strategy 2)
higherTimeframeTrendMA := request.security(syminfo.tickerid, s2_timeframeTrend, ta.sma(close, s2_slowMALen))

// ####################### LOGIC ########################
if (strategyOptions == "Strategy 1")
    // Strategy 1 Logic (Original Logic Preserved)
    fastMA := ta.sma(close, s1_fastMALen)
    slowMA := ta.sma(close, s1_slowMALen)
    openLongPosition = ta.crossover(fastMA, slowMA)
    validOpenLongPosition := openLongPosition and strategy.opentrades.size(strategy.opentrades - 1) == 0
    
    // Take Profit Price
    takeProfitPrice := if (s1_takeProfitMode == "Percentage")
        close * (1 + s1_takeProfitPerc)
    else
        close + (s1_takeProfitPips * syminfo.mintick)

    // Trailing Stop Price (if enabled)
    if (strategy.position_size > 0 and s1_trailingTakeProfitEnabled)
        trailingStopPrice := high - (s1_takeProfitPips * syminfo.mintick)
    else
        trailingStopPrice := na

else if (strategyOptions == "Strategy 2")
    // Strategy 2 Logic with Recommendations
    fastMA := ta.sma(close, s2_fastMALen)
    slowMA := ta.sma(close, s2_slowMALen)
    openLongPosition = ta.crossover(fastMA, slowMA) and close > higherTimeframeTrendMA
    validOpenLongPosition := openLongPosition and strategy.opentrades.size(strategy.opentrades - 1) == 0

    // ATR-Based Stop-Loss
    atr = ta.atr(s2_atrLength)
    stopLossPrice := close - (atr * s2_atrMultiplier)

    // Partial Take Profit Logic
    takeProfitPrice := close * (1 + (s2_partialTakeProfitPerc / 100))
//#endregion STRATEGY LOGIC

// ####################### PLOTTING ########################
plot(series=fastMA, title="Fast SMA", color=color.yellow, linewidth=1)
plot(series=slowMA, title="Slow SMA", color=color.orange, linewidth=1)
plot(series=takeProfitPrice, title="Take Profit Price", color=color.teal, linewidth=1, style=plot.style_linebr)

// Trailing Stop and ATR Stop-Loss Plots (Global Scope)
plot(series=(strategyOptions == "Strategy 1" and s1_trailingTakeProfitEnabled) ? trailingStopPrice : na, title="Trailing Stop", color=color.red, linewidth=1, style=plot.style_linebr)
plot(series=(strategyOptions == "Strategy 2") ? stopLossPrice : na, title="ATR Stop-Loss", color=color.red, linewidth=1, style=plot.style_linebr)
//#endregion PLOTTING

// ####################### POSITION ORDERS ########################
//#region POSITION ORDERS
if (validOpenLongPosition)
    strategy.entry(id="Long Entry", direction=strategy.long)

if (strategyOptions == "Strategy 1")
    if (strategy.position_size > 0)
        if (s1_trailingTakeProfitEnabled)
            strategy.exit(id="Trailing Take Profit", from_entry="Long Entry", stop=trailingStopPrice)
        else
            strategy.exit(id="Take Profit", from_entry="Long Entry", limit=takeProfitPrice)

else if (strategyOptions == "Strategy 2")
    if (strategy.position_size > 0)
        strategy.exit(id="Partial Take Profit", from_entry="Long Entry", qty_percent=s2_partialTakeProfitPerc, limit=takeProfitPrice)
        strategy.exit(id="Stop Loss", from_entry="Long Entry", stop=stopLossPrice)
//#endregion POSITION ORDERS