MACD 기반의 이중 거래 전략

저자:차오장, 날짜: 2023-12-07 17:11:52
태그:

img

전반적인 설명

이 전략은 MACD 지표에 기반한 이중 거래 전략을 구현합니다. MACD에 황금 십자가가있을 때 길게 갈 수 있으며 죽음의 십자가가있을 때 짧게 갈 수 있으며, 일부 유효하지 않은 신호를 제거하기 위해 다른 지표에 기반한 추가 필터를 사용합니다.

전략 원칙

이 전략의 핵심은 MACD 지표를 활용하여 쌍방향 거래를 실현하는 것입니다. 구체적으로, 그것은 빠른 이동 평균, 느린 이동 평균 및 MACD 신호 라인을 계산합니다. 빠른 MA가 느린 MA를 넘을 때, 긴 이동을위한 황금 십자가가 생성됩니다. 빠른 MA가 느린 MA 아래에 넘을 때, 짧은 이동을위한 죽음의 십자가가 생성됩니다.

일부 유효하지 않은 신호를 필터링하기 위해 전략은 필터로 ±30 범위를 설정하여 MACD 히스토그램이 이 범위를 초과할 때만 거래 신호가 활성화됩니다. 또한, 포지션을 닫을 때 MACD 히스토그램의 방향을 판단합니다. 두 개의 연속 히스토그램 바의 방향이 변경될 때만 포지션이 폐쇄됩니다.

장점

  • MACD 지표는 두 방향의 가격 움직임에 민감한 주요 거래 신호로 사용됩니다.
  • 추가 필터는 일부 유효하지 않은 신호를 제거하는 데 도움이됩니다.
  • 포지션을 닫는 두 바 방향 논리는 일부 잘못된 파장을 어느 정도 피합니다.

위험성

  • MACD 지표는 거래 빈도를 높이기 위해 빈번한 거래 신호를 생성하는 경향이 있습니다
  • 하나의 지표에만 의존하면 전략이 신호 지연에 취약합니다.
  • 히스토그램 방향에 기반한 폐쇄 논리는 충분히 엄격하지 않습니다, 일부 신호를 놓칠 위험이 있습니다

최적화 방향

  • KDJ, 볼링거 밴드 등과 같은 신호 확인을 위한 다른 지표와 결합하는 것을 고려하십시오.
  • KD와 같은 MACD를 대체하기 위해 더 고급 인디케이터를 연구하십시오.
  • 단일 거래 손실을 제어하기 위해 손해를 멈추고 이익을 취함으로써 폐쇄 논리를 최적화하십시오.

결론

요약하자면, 이것은 기본적으로 실행 가능한 이방향 거래 전략입니다. MACD 지표의 장점을 활용하고 신호 품질을 제어하기 위해 몇 가지 필터를 추가합니다. 그러나 MACD 자체에도 몇 가지 문제가 있습니다. 전략을 더 신뢰할 수 있도록 라이브 거래에서 추가 테스트 및 최적화가 여전히 필요합니다. 전반적으로,이 전략은 이방향 거래 전략의 기초를 마련하며 강력한 양적 거래 전략이 될 수 있도록 점차적으로 최적화 될 수 있습니다.

]


