트리플MACD 크로스오버와 상대적 강도 지수를 결합한 고주파 암호화폐 거래 전략

저자:차오장, 날짜: 2024-03-22 15:41:46
태그:

img

전반적인 설명

이 문서에서는 트립 MACD 크로스오버와 상대적 강도 지수 (RSI) 를 결합한 고주파 암호화폐 거래 전략을 소개합니다. 이 전략은 다른 매개 변수와 신호 라인을 평균하는 MACD 지표 세 세트를 사용하며 최적의 구매 및 판매 시기를 결정하기 위해 RSI 지표를 통합합니다. 이 전략은 1 분 시간 프레임에서 자동화 된 거래를 위해 고안되어 있으며, 긴 거래를만 고려합니다. 또한 전략은 선형 회귀를 사용하여 시장의 통합 단계를 식별하고 불안정한 시장 조건에서 거래를 피합니다.

전략 원칙

이 전략의 핵심은 다른 매개 변수와 함께 세 개의 MACD 지표를 사용하여 다양한 시간 스케일에 트렌드 신호를 캡처하는 것입니다. 이 세 가지 MACD 지표의 신호 라인을 평균화함으로써 소음을 효과적으로 부드럽게하여 더 신뢰할 수있는 거래 신호를 제공할 수 있습니다. 동시에 RSI 지표는 상승 추세의 강도를 확인하는 데 사용됩니다. 세 가지 MACD 지표가 모두 상승 신호를 표시하고 RSI 지표가 상승 추세의 강도를 확인 할 때만 전략이 구매 신호를 생성합니다.

또한, 전략은 시장의 통합 단계를 식별하기 위해 선형 회귀를 사용합니다. 촛불의 몸 길이에 대한 상위 및 하위 그림자 길이의 비율을 계산함으로써 현재 시장이 통합 상태에 있는지 결정할 수 있습니다. 상위 및 하위 그림자의 길이가 몸 길이의 두 배 이상이면 시장이 통합 단계로 간주되며 전략은이 기간 동안 거래를 피합니다.

이점 분석

  1. 멀티 타임프레임 분석: 다른 매개 변수와 함께 MACD 지표 세 세트를 사용하여 전략은 다양한 시간 스케일에 트렌드 신호를 캡처하여 거래의 정확성과 신뢰성을 향상시킬 수 있습니다.

  2. 신호 평형화: 세 가지 MACD 지표의 신호 라인을 평균화하면 하나의 지표에서 생성될 수 있는 잘못된 신호를 피하여 소음을 효과적으로 평형화합니다.

  3. 트렌드 확인: 상승 트렌드의 강도를 확인하기 위해 RSI 지표를 통합하면 거래 신호의 신뢰성이 더욱 향상됩니다.

  4. 통합 식별: 시장에서 통합 단계를 식별하기 위해 선형 회귀를 사용하면 전략이 불안정한 시장 조건에서 거래를 피하고 전략의 위험을 줄일 수 있습니다.

  5. 자동 거래: 전략은 1분 시간 내에 자동 거래를 위해 설계되어 시장 변화에 신속한 대응과 효율적인 거래 실행을 가능하게 합니다.

위험 분석

  1. 매개 변수 최적화: 전략은 세 가지 MACD 지표의 빠르고 느린 라인 기간 및 RSI 지표의 기간과 같은 여러 매개 변수를 포함합니다. 이러한 매개 변수 선택은 전략의 성능에 중요한 영향을 미칩니다. 매개 변수가 적절히 최적화되지 않으면 전략의 성능이 감소 할 수 있습니다.

  2. 과도한 적합성 위험: 전략은 특정 역사적 데이터에 잘 수행 할 수 있지만 실제 적용에서 시장 변화에 적응하지 못할 수 있으며 전략 실패로 이어질 수 있습니다.

  3. 블랙 스완 이벤트: 전략은 주로 기술 지표에 의존하고 있으며 극한 시장 조건에서 나쁜 성과를 초래할 수있는 중요한 근본 이벤트에 적절하게 대응하지 않을 수 있습니다.

