이중 이동 평균 크로스오버 모멘텀 전략

저자:차오장, 날짜: 2023-11-16 17:25:13
태그:

img

전반적인 설명

이 전략은 이중 이동 평균 크로스오버 원리를 활용하고, 트렌드 판단과 크로스 배경 강조를 위해 MACD 지표를 결합하고, 시장의 중장기 트렌드를 캡처하는 것을 목표로 패턴 점으로 항목을 확인합니다. 주요 논리는 이동 평균의 방향이 변경되면 입력하고, MACD 배경 색으로 교차점을 구별하고, MACD 히스토그램 색상의 변화에 의해 모멘텀을 결정하는 것입니다.

전략 논리

이 전략은 빠른 EMA와 느린 EMA를 사용하여 이중 이동 평균을 구축하고 빠른 라인과 느린 라인의 교차를 기반으로 트렌드 방향을 결정합니다. 또한 MACD와 신호를 계산하고 그 차이를 히스토그램으로 그래프화합니다.

코드에 따르면, 빠른 라인의 길이는 12이고 느린 라인의 길이는 26이며, 단기 및 장기적인 경향을 나타냅니다. 신호 길이는 추가 평형을 위해 9입니다.

크로스오버 로직:

  • trend_up = macd > 신호: 빠른 선이 느린 선 위에 넘어가고 단기 상승 추세를 나타냅니다.

  • trend_dn = macd < 신호: 빠른 선이 느린 선 아래로 넘어가고 단기 하락 추세를 나타냅니다.

교차점 탐지:

  • cross_UP = 신호[1] >= macd[1] 및 신호 < macd: 빠른 선은 밑에서 느린 선을 가로지릅니다

  • cross_DN = 신호[1] <= macd[1] 및 신호 > macd: 빠른 선은 위에서 느린 선을 가로지릅니다

히스토그램 색의 변화는 운동 강도를 결정합니다.

  • histA_IsUp = 히스토그램 열 증가 및 0 이상, 상승 추세에서 추진력 강화

  • histA_IsDown = 히스토그램 열이 감소하지만 여전히 0보다 크다. 상승 추세에서 추진력이 약화됩니다.

  • 0 아래의 논리도 똑같습니다.

장점

  1. 이중 이동 평균은 중기 트렌드를 결정하고 단기 소음을 피합니다.

  2. MACD는 더 높은 수익성을 위한 단기 동향과 동력을 판단하는데 도움을 줍니다.

  3. 히스토그램 색상 변경은 더 나은 입력 시기를 식별하는 데 도움이됩니다.

  4. 크로스오버 배경 색상은 신호를 강조합니다

  5. 조정 가능한 이동 평균 기간은 다른 시장 환경에 적합합니다

  6. 조정 가능한 MACD 매개 변수는 지표를 최적화합니다

  7. 복수의 입력 확인을 제공합니다: 트렌드, 크로스오버, 패턴 파업

위험성

  1. 단기 변동에 민감하지 않은 이중 MAs는 단기 기회를 놓칠 수 있습니다.

  2. 잘못된 매개 변수 설정으로 MACD 효과가 좋지 않으면 잘못된 신호를 생성 할 수 있습니다.

  3. MAs와 MACD에만 기반한 엔트리는 일부 맹점을 가지고 있습니다.

  4. 스톱 로스 메커니즘이 없는 경우 손실이 증가할 위험이 있습니다.

  5. 엄격한 금전 관리와 포지션 크기의 부재

가능한 해결책:

  1. 다른 지표를 결합하여 단기 변동 범위를 정의하고 위험을 제어합니다.

  2. MACD 매개 변수를 최적화하고 다른 시장에서 테스트

  3. 신호를 확인하기 위해 패턴, 모멘텀 등을 추가

  4. 손실 규모를 제한하기 위한 스톱 로스 메커니즘을 구축

  5. 자본에 기초한 포지션 크기에 자금 관리 모듈을 추가합니다.