/*backtest
start: 2022-11-30 00:00:00
end: 2023-12-06 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=3

//Created by user ChrisMoody updated 4-10-2014
//Regular MACD Indicator with Histogram that plots 4 Colors Based on Direction Above and Below the Zero Line
//Update allows Check Box Options, Show MacD & Signal Line, Show Change In color of MacD Line based on cross of Signal Line.
//Show Dots at Cross of MacD and Signal Line, Histogram can show 4 colors or 1, Turn on and off Histogram.
//Special Thanks to that incredible person in Tech Support whoem I won't say you r name so you don't get bombarded with emails
//Note the feature Tech Support showed me on how to set the default timeframe of the indicator to the chart Timeframe, but also allow you to choose a different timeframe.
//By the way I fully disclose that I completely STOLE the Dots at the MAcd Cross from "TheLark"

strategy("MACD Strategy", overlay=false)
// study(title="CM_MacD_Ult_MTF", shorttitle="CM_Ult_MacD_MTF")
source = close
useCurrentRes = input(true, title="Use Current Chart Resolution?")
resCustom = input(title="Use Different Timeframe? Uncheck Box Above", defval="60")
smd = input(true, title="Show MacD & Signal Line? Also Turn Off Dots Below")
sd = input(true, title="Show Dots When MacD Crosses Signal Line?")
sh = input(true, title="Show Histogram?")
macd_colorChange = input(true,title="Change MacD Line Color-Signal Line Cross?")
hist_colorChange = input(true,title="MacD Histogram 4 Colors?")

res = useCurrentRes ? timeframe.period : resCustom

fastLength = input(12, minval=1), slowLength=input(26,minval=1)
signalLength=input(9,minval=1)

fastMA = ema(source, fastLength)
slowMA = ema(source, slowLength)

macd = fastMA - slowMA
signal = sma(macd, signalLength)
hist = macd - signal

outMacD = request.security(syminfo.tickerid, res, macd)
outSignal = request.security(syminfo.tickerid, res, signal)
outHist = request.security(syminfo.tickerid, res, hist)

histA_IsUp = outHist > outHist[1] and outHist > 0
histA_IsDown = outHist < outHist[1] and outHist > 0
histB_IsDown = outHist < outHist[1] and outHist <= 0
histB_IsUp = outHist > outHist[1] and outHist <= 0

//MacD Color Definitions
macd_IsAbove = outMacD >= outSignal
macd_IsBelow = outMacD < outSignal



// strategy.entry("Long", strategy.long, 1, when = shouldPlaceLong) 
       
// strategy.close("Long", shouldExitLong)
    

// strategy.entry("Short", strategy.short, 1, when = shouldPlaceShort) 
       
// strategy.close("Short", shouldExitShort)
    
    
isWithinZeroMacd = outHist < 30 and outHist > -30 

delta = hist
// shouldExitShort = false//crossover(delta, 0)    
// shouldExitLong = false//crossunder(delta, 0)

// if(crossover(delta, 0))// and not isWithinZeroMacd)
//     strategy.entry("Long", strategy.long, comment="Long")

// if (crossunder(delta, 0))// and not isWithinZeroMacd)
//     strategy.entry("Short", strategy.short, comment="Short")
    
shouldPlaceLong = crossover(delta, 0)
    
strategy.entry("Long", strategy.long, 1, when = shouldPlaceLong) 

shouldExitLong = not histA_IsUp and histA_IsDown

shouldExitShort = not histA_IsUp and not histA_IsDown and not histB_IsDown and histB_IsUp

shouldPlaceShort = crossunder(delta, 0)
strategy.entry("Short", strategy.short, 1, when = shouldPlaceShort) 
       
// plot_color = gray
plot_color = if(hist_colorChange)
	if(histA_IsUp)
	    aqua
	else
		if(histA_IsDown)
			//need to sell
// 			if(not isWithinZeroMacd)
// 			shouldExitLong = true
			    //   strategy.entry("Short", strategy.short, comment="Short")
			
			blue
		else
			if(histB_IsDown)
				red 
			else
				if(histB_IsUp)
					//need to buy
				// 	if(not isWithinZeroMacd)
				// 	shouldExitShort = true
					   // strategy.entry("Long", strategy.long, comment="Long")
					    
					    
					maroon
				else
					yellow
else
	gray


// plot_color = hist_colorChange ? histA_IsUp ? aqua : histA_IsDown ? blue : histB_IsDown ? red : histB_IsUp ? maroon :yellow :gray
macd_color = macd_colorChange ? macd_IsAbove ? lime : red : red
signal_color = macd_colorChange ? macd_IsAbove ? orange : orange : lime

circleYPosition = outSignal

plot(smd and outMacD ? outMacD : na, title="MACD", color=macd_color, linewidth=4)
plot(smd and outSignal ? outSignal : na, title="Signal Line", color=signal_color, style=line ,linewidth=2)
plot(sh and outHist ? outHist : na, title="Histogram", color=plot_color, style=histogram, linewidth=4)
plot(sd and cross(outMacD, outSignal) ? circleYPosition : na, title="Cross", style=circles, linewidth=4, color=macd_color)

// plot( isWithinZeroMacd ? outHist : na, title="CheckSmallHistBars", style=circles, linewidth=4, color=black)

hline(0, '0 Line',  linewidth=2, color=white)




strategy.close("Short", shouldExitShort)
strategy.close("Long", shouldExitLong)

// fastLength = input(12)
// slowlength = input(26)
// MACDLength = input(9)

// MACD = ema(close, fastLength) - ema(close, slowlength)
// aMACD = ema(MACD, MACDLength)
// delta = MACD - aMACD


// if (crossover(delta, 0))
   // strategy.entry("MacdLE", strategy.long, comment="MacdLE")

//if last two macd bars are higher than current, close long position

// if (crossunder(delta, 0))
   // strategy.entry("MacdSE", strategy.short, comment="MacdSE")

//if last two macd bars are higher than current, close long position

// plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)

더 많은