볼링거 밴드 ATR 트레일링 스톱 전략

저자:차오장, 날짜: 2024-01-03 11:20:06
태그:

img

전반적인 설명

이 전략은 볼링거 밴드 지표와 평균 참 범위 (ATR) 지표를 결합하여 후속 스톱 로스 함수를 가진 브레이크아웃 거래 전략을 형성합니다. 가격은 지정된 표준 오차의 볼링거 밴드를 통과 할 때 거래 신호가 생성됩니다. 동시에 ATR 지표는 스톱 로스를 계산하고 리스크 / 리워드 비율을 제어하기 위해 이익을 취하기 위해 사용됩니다. 또한 전략에는 시간 필터 및 매개 변수 최적화와 같은 기능이 있습니다.

전략 논리

단계 1, 중간 대역, 상위 대역 및 하위 대역을 계산합니다. 중간 대역은 가격의 간단한 이동 평균 (SMA), 상위 대역과 하위 대역은 가격 표준편차의 배수입니다. 가격이 하위 대역에서 상향으로 돌파하면 길게 이동합니다. 가격이 상위 대역에서 하향으로 돌파하면 짧게 이동합니다.

단계 2, ATR 지표를 계산합니다. ATR 지표는 가격의 평균 변동성을 반영합니다. ATR 값에 따라 긴 위치와 짧은 위치의 스톱 손실을 설정합니다. 동시에 ATR 값을 기반으로 수익 입장을 설정하여 위험 / 보상 비율을 제어합니다.

단계 3, 주요 뉴스 사건의 급격한 변동을 피하기 위해 지정된 시간 내에만 거래하기 위해 시간 필터를 사용하십시오.

4단계, 트레일링 스톱 메커니즘. 더 많은 수익을 확보하기 위해 최신 ATR 위치에 따라 스톱 손실을 조정하십시오.

이점 분석

  1. 볼링거 대역 자체는 단일 이동 평균보다 가격 평형을 더 효과적으로 반영합니다.

  2. ATR는 각 거래의 위험/이익 비율을 제어합니다.

  3. 트레일링 스톱은 수익을 확보하기 위해 시장 변동성에 따라 자동으로 조정됩니다.

  4. 풍부한 전략 매개 변수는 높은 사용자 정의성을 가능하게합니다.

위험 분석

  1. 시장이 고집합되면 여러 개의 작은 손실이 발생할 수 있습니다.

  2. 볼링거 밴드 크로스오버로 실패한 브레이크오웃 역전

  3. 야간 세션과 주요 뉴스 이벤트와 관련된 위험이 더 높습니다.

대책:

  1. 위험 관리 원칙을 엄격히 따르고 거래당 손실을 통제합니다.
  2. 승률을 높이기 위해 매개 변수를 최적화합니다.
  3. 고위험 기간을 피하기 위해 시간 필터를 적용하십시오.

최적화 방향

  1. 서로 다른 매개 변수 조합을 테스트합니다.
  2. OBV와 같은 타이밍 표시기를 추가합니다.
  3. 머신러닝 모델을 적용합니다.

결론

이 전략은 트렌드 평형 및 브레이크아웃 방향을 결정하기 위해 볼링거 밴드, 위험 / 보상 비율을 제어하기 위해 스톱 로스를 계산하고 수익을 취하기 위해 ATR 및 수익을 잠금하기 위해 트레일링 스톱을 결합합니다. 이 전략의 장점은 높은 사용자 정의성, 제어 가능한 위험 및 단기 내일 거래에 적합합니다. 매개 변수 최적화 및 기계 학습을 통해 승률 및 수익성에 대한 추가 개선이 가능합니다.