최적화 방향

  1. 더 많은 시장 적응력을 위해 MA 매개 변수 조합을 테스트하고 최적화하십시오.

  2. VWAP, 볼링거 미드라인 등 다양한 MA 유형을 시도해보세요.

  3. 가짜 브레이크를 피하기 위해 거래량을 고려하십시오.

  4. RSI 등을 포함하여 과잉 구매/ 과잉 판매를 확인합니다.

  5. 트레일링 스톱, 변동성 스톱 등과 같은 강력한 스톱 손실 메커니즘을 구축하십시오.

  6. 계정 크기에 따라 포지션 크기를 포함합니다.

  7. 매개 변수 최적화를 위해 기계 학습을 고려하십시오.

  8. 강화된 포트폴리오 접근을 위해 전략 우주를 확장

결론

이 전략은 이중 이동 평균 트렌드 필터링과 MACD 모멘텀을 통합하고, 비교적 안정적인 중장기 거래 시스템을 구축하는 패턴 기능을 추가합니다. 주요 장점은 단기 소음을 피하면서 주요 트렌드를 캡처하는 데 있습니다. 그러나 스톱 로스 메커니즘과 리스크 관리와 같은 개선 될 수있는 영역도 있습니다. 전반적으로 이것은 가치있는 개념적 예로 작용하지만 라이브 거래에 대한 포괄적 인 테스트와 정밀화를 필요로합니다.


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