최적화 방향

  1. 동적 매개 변수 조정: 다른 시장 환경에 적응하기 위해 시장 조건의 변화에 따라 MACD 지표의 빠른 및 느린 라인 기간 및 RSI 지표의 기간과 같은 전략의 매개 변수를 동적으로 조정합니다.

  2. 추가 지표를 포함: 기존 MACD 및 RSI 지표 외에도 거래 신호의 정확성과 신뢰성을 더욱 향상시키기 위해 볼링거 밴드 및 이동 평균과 같은 다른 기술적 지표를 포함하는 것을 고려하십시오.

  3. 리스크 관리 최적화: 전략의 전체 리스크를 줄이기 위해 동적 스톱 로스 및 포지션 관리와 같은 전략에서 보다 포괄적인 리스크 관리 조치를 시행합니다.

  4. 기계 학습 최적화: 신경 네트워크 및 지원 벡터 기계와 같은 기계 학습 알고리즘을 활용하여 전략의 매개 변수 및 거래 규칙을 최적화하여 전략의 적응력과 견고성을 향상시킵니다.

결론

이 문서에서는 트리플MACD 크로스오버와 RSI 지표를 결합한 고주파 암호화폐 거래 전략을 소개합니다. 이 전략은 다른 매개 변수와 RSI 지표와 함께 세 개의 MACD 지표 세트를 사용하여 시장의 통합 단계를 식별하는 선형 회귀를 활용하면서 신뢰할 수있는 거래 신호를 생성하며, 불안정한 시장 조건에서 거래를 피합니다. 이 전략의 장점은 멀티 타임프레임 분석, 신호 평형화, 확증, 통합 트렌드 식별 및 자동화 거래에 있습니다. 그러나 매개 변수 최적화, 오버피팅 및 블랙 스완 이벤트와 같은 거래 위험도 직면합니다. 미래에 전략은 매개 변수 조정, 추가 지표 통합, 위험 관리 최적화 및 기계 학습 최적화를 통해 역동적으로 개선 될 수 있습니다. 적응력과 탄력성을 향상시키고 암호화폐 시장의 변화에 더 잘 대처 할 수 있습니다.


