이동 평균 캔들스틱과 슈퍼 트렌드 스톱 로스를 기반으로 한 트렌드 추적 전략


생성 날짜: 2023-09-13 18:07:54 마지막으로 수정됨: 2023-09-13 18:07:54
복사: 1 클릭수: 694
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

이 전략의 이름은 는 이동평균 K선과 오버스트로핑의 트렌드 추적 전략 이다. 이 전략은 이동평균을 사용하여 트렌드 K선을 그리고, 오버스트로핑 메커니즘과 결합하여 거래 신호를 생성하여 트렌드를 추적한다.

특히, 전략의 거래 논리는 다음과 같습니다.

  1. 이동 평균선으로 개시 가격과 하락 가격을 계산하고, 트렌드 K 선을 도출한다.

  2. 트렌드 K 라인에서 초트렌드 스톱 기술을 적용하여 오비스 및 오피스 스톱을 얻습니다.

  3. 가격이 다수 중지 지점을 돌파 할 때, 구매 신호를 생성합니다. 가격이 공백 중지 지점을 돌파 할 때, 판매 신호를 생성합니다.

  4. 더 높은 시간 주기에서의 연간 최고 가격과 최저 가격을 판단하여, 흔들리는 시장에서 너무 많은 무효 신호를 피한다.

  5. 초상조각이 역전될 때, 평점조각.

이 전략의 장점은 여러 가지 기술 지표를 동시에 통합하여 판단의 정확도를 높이는 것이다. 그러나 이동 평균선과 초상향 상쇄의 파라미터는 모두 최적화가 필요하다. 상쇄 전략은 필수적이다.

전체적으로, 지표와 모델의 통합된 응용은 단일 지표의 결함을 어느 정도 보완하지만, 어떤 전략도 완벽할 수 없습니다. 거래자는 여전히 시장 변화에 대응하기 위해 충분한 유연성을 유지해야합니다.

전략 소스 코드
/*backtest
start: 2023-01-01 00:00:00
end: 2023-04-14 00:00:00
period: 1d
basePeriod: 1h
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/
// © HeWhoMustNotBeNamed

//@version=4
strategy("MA Candles Supertrend Strategy", shorttitle="MACSTS", overlay=true, initial_capital = 20000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)

MAType = input(title="Moving Average Type", defval="rma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
LoopbackBars = input(20, step=10)

AtrMAType = input(title="Moving Average Type", defval="rma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
AtrLength = input(30, step=10)
AtrMult = input(1)
adoptiveWicks = false // does not work
wicks = input(true)

dThreshold = input(0.2, step=0.1, maxval=1)
rThreshold = input(0.7, step=0.1, maxval=1)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time)
inDateRange = true
strategy.risk.allow_entry_in(tradeDirection)

f_getMovingAverage(source, MAType, length)=>
    ma = sma(source, length)
    if(MAType == "ema")
        ma := ema(source,length)
    if(MAType == "hma")
        ma := hma(source,length)
    if(MAType == "rma")
        ma := rma(source,length)
    if(MAType == "vwma")
        ma := vwma(source,length)
    if(MAType == "wma")
        ma := wma(source,length)
    ma

f_secureSecurity(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on)

f_getYearlyHighLowCondition()=>
    yhighrange = f_secureSecurity(syminfo.tickerid, '12M', high, 1) 
    ylowrange = f_secureSecurity(syminfo.tickerid, '12M', low, 1)
    yearlyHighCondition = close > yhighrange*(1-dThreshold) or close > ylowrange*(1+rThreshold)
    yearlyLowCondition = close < ylowrange*(1+dThreshold) or close < yhighrange*(1-rThreshold)
    [yearlyHighCondition, yearlyLowCondition]


f_getSupertrend(oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks)=>
    truerange = max(oHigh, oClose[1]) - min(oLow, oClose[1])
    
    averagetruerange = f_getMovingAverage(truerange, AtrMAType, AtrLength)
    atr = averagetruerange * AtrMult

    longWicks = (adoptiveWicks and (close < oClose)) or wicks
    shortWicks = (adoptiveWicks and (close > oClose)) or wicks
    longStop = oClose - atr
    longStopPrev = nz(longStop[1], longStop)
    longStop := (longWicks ? oLow[1] : oClose[1]) > longStopPrev ? max(longStop, longStopPrev) : longStop
    
    shortStop = oClose + atr
    shortStopPrev = nz(shortStop[1], shortStop)
    shortStop := (shortWicks ? oHigh[1] : oClose[1]) < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
    
    dir = 1
    dir := nz(dir[1], dir)
    dir := dir == -1 and (longWicks ? oHigh : oClose) > shortStopPrev ? 1 : dir == 1 and (shortWicks[1]? oLow : oClose) < longStopPrev ? -1 : dir
    

    [dir, longStop, shortStop]

oOpen = f_getMovingAverage(open, MAType, LoopbackBars)
oClose = f_getMovingAverage(close, MAType, LoopbackBars)
oHigh = f_getMovingAverage(high, MAType, LoopbackBars)
oLow = f_getMovingAverage(low, MAType, LoopbackBars)

colorByPreviousClose = false
candleColor = colorByPreviousClose ?
                 (oClose[1] < oClose ? color.green : oClose[1] > oClose ? color.red : color.silver) : 
                 (oOpen < oClose ? color.green : oOpen > oClose ? color.red : color.silver)
plotcandle(oOpen, oHigh, oLow, oClose, 'Oscilator Candles', color = candleColor)

[yearlyHighCondition, yearlyLowCondition] =  f_getYearlyHighLowCondition()
[dir, longStop, shortStop] = f_getSupertrend(oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks)
trailingStop = dir == 1? longStop : shortStop
trendColor = dir == 1? color.green: color.red
plot(trailingStop, title="TrailingStop", color=trendColor, linewidth=2, style=plot.style_linebr)

longCondition = close > shortStop and dir == 1 and yearlyHighCondition
shortCondition = close < longStop and dir == -1 and yearlyLowCondition

exitLongCondition = dir == -1
exitShortCondition = dir == 1

strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Long", strategy.long, when=longCondition, oca_name="oca_buy")
strategy.close("Long", when=exitLongCondition)
strategy.entry("Short", strategy.short, when=shortCondition, oca_name="oca_sell")
strategy.close("Short", when=exitShortCondition)