//@version=5
strategy(title="Histogram MacD MVP_V2.1", shorttitle="Histogram MacD MVP_2.1")
//Plot Inputs
res           = input.timeframe("",  "Indicator TimeFrame")
fast_length   = input.int(title="Fast Length", defval=12)
slow_length   = input.int(title="Slow Length", defval=26)
src           = input.source(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 999, 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"])
// Show Plots T/F
show_macd     = input.bool(true, title="Show MACD Lines", group="Show Plots?", inline="SP10")
show_macd_LW  = input.int(3, minval=0, maxval=5, title = "MACD Width", group="Show Plots?", inline="SP11")
show_signal_LW= input.int(2, minval=0, maxval=5, title = "Signal Width", group="Show Plots?", inline="SP11")
show_Hist     = input.bool(true, title="Show Histogram", group="Show Plots?", inline="SP20")
show_hist_LW  = input.int(5, minval=0, maxval=5, title = "-- Width", group="Show Plots?", inline="SP20")
show_trend    = input.bool(true, title = "Show MACD Lines w/ Trend Color", group="Show Plots?", inline="SP30")
show_HB       = input.bool(false, title="Show Highlight Price Bars", group="Show Plots?", inline="SP40")
show_cross    = input.bool(false, title = "Show BackGround on Cross", group="Show Plots?", inline="SP50")
show_dots     = input.bool(true, title = "Show Circle on Cross", group="Show Plots?", inline="SP60")
show_dots_LW  = input.int(5, minval=0, maxval=5, title = "-- Width", group="Show Plots?", inline="SP60")

//show_trend    = input(true, title = "Colors MACD Lines w/ Trend Color", group="Show Plots?", inline="SP5")
// MACD Lines colors
col_macd      = input.color(#FF6D00, "MACD Line  ",  group="Color Settings", inline="CS1")
col_signal    = input.color(#2962FF, "Signal Line  ",  group="Color Settings", inline="CS1")
col_trnd_Up   = input.color(#4BAF4F, "Trend Up      ",  group="Color Settings", inline="CS2")
col_trnd_Dn   = input.color(#B71D1C, "Trend Down    ",  group="Color Settings", inline="CS2")
// Histogram Colors
col_grow_above = input.color(#26A69A, "Above   Grow",  group="Histogram Colors", inline="Hist10")
col_fall_above = input.color(#FF5252, "Fall",  group="Histogram Colors", inline="Hist10")
col_grow_below = input.color(#FF5252, "Below Grow",  group="Histogram Colors", inline="Hist20")
col_fall_below = input.color(#f8f524, "Fall",  group="Histogram Colors", inline="Hist20")
// Alerts T/F Inputs
alert_Long    = input.bool(true, title = "MACD Cross Up", group = "Alerts", inline="Alert10")
alert_Short   = input.bool(true, title = "MACD Cross Dn", group = "Alerts", inline="Alert10")
alert_Long_A  = input.bool(false, title = "MACD Cross Up & > 0", group = "Alerts", inline="Alert20")
alert_Short_B = input.bool(false, title = "MACD Cross Dn & < 0", group = "Alerts", inline="Alert20")
// Calculating
fast_ma = request.security(syminfo.tickerid, res, sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length))
slow_ma = request.security(syminfo.tickerid, res, sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length))
macd = fast_ma - slow_ma
signal = request.security(syminfo.tickerid, res, sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length))
hist = macd - signal
// MACD Trend and Cross Up/Down conditions
trend_up   = macd > signal
trend_dn   = macd < signal
cross_UP   = signal[1] >= macd[1] and signal < macd
cross_DN   = signal[1] <= macd[1] and signal > macd
cross_UP_A = (signal[1] >= macd[1] and signal < macd) and macd > 0
cross_DN_B = (signal[1] <= macd[1] and signal > macd) and macd < 0
// Condition that changes Color of MACD Line if Show Trend is turned on..
trend_col = show_trend  and trend_up ? col_trnd_Up : trend_up ? col_macd : show_trend  and trend_dn ? col_trnd_Dn: trend_dn ? col_macd : na 

//Var Statements for Histogram Color Change
var bool histA_IsUp = false
var bool histA_IsDown = false
var bool histB_IsDown = false
var bool histB_IsUp = false
histA_IsUp   := hist == hist[1] ? histA_IsUp[1] : hist > hist[1] and hist > 0
histA_IsDown := hist == hist[1] ? histA_IsDown[1] : hist < hist[1] and hist > 0
histB_IsDown := hist == hist[1] ? histB_IsDown[1] : hist < hist[1] and hist <= 0
histB_IsUp   := hist == hist[1] ? histB_IsUp[1] : hist > hist[1] and hist <= 0

hist_col =  histA_IsUp ? col_grow_above : histA_IsDown ? col_fall_above : histB_IsDown ? col_grow_below : histB_IsUp ? col_fall_below :color.silver 

// Plot Statements
//Background Color
bgcolor(show_cross and cross_UP ? col_trnd_Up : na, editable=false)
bgcolor(show_cross and cross_DN ? col_trnd_Dn : na, editable=false)
//Highlight Price Bars
barcolor(show_HB and trend_up ? col_trnd_Up : na, title="Trend Up", offset = 0, editable=false)
barcolor(show_HB and trend_dn ? col_trnd_Dn : na, title="Trend Dn", offset = 0, editable=false)
//Regular Plots
plot(show_Hist and hist ? hist : na, title="Histogram", style=plot.style_columns, color=color.new(hist_col ,0),linewidth=show_hist_LW)
plot(show_macd  and signal ? signal : na, title="Signal", color=color.new(col_signal, 0),  style=plot.style_line ,linewidth=show_signal_LW)
plot(show_macd  and macd ? macd : na, title="MACD", color=color.new(trend_col, 0),  style=plot.style_line ,linewidth=show_macd_LW)
hline(0, title="0 Line", color=color.new(color.gray, 0), linestyle=hline.style_dashed, linewidth=1, editable=false)
plot(show_dots and cross_UP ? macd : na, title="Dots", color=color.new(trend_col ,0), style=plot.style_circles, linewidth=show_dots_LW, editable=false)
plot(show_dots and cross_DN ? macd : na, title="Dots", color=color.new(trend_col ,0), style=plot.style_circles, linewidth=show_dots_LW, editable=false)

//Alerts
if alert_Long and cross_UP
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD Crosses Up.", alert.freq_once_per_bar_close)

if alert_Short and cross_DN
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD Crosses Down.", alert.freq_once_per_bar_close)
//Alerts - Stricter Condition - Only Alerts When MACD Crosses UP & MACD > 0 -- Crosses Down & MACD < 0
if alert_Long_A and cross_UP_A
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD > 0 And Crosses Up.", alert.freq_once_per_bar_close)

if alert_Short_B and cross_DN_B
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD < 0 And Crosses Down.", alert.freq_once_per_bar_close)


if (histA_IsUp)
	strategy.entry("buy", strategy.long, comment="buy")
if (histA_IsDown)
	strategy.entry("sell", strategy.short, comment="sell")


더 많은