다중 시간 프레임 추세 추적 및 ATR 손절매 및 손절매 전략

ATR EMA
생성 날짜: 2024-12-20 14:14:32 마지막으로 수정됨: 2024-12-20 14:14:32
복사: 0 클릭수: 431
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

다중 시간 프레임 추세 추적 및 ATR 손절매 및 손절매 전략

개요

이것은 UT Bot와 50주기 지수 이동 평균 ((EMA) 을 결합한 트렌드 추적 거래 전략이다. 이 전략은 주로 1분 시간 주기에서 단선 거래를 하고, 5분 시간 주기의 트렌드 라인을 방향 필터로 사용한다. 이 전략은 ATR 지표의 동적으로 스톱 손실 위치를 계산하고, 이윤을 최적화하기 위해 더블 스톱 목표를 설정한다.

전략 원칙

전략의 핵심 논리는 다음과 같은 핵심 구성 요소를 기반으로 합니다.

  1. UT Bot를 사용하여 역동적으로 지원 저항을 계산합니다.
  2. 5분 주기의 50주기 EMA를 사용하여 전체 트렌드 방향을 판단합니다.
  3. 21주기 EMA와 UT Bot 신호를 결합하여 특정 입구점을 결정한다
  4. ATR 배수를 통해 동적 추적 중지 설정
  5. 0.5%와 1%의 두 개의 정지 목표를 설정하여 각각 50%의 지위를 청산하십시오.

가격이 UT 봇이 계산한 지지/저항 지점을 뚫고 21주기 EMA와 UT 봇이 교차할 때, 가격이 5분 50주기 EMA의 올바른 방향에 있다면 거래 신호를 유발한다.

전략적 이점

  1. 다중 시간 주기를 결합하여 거래 신뢰성을 향상시킵니다.
  2. 동적 ATR 중지 손실은 시장의 변동에 따라 적응할 수 있습니다.
  3. 이중 정지 목표가 수익과 승률을 균형을 맞추고 있습니다.
  4. Heikin Ashi 필터링을 사용하여 일부 가짜 돌파구를 필터링할 수 있습니다.
  5. 유연한 거래방향을 지원합니다. (일단 거래, 단 거래 또는 양방향 거래가 가능합니다.)

전략적 위험

  1. 단기 거래는 높은 분기점과 수수료 비용에 직면할 수 있습니다.
  2. 수평 정리 시장에서 빈번한 잘못된 신호가 발생할 수 있습니다.
  3. 다중 조건의 제한은 잠재적인 거래 기회를 놓칠 수 있습니다.
  4. ATR 매개 변수의 설정은 다른 시장에 대해 최적화해야 합니다.

전략 최적화 방향

  1. 수송량 지표가 추가될 수 있습니다.
  2. 더 많은 시장 감정 지표를 도입하는 것을 고려하십시오.
  3. 다양한 시장 변동 특성에 대한 적응 변수 개발
  4. 트랜잭션 시간대에 대한 필터를 추가합니다.
  5. 더 지능적인 포지션 관리 시스템을 개발

요약하다

이 전략은 다중 기술 지표와 시간 주기를 결합하여 완전한 거래 시스템을 구축한다. 그것은 명확한 입출장 조건을 포함할 뿐만 아니라, 완벽한 위험 관리 메커니즘을 제공한다. 실제 응용에서는 특정 시장 상황에 따라 변수를 최적화하는 것이 여전히 필요하지만, 전체 프레임 워크는 실용성과 확장성이 좋다.

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

//@version=5
//Created by Nasser mahmoodsani' all rights reserved
// E-mail : [email protected]

strategy("UT Bot Strategy with T/P and S/L and Trend EMA", overlay=true)

// Inputs
along = input(1, title='Key Value (Sensitivity - Long)', group="LONG")
clong = input(10, title='ATR Period (Long)', group="LONG")
h = input(true, title='Signals from Heikin Ashi Candles')
ashort = input(7, title='Key Value (Sensitivity - Short)', group="SHORT")
cshort = input(2, title='ATR Period (Short)', group="SHORT")
tradeType = input.string("Both", title="Trade Type", options=["Buy Only", "Sell Only", "Both"])
tp1_percent = input.float(0.5, title="TP1 Percentage", step=0.1, group="TP Settings") // TP1 % input
tp2_percent = input.float(1.0, title="TP2 Percentage", step=0.1, group="TP Settings") // TP2 % input
sl_percent = input.float(1.0, title="Stop Loss Percentage", step=0.1, group="TP Settings") // SL % input
sl_in_percent = input(true, title="Use Stop Loss in Percentage", group="TP Settings")
tp1_qty = input.float(0.5, title="Take Profit 1 Quantity (as % of position size)", minval=0.0, maxval=1.0, step=0.1)
tp2_qty = input.float(0.5, title="Take Profit 2 Quantity (as % of position size)", minval=0.0, maxval=1.0, step=0.1)

// Check that total quantities for TPs do not exceed 100%
if tp1_qty + tp2_qty > 1
    runtime.error("The sum of Take Profit quantities must not exceed 100%.")

// Calculate 50 EMA from 5-Minute Timeframe
trendEmaPeriod = 50
trendEma_5min = request.security(syminfo.tickerid, "5", ta.ema(close, trendEmaPeriod))
plot(trendEma_5min, title="Trend EMA (5-Min)", color=color.blue, linewidth=2)

// Calculations 
xATRlong = ta.atr(clong)
xATRshort = ta.atr(cshort)
nLosslong = along * xATRlong
nLossshort = ashort * xATRshort

src = h ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close) : close

