이중 MACD 양적 거래 전략

저자:차오장, 날짜: 2024-01-30 16:43:29
태그:

img

전반적인 설명

듀얼 MACD 양적 거래 전략은 듀얼 타임프레임 MACD 인디케이터를 사용하여 구현되는 양적 거래 전략이다. 주간 MACD 인디케이터가 황금 십자가를 형성할 때 길어지고 일일 MACD 인디케이터가 죽음의 십자가를 형성할 때 포지션을 닫는다. 포지션이 비어있을 때, 매일 MACD 인디케이터가 또 다른 황금 십자가를 형성하면 새로운 긴 포지션을 열 수 있다.

전략 논리

듀얼 MACD 양적 거래 전략은 주간 MACD와 일일 MACD 지표의 조합을 사용하여 입점 및 출구 신호를 결정합니다.

첫째, 주간 MACD 지표의 MACD 라인이 신호 라인의 위를 넘을 때, 구매 신호가 생성되고 긴 포지션이 열립니다. 다음, 일일 MACD 지표의 MACD 라인이 신호 라인의 아래를 넘을 때, 판매 신호가 생성되고 포지션은 닫습니다.

포지션이 비어있을 때, 일일 MACD 지표의 MACD 라인이 신호 라인 위에 다시 넘어가면 새로운 긴 포지션이 다시 열립니다. 즉, 일일 MACD의 황금 십자가가 재입구 조건으로 작용합니다.

매일 MACD의 죽음의 십자가만이 포지션을 닫을 것이라는 점에 유의하십시오. 그러나 주간 MACD의 MACD 라인이 신호 라인 위에 있고, 트레이딩 윈도 내에 있을 때만 재개가 허용됩니다.

장점

이중 MACD 양적 거래 전략은 이중 시간 프레임 분석을 결합하여 잘못된 신호를 효과적으로 필터하고 신호 품질을 향상시킬 수 있습니다. 구체적으로 몇 가지 주요 장점이 있습니다.

  1. 주간 시간 프레임은 주요 트렌드 방향을 판단하여 상반된 거래를 피하는 데 도움이됩니다.

  2. 일일 시간 프레임은 출입 및 출입 시기를 결정합니다. 이는 단기 거래 기회를 적시에 포착 할 수 있습니다.

  3. 거래 창구 메커니즘은 단기 조정으로 인해 과도하게 빈번한 개장과 폐쇄를 피할 수 있습니다.

  4. MACD 지표 매개 변수는 조정 가능하며 다양한 품종과 시장 조건에 따라 최적화 될 수 있습니다.

  5. 수익을 취하고, 손해를 멈추고, 위험을 효과적으로 통제하기 위해 손해를 멈추는 기능을 통합합니다.

위험성

이중 MACD 양적 거래 전략은 또한 다음과 같은 몇 가지 위험을 가지고 있습니다.

  1. MACD 지표는 잘못된 신호와 빈번한 크로스오버를 생성하는 경향이 있으며 다른 지표로부터 확인이 필요합니다.

  2. 주간/월간 시간 프레임에서 확인된 주요 트렌드는 반전될 수 있으며, 트레일링 스톱 로스는 필요합니다.

  3. 매개 변수들은 품종과 시장 조건에 따라 지속적으로 최적화되고 조정되어야 합니다.

  4. 백테스트 결과에 지나치게 의존할 수 없습니다. 라이브 성능은 백테스트와 다를 수 있습니다.

대응 솔루션:

  1. 다른 지표와 결합하여 논리 최적화로 전략 시스템을 구축합니다.

  2. 최대 허용 손실을 초과하지 않도록 합리적인 스톱 손실을 설정합니다.

  3. 최적의 조합을 찾기 위해 매개 변수를 지속적으로 최적화합니다.

  4. 최소한의 자본으로 실시간 거래를 시작해 안정성을 확인해

최적화