/*backtest
start: 2023-12-26 00:00:00
end: 2024-01-02 00:00:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sadeq_haddadi

//@version=5

strategy('Bollinger Bands + ATR / trail- V2', overlay=true ) // Interactive Brokers rate)



//date and time
startDate   = input(title="Start Date", defval=timestamp("01 Aug 2023 00:00 +0000"), tooltip="Date & time to begin analysis",group = 'Time Filter')
endDate     = input(title="End Date", defval=timestamp("1 Jan 2099 00:00 +0000"), tooltip="Date & time to stop analysis")
timeSession = input(title="Time Session To Analyze", defval="0300-1700", tooltip="Time session to analyze")
inSession(sess) => true

// indicators 

length = input.int(20, minval=1,group = 'Bollinger Band')
maType = input.string("SMA", "Basis MA Type", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
src = input(close, title="Source")
mult1 = input.float(2.0, minval=0.001, maxval=50, title="StdDev1")
mult2 = input.float(3.0, minval=0.001, maxval=50, title="StdDev2")

ma(source, length, _type) =>
    switch _type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

basis = ma(src, length, maType)
dev1 = mult1 * ta.stdev(src, length)
dev2 = mult2 * ta.stdev(src, length)
upper1 = basis + dev1
lower1 = basis - dev1
upper2 = basis + dev2
lower2 = basis - dev2
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#2962FF, offset = offset,linewidth=2)
p1 = plot(upper1, "Upper", color=color.new(color.white,50), offset = offset,linewidth=2)
p2 = plot(lower1, "Lower", color=color.new(color.white,50), offset = offset,linewidth=2)
p3 = plot(upper2, "Upper", color=color.new(color.white,80), offset = offset,linewidth=1)
p4 = plot(lower2, "Lower", color=color.new(color.white,80), offset = offset,linewidth=1)

fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
fill(p3, p4, title = "Background", color=color.rgb(33, 150, 243, 95))

show_crosses = input(false, "Show Cross the Bands?")

plotshape(show_crosses and ta.crossover(close, upper2)  ? src : na, "S", style = shape.triangledown, location =location.abovebar, color = color.yellow, size = size.tiny)
plotshape(show_crosses and ta.crossunder(low, lower2) ? src : na ,"L", style = shape.triangleup, location =  location.belowbar, color = color.purple, size = size.tiny)

second_entry = input(true, "Show second deviation entry point?")

//atr

length_ATR = input.int(title="Length", defval=5, minval=1,group = 'ATR')
smoothing = input.string(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
m = input.float(1, "Multiplier")
src1 = input(high)
src2 = input(low)
pline = input.bool(title = 'show ATR lines ?', defval=false)



ma_function(source, length_ATR) =>
	if smoothing == "RMA"
		ta.rma(source, length_ATR)
	else
		if smoothing == "SMA"
			ta.sma(source, length_ATR)
		else
			if smoothing == "EMA"
				ta.ema(source, length_ATR)
			else
				ta.wma(source, length_ATR)
				
a = ma_function(ta.tr(true), length_ATR) * m
x = ma_function(ta.tr(true), length_ATR) * m + src1
x2 = src2 - ma_function(ta.tr(true), length_ATR) * m

PP1 = plot(pline ? x :na , title = "ATR Short Stop Loss", color= color.new(color.red,20) )
PP2 = plot(pline ? x2:na , title = "ATR Long Stop Loss",  color=color.new(color.green,20) )

Tp_to_Sl = input.float(1.5, "TP/SL")
candle_size =  input.float(10, "candle/pip")
distance_source =  input.float(1.5, "distance to midline/pip")
//strategy

buyCondition = low[2] < lower1 and  ta.crossover(close[1], lower1)  and strategy.position_size == 0 and (close[1] - open[1]) < candle_size * 0.0001 and close > open and ( basis - close) > distance_source * 0.0001

sellCondition = high[2] > upper1 and ta.crossunder(close[1], upper1)  and strategy.position_size == 0 and (open[1] - close[1]) < candle_size * 0.0001 and close < open  and (close - basis) > distance_source * 0.0001
//
buyCondition2 = low[2] < lower2 and  ta.crossover(close[1], lower2)  and (close[1] - open[1]) < candle_size * 0.0001 and close > open and ( basis - close) > distance_source * 0.0001
sellCondition2 = high[2] > upper2 and ta.crossunder(close[1], upper2)   and (open[1] - close[1]) < candle_size * 0.0001 and close < open  and (close - basis) > distance_source * 0.0001

plotshape(second_entry and  sellCondition2 ? src : na, "S", style = shape.triangledown, location =location.abovebar, color = color.rgb(241, 153, 177), size = size.tiny)
plotshape(second_entry and buyCondition2 ? src : na ,"L", style = shape.triangleup, location =  location.belowbar, color = color.rgb(177, 230, 168), size = size.tiny)
//
since_buy  =ta.barssince(buyCondition)
since_sell =ta.barssince(sellCondition)
entry_price = ta.valuewhen(buyCondition or sellCondition, src, 0)

sl_long = ta.valuewhen(buyCondition, x2[1], 0)
sl_short = ta.valuewhen(sellCondition, x[1], 0)
buyprofit = entry_price + (Tp_to_Sl*( entry_price - sl_long))
sellprofit= entry_price + (Tp_to_Sl*( entry_price - sl_short))

//alert_massage = "new strategy position is {{strategy.position_size}}"
//prof = ta.crossover(high,upper1)
//buyexit=ta.valuewhen(prof,upper1,0)

if buyCondition and inSession(timeSession)

    strategy.entry( id = "long", direction = strategy.long , alert_message='Open Long Position' )

if sellCondition and inSession(timeSession)
   
    strategy.entry(id= "short", direction = strategy.short, alert_message='Open Short Position')

//trail-stop loss
use_trailing = input.bool(title = 'use trailing stop loss?', defval=true)
pricestop_long=0.00
pricestop_short=100000.00
if (strategy.position_size > 0)
   
    if use_trailing == false
        pricestop_long := sl_long
    else
        pricestop_long := math.max (x2, pricestop_long[1]) //trail - long

if (strategy.position_size < 0)
   
    if use_trailing == false
        pricestop_short := sl_short
    else
        pricestop_short := math.min (x, pricestop_short[1])  // trail - short 

if strategy.position_size > 0 
   
    strategy.exit(id = 'close', limit =  buyprofit , stop = pricestop_long  )

if strategy.position_size < 0 

    strategy.exit(id = 'close', limit = sellprofit  , stop = pricestop_short  )

alertcondition(buyCondition or sellCondition, 'Enter_position')



더 많은