/*backtest
start: 2024-02-01 00:00:00
end: 2024-02-29 23:59:59
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
//indicator("Triplle",shorttitle="Triplle MACD", overlay=true, scale = scale.none)
//indicator("Triplle","TrippleMACD",true)
strategy(title="TrippleMACD", shorttitle="TrippleMACD + RSI strategy", format=format.price, precision=4, overlay=true)

// RSI 
ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "Bollinger Bands" => 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)

rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")
showDivergence = input.bool(false, title="Show Divergence", group="RSI Settings")

up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA = ma(rsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"

//rsiPlot = plot(rsi, "RSI", color=#7E57C2)
//plot(rsiMA, "RSI-based MA", color=color.yellow)
//rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
//midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
//rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
//fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green)
//fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill")

//midLinePlot = plot(50, color = na, editable = false, display = display.none)
//fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100),  title = "Overbought Gradient Fill")
//fill(rsiPlot, midLinePlot, 30,  0,  top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0),      title = "Oversold Gradient Fill")

// Divergence
lookbackRight = 5
lookbackLeft = 5
rangeUpper = 60
rangeLower = 5
bearColor = color.red
bullColor = color.green
textColor = color.white
noneColor = color.new(color.white, 100)

plFound = na(ta.pivotlow(rsi, lookbackLeft, lookbackRight)) ? false : true
phFound = na(ta.pivothigh(rsi, lookbackLeft, lookbackRight)) ? false : true
_inRange(cond) =>
	bars = ta.barssince(cond == true)
	rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// Regular Bullish
// rsi: Higher Low

rsiHL = rsi[lookbackRight] > ta.valuewhen(plFound, rsi[lookbackRight], 1) and _inRange(plFound[1])

// Price: Lower Low

priceLL = low[lookbackRight] < ta.valuewhen(plFound, low[lookbackRight], 1)
bullCondAlert = priceLL and rsiHL and plFound
bullCond = showDivergence and bullCondAlert

// plot(
//      plFound ? rsi[lookbackRight] : na,
//      offset=-lookbackRight,
//      title="Regular Bullish",
//      linewidth=2,
//      color=(bullCond ? bullColor : noneColor)
//      )

// plotshape(
// 	 bullCond ? rsi[lookbackRight] : na,
// 	 offset=-lookbackRight,
// 	 title="Regular Bullish Label",
// 	 text=" Bull ",
// 	 style=shape.labelup,
// 	 location=location.absolute,
// 	 color=bullColor,
// 	 textcolor=textColor
// 	 )

//------------------------------------------------------------------------------
// Regular Bearish
// rsi: Lower High

rsiLH = rsi[lookbackRight] < ta.valuewhen(phFound, rsi[lookbackRight], 1) and _inRange(phFound[1])

// Price: Higher High

priceHH = high[lookbackRight] > ta.valuewhen(phFound, high[lookbackRight], 1)

bearCondAlert = priceHH and rsiLH and phFound
bearCond = showDivergence and bearCondAlert

// plot(
// 	 phFound ? rsi[lookbackRight] : na,
// 	 offset=-lookbackRight,
// 	 title="Regular Bearish",
// 	 linewidth=2,
// 	 color=(bearCond ? bearColor : noneColor)
// 	 )

// plotshape(
// 	 bearCond ? rsi[lookbackRight] : na,
// 	 offset=-lookbackRight,
// 	 title="Regular Bearish Label",
// 	 text=" Bear ",
// 	 style=shape.labeldown,
// 	 location=location.absolute,
// 	 color=bearColor,
// 	 textcolor=textColor
// 	 )
// END RSI

// Getting inputs
stopLuse          = input(1.040)
fast_length = input(title = "Fast Length", defval = 5)
slow_length = input(title = "Slow Length", defval = 8)
fast_length2 = input(title = "Fast Length2", defval = 13)
slow_length2 = input(title = "Slow Length2", defval = 21)
fast_length3 = input(title = "Fast Length3", defval = 34)
slow_length3 = input(title = "Slow Length3", defval = 144)
fast_length4 = input(title = "Fast Length3", defval = 68)
slow_length4 = input(title = "Slow Length3", defval = 288)
src = input(title = "Source", defval = close)
signal_length2 = input.int(title="Signal Smoothing", minval = 1, maxval = 200, defval = 11)
signal_length = input.int(title = "Signal Smoothing",  minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title = "Oscillator MA Type",  defval = "EMA", options = ["SMA", "EMA"])
sma_signal = input.string(title = "Signal Line MA Type", defval = "EMA", options = ["SMA", "EMA"])
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)

fast_ma2 = sma_source == "SMA2" ? ta.sma(src, fast_length2) : ta.ema(src, fast_length2)
slow_ma2 = sma_source == "SMA2" ? ta.sma(src, slow_length2) : ta.ema(src, slow_length2)

fast_ma3 = sma_source == "SMA3" ? ta.sma(src, fast_length3) : ta.ema(src, fast_length3)
slow_ma3 = sma_source == "SMA3" ? ta.sma(src, slow_length3) : ta.ema(src, slow_length3)

fast_ma4 = sma_source == "SMA3" ? ta.sma(src, fast_length3) : ta.ema(src, fast_length3)
slow_ma4 = sma_source == "SMA3" ? ta.sma(src, slow_length3) : ta.ema(src, slow_length3)

macd = fast_ma - slow_ma
macd2 = fast_ma2 - slow_ma2
macd3 = fast_ma3 - slow_ma3
macd4 = fast_ma4 - slow_ma4

signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
signal2 = sma_signal == "SMA" ? ta.sma(macd2, signal_length) : ta.ema(macd2, signal_length)
signal3 = sma_signal == "SMA" ? ta.sma(macd3, signal_length) : ta.ema(macd3, signal_length)
signal4 = sma_signal == "SMA" ? ta.sma(macd4, signal_length) : ta.ema(macd4, signal_length)
//hist = (macd + macd2 + macd3)/1 - (signal + signal2 + signal3)/1
hist = (macd + macd2 + macd3 + macd4)/4 - (signal + signal2 + signal3 + signal4)/4
signal5 = (signal + signal2 + signal3)/3

sma_signal2 = input.bool(title="Simple MA (Signal Line)", defval=true)

lin_reg = input.bool(title="Lin Reg", defval=true)
linreg_length = input.int(title="Linear Regression Length", minval = 1, maxval = 200, defval = 11)

bopen = lin_reg ? ta.linreg(open, linreg_length, 0) : open
bhigh = lin_reg ? ta.linreg(high, linreg_length, 0) : high
blow = lin_reg ? ta.linreg(low, linreg_length, 0) : low
bclose = lin_reg ? ta.linreg(close, linreg_length, 0) : close

shadow = (bhigh - bclose) + (bopen - blow)
body = bclose - bopen
perc = (shadow/body)
cond2 = perc >=2 and bclose+bclose[1]/2 > bopen+bopen[1]/2

r = bopen < bclose

//signal5 = sma_signal2 ? ta.sma(bclose, signal_length) : ta.ema(bclose, signal_length)
plotcandle(r ? bopen : na, r ? bhigh : na, r ? blow: na, r ? bclose : na, title="LinReg Candles", color= color.green, wickcolor=color.green, bordercolor=color.green, editable= true)
plotcandle(r ? na : bopen, r ? na : bhigh, r ? na : blow, r ? na : bclose, title="LinReg Candles", color=color.red, wickcolor=color.red, bordercolor=color.red, editable= true)
//alertcondition(hist[1] >= 0 and hist < 0, title = 'Rising to falling', message = 'The MACD histogram switched from a rising to falling state')
//alertcondition(hist[1] <= 0 and hist > 0, title = 'Falling to rising', message = 'The MACD histogram switched from a falling to rising state')

green = hist >= 0 ? (hist[1] < hist ? "G" : "GL") : (hist[1] < hist ? "RL" : "R")
Buy = green == "G" and green[1] != "G" and green[1] != "GL" and bopen < bclose and rsi < 55.0 //and not cond2
//StopBuy = (green == "R" or green == "RL" or green == "RL") and bopen > bclose and bopen[1] < bclose[1]
StopBuy = bopen > bclose and bopen[1] < bclose[1] and (green == "G" or green == "GL" or green == "R") and bopen[2] < bclose[2] and bopen[3] < bclose[3]
hists = close[3] < close[2] and close[2] < close[1]
//Buy = green == "RL" and hist[0] > -0.07 and hist[0] < 0.00 and rsi < 55.0 and hists
//StopBuy = green == "GL" or green == "R"
alertcondition(Buy, "Long","Покупка в лонг")
alertcondition(StopBuy, "StopLong","Закрытие сделки")

//hline(0, "Zero Line", color = color.new(#787B86, 50))
plot(hist + (close - (close * 0.03)), title = "Histogram", style = plot.style_line, color = (hist >= 0 ? (hist[1] < hist ? #26A69A : #B2DFDB) : (hist[1] < hist ? #FFCDD2 : #FF5252)))
plotshape(Buy ? low : na, 'Buy', shape.labelup, location.belowbar , color=color.new(#0abe40, 50), size=size.small, offset=0)
plotshape(StopBuy ? low : na, 'Buy', shape.cross, location.abovebar , color=color.new(#be0a0a, 50), size=size.small, offset=0)
plot(macd4  + (close - (close * 0.01)),   title = "MACD",   color = #2962FF)
plot(signal5 + (close - (close * 0.01)), title = "Signal", color = #FF6D00)

plotchar(cond2 , char='↓', color = color.rgb(0, 230, 119), text = "-")

if (Buy)
    strategy.entry("long", strategy.long)

// if (startShortTrade)
//     strategy.entry("short", strategy.short)

profitTarget = strategy.position_avg_price * stopLuse
strategy.exit("Take Profit", "long", limit=profitTarget)
// strategy.exit("Take Profit", "short", limit=profitTarget)

더 많은