이중 MACD 양적 거래 전략은 더 많은 최적화를 위한 여지가 있습니다:

  1. 볼링거 밴드, KDJ 및 기타 지표를 도입하여 다중 지표 결합 전략을 구축하고 신호 품질을 향상시킵니다.

  2. 거래 부피 지표를 포함하여 거래 부피가 충분하지 않은 잘못된 브레이크오프를 피합니다.

  3. 기계 학습 방법을 활용하여 자동으로 매개 변수를 최적화하고 동적 조정을 달성합니다.

  4. 전략의 추가 위험 조정, 예를 들어 수익과 손실 비율과 같은 고급 스톱 손실 방법을 추가하는 것.

  5. 전략 적합성 테스트 & 최적화 과잉 적합성 문제를 피하기 위해.

결론

이중 MACD 양적 거래 전략은 주요 트렌드와 하위 트렌드를 결정하기 위해 이중 타임프레임 분석을 통합하고 각 지표의 장점을 완전히 발휘합니다. 전략 최적화에 대한 잠재력은 여전히 크며 다른 지표, 기계 학습을 통해 자동 매개 변수 최적화 등을 도입하여 전략 성능을 더욱 향상시킬 것으로 예상됩니다. 라이브 거래 검증은 전략을 더욱 완성하는 데 필수적인 단계이자 중요한 기초입니다.