// LONG
var float xATRTrailingStoplong = na
var float stopLossLong = na
var float takeProfit1 = na
var float takeProfit2 = na

iff_1long = src > nz(xATRTrailingStoplong[1], 0) ? src - nLosslong : src + nLosslong
iff_2long = src < nz(xATRTrailingStoplong[1], 0) and src[1] < nz(xATRTrailingStoplong[1], 0) ? math.min(nz(xATRTrailingStoplong[1]), src + nLosslong) : iff_1long
xATRTrailingStoplong := src > nz(xATRTrailingStoplong[1], 0) and src[1] > nz(xATRTrailingStoplong[1], 0) ? math.max(nz(xATRTrailingStoplong[1]), src - nLosslong) : iff_2long

buy = src > xATRTrailingStoplong and ta.crossover(ta.ema(src, 21), xATRTrailingStoplong) and close > trendEma_5min

if buy and (tradeType == "Buy Only" or tradeType == "Both")
    takeProfit1 := close * (1 + tp1_percent / 100)
    takeProfit2 := close * (1 + tp2_percent / 100)

    // Calculate stop loss based on percentage or ATR
    if sl_in_percent
        stopLossLong := close * (1 - sl_percent / 100)
    else
        stopLossLong := close - nLosslong

    strategy.entry("Long", strategy.long)
    strategy.exit("Take Profit 1", from_entry="Long", limit=takeProfit1, qty=strategy.position_size * tp1_qty)
    strategy.exit("Take Profit 2", from_entry="Long", limit=takeProfit2, qty=strategy.position_size * tp2_qty)
    strategy.exit("Stop Loss", from_entry="Long", stop=stopLossLong, qty=strategy.position_size)

    // // Create Position Projectile for Long
    // var line tpLineLong1 = na
    // var line tpLineLong2 = na
    // var line slLineLong = na
    // var label entryLabelLong = na

    // // Update projectile on entry
    // line.delete(tpLineLong1)
    // line.delete(tpLineLong2)
    // line.delete(slLineLong)
    // label.delete(entryLabelLong)

    // tpLineLong1 := line.new(x1=bar_index, y1=takeProfit1, x2=bar_index + 1, y2=takeProfit1, color=color.green, width=2, style=line.style_solid)
    // tpLineLong2 := line.new(x1=bar_index, y1=takeProfit2, x2=bar_index + 1, y2=takeProfit2, color=color.green, width=2, style=line.style_dashed)
    // slLineLong := line.new(x1=bar_index, y1=stopLossLong, x2=bar_index + 1, y2=stopLossLong, color=color.red, width=2, style=line.style_solid)

// SHORT
var float xATRTrailingStopshort = na
var float stopLossShort = na
var float takeProfit1Short = na
var float takeProfit2Short = na

iff_1short = src > nz(xATRTrailingStopshort[1], 0) ? src - nLossshort : src + nLossshort
iff_2short = src < nz(xATRTrailingStopshort[1], 0) and src[1] < nz(xATRTrailingStopshort[1], 0) ? math.min(nz(xATRTrailingStopshort[1]), src + nLossshort) : iff_1short
xATRTrailingStopshort := src > nz(xATRTrailingStopshort[1], 0) and src[1] > nz(xATRTrailingStopshort[1], 0) ? math.max(nz(xATRTrailingStopshort[1]), src - nLossshort) : iff_2short

sell = src < xATRTrailingStopshort and ta.crossover(xATRTrailingStopshort, ta.ema(src, 21)) and close < trendEma_5min

if sell and (tradeType == "Sell Only" or tradeType == "Both")
    takeProfit1Short := close * (1 - tp1_percent / 100)
    takeProfit2Short := close * (1 - tp2_percent / 100)

    // Calculate stop loss based on percentage or ATR
    if sl_in_percent
        stopLossShort := close * (1 + sl_percent / 100)
    else
        stopLossShort := close + nLossshort

    strategy.entry("Short", strategy.short)
    strategy.exit("Take Profit 1 Short", from_entry="Short", limit=takeProfit1Short, qty=strategy.position_size * tp1_qty)
    strategy.exit("Take Profit 2 Short", from_entry="Short", limit=takeProfit2Short, qty=strategy.position_size * tp2_qty)
    strategy.exit("Stop Loss Short", from_entry="Short", stop=stopLossShort, qty=strategy.position_size)

    // Create Position Projectile for Short
    // var line tpLineShort1 = na
    // var line tpLineShort2 = na
    // var line slLineShort = na
    // var label entryLabelShort = na

    // // Update projectile on entry
    // line.delete(tpLineShort1)
    // line.delete(tpLineShort2)
    // line.delete(slLineShort)
    // label.delete(entryLabelShort)

    // tpLineShort1 := line.new(x1=bar_index, y1=takeProfit1Short, x2=bar_index + 1, y2=takeProfit1Short, color=color.green, width=2, style=line.style_solid)
    // tpLineShort2 := line.new(x1=bar_index, y1=takeProfit2Short, x2=bar_index + 1, y2=takeProfit2Short, color=color.green, width=2, style=line.style_dashed)
    // slLineShort := line.new(x1=bar_index, y1=stopLossShort, x2=bar_index + 1, y2=stopLossShort, color=color.red, width=2, style=line.style_solid)

// Updating Stop Loss after hitting Take Profit 1
if buy and close >= takeProfit1
    strategy.exit("Adjusted Stop Loss", from_entry="Long", stop=close)

// Updating Stop Loss after hitting Take Profit 1 for Short
if sell and close <= takeProfit1Short
    strategy.exit("Adjusted Stop Loss Short", from_entry="Short", stop=close)