/*backtest
start: 2023-01-29 00:00:00
end: 2024-01-11 05:20: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/
// © maxits

// Long Position: Weekly Macd line crosses above Signal line   
// [Trading Window Macd Line > Signal Line] (Weekly)
// Close Position: Daily Macd Line crosses above Daily Signal line.  
// Re Entry Condition: Macd line crosses above Signal line only if [Trading Window MacdLine > Sgnal Line] (Weekly)

//@version=4
strategy("Dual MACD Strategy",
         shorttitle="Dual Macd Tester",
         overlay=false,
         initial_capital=1000,
         default_qty_value=20,
         default_qty_type=strategy.percent_of_equity,
         commission_value=0.1,
         pyramiding=0)



// Define user inputs
i_time     = input(defval = timestamp("01 May 2018 13:30 +0000"), title = "Start Time", type = input.time) // Starting  time for Backtesting
f_time     = input(defval = timestamp("9 Sep 2021 13:30 +0000"), title = "Finish Time", type = input.time) // Finishing time for Backtesting

sep1          = input(false, title="------ Profit & Loss ------")

enable_TP     = input(true, title="Enable Just a Profit Level?")
enable_SL     = input(false, title="Enable Just a S.Loss Level?")
enable_TS     = input(true, title=" Enable Only Trailing Stop")
long_TP_Input = input(30.0,   title='Take Profit %',      type=input.float, minval=0)/100
long_SL_Input = input(1.0,   title='Stop Loss %',        type=input.float, minval=0)/100
long_TS_Input = input(5.0,   title='Trailing Stop %',    type=input.float, minval=0)/100
cl_low_Input  = input(low,   title="Trailing Stop Source")
long_TP       = strategy.position_avg_price * (1 + long_TP_Input)
long_SL       = strategy.position_avg_price * (1 - long_SL_Input)
long_TS       = cl_low_Input * (1 - long_TS_Input)

sep2       = input(false, title="------ Macd Properties ------")

d_res      = input(title="Short Term TimeFrame", type=input.resolution, defval="D") // Daily Time Frame
w_res      = input(title="Long Term TimeFrame", type=input.resolution, defval="W")  // Weekly Time Frame
src        = input(close, title="Source")                                           // Indicator Price Source
fast_len   = input(title="Fast Length", type=input.integer, defval=12)              // Fast MA Length
slow_len   = input(title="Slow Length", type=input.integer, defval=26)              // Slow MA Length
sign_len   = input(title="Sign Length", type=input.integer, defval=9)               // Sign MA Length
d_w        = input(title="Daily or Weekly?", type=input.bool, defval=true)          // Plot Daily or Weekly MACD

// Color Plot for Macd

col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350

// BG Color

bg_color = color.rgb(127, 232, 34, 75)

// Daily Macd

[d_macdLine, d_singleLine, d_histLine] = security(syminfo.tickerid, d_res, macd(src, fast_len, slow_len, sign_len)) // Funcion Security para poder usar correcta resolución

plot(d_w ? d_macdLine   : na, color=color.blue)
plot(d_w ? d_singleLine : na, color=color.orange)
plot(d_w ? d_histLine   : na, style=plot.style_columns,
     color=(d_histLine>=0 ? (d_histLine[1] < d_histLine ? col_grow_above : col_fall_above) : 
     (d_histLine[1] < d_histLine ? col_grow_below : col_fall_below)))
    
// Weekly Macd

[w_macdLine, w_singleLine, w_histLine] = security(syminfo.tickerid, w_res, macd(src, fast_len, slow_len, sign_len)) // Funcion Security para poder usar correcta resolución

plot(d_w ? na : w_macdLine,   color=color.blue)
plot(d_w ? na : w_singleLine, color=color.orange)
plot(d_w ? na : w_histLine,   style=plot.style_columns,
     color=(w_histLine>=0 ? (w_histLine[1] < w_histLine ? col_grow_above : col_fall_above) : 
     (w_histLine[1] < w_histLine ? col_grow_below : col_fall_below)))

///////////////////////////////// Entry Conditions
inTrade    = strategy.position_size != 0       // Posición abierta
notInTrade = strategy.position_size == 0       // Posición Cerrada
start_time = true

trading_window = w_macdLine > w_singleLine   // Weekly Macd Signal enables a trading window 
bgcolor(trading_window ? bg_color : na)
buy_cond       = crossover (w_macdLine, w_singleLine)
sell_cond      = crossunder(d_macdLine, d_singleLine)
re_entry_cond  = crossover (d_macdLine, d_singleLine) and trading_window

// Entry Exit Conditions

trailing_stop  = 0.0        // Code for calculating Long Positions Trailing Stop Loss
trailing_stop := if (strategy.position_size != 0)
    stopValue = long_TS
    max(trailing_stop[1], stopValue)
else 
    0

if (buy_cond and notInTrade and start_time)
    strategy.entry(id="First Entry", long=strategy.long, comment="First Long")

if (sell_cond and inTrade)
    strategy.close(id="First Entry", comment="Close First Long")
    
if (re_entry_cond and notInTrade and start_time)
    strategy.entry(id="Further Entry", long=strategy.long, comment="Further Entry")

if (sell_cond and inTrade)
    strategy.close(id="Further Entry", comment="Close First Long")

if enable_TP
    if (enable_TS and not enable_SL)
        strategy.exit("Long TP & TS FiEn", "First Entry",   limit = long_TP, stop = trailing_stop)
        strategy.exit("Long TP & TS FuEn", "Further Entry", limit = long_TP, stop = trailing_stop)
    else
        if (enable_SL and not enable_TS)
            strategy.exit("Long TP & TS FiEn", "First Entry",   limit = long_TP, stop = long_SL)
            strategy.exit("Long TP & TS FuEn", "Further Entry", limit = long_TP, stop = long_SL)
        else 
            strategy.exit("Long TP & TS FiEn", "First Entry",   limit = long_TP)
            strategy.exit("Long TP & TS FuEn", "Further Entry", limit = long_TP)
else
    if not enable_TP 
        if (enable_TS and not enable_SL)
            strategy.exit("Long TP & TS FiEn", "First Entry",   stop = trailing_stop)
            strategy.exit("Long TP & TS FuEn", "Further Entry", stop = trailing_stop)
        else
            if (enable_SL and not enable_TS)
                strategy.exit("Long TP & TS FiEn", "First Entry",   stop = long_SL)
                strategy.exit("Long TP & TS FuEn", "Further Entry", stop = long_SL)

plot(enable_TP ? long_TP : na, title="TP Level", color=color.green, style=plot.style_linebr, linewidth=2)
plot(enable_SL ? long_SL : na, title="SL Level", color=color.red,   style=plot.style_linebr, linewidth=2)
plot(enable_TS and trailing_stop ? trailing_stop : na, title="TS Level", color=color.red, style=plot.style_linebr, linewidth=2)


더 많은