동적 봉투 이동 평균 전략

저자:차오장, 날짜: 2024-02-05 14:15:40
태그:

img

전반적인 설명

이 전략은 이동 평균과 동적 봉투 라인을 기반으로 긴 및 짧은 거래를 구현합니다. 포지션을 설정하기 위해 봉투 라인을 넘어 가격 브레이크를 추적하고 가격이 기본 이동 평균 이하로 떨어지면 포지션을 닫습니다. 이 전략은 명백한 추세를 보이는 주식과 암호화폐에 잘 작동합니다.

전략 논리

첫째, 이 전략은 사용자 정의 이동 평균 유형과 길이를 기반으로 기본 이동 평균을 계산합니다. 일반적인 이동 평균에는 SMA, EMA 등이 있습니다.

다음으로, 그것은 사용자 정의 비율 매개 변수에 기초하여 상위 및 하위 봉투 라인을 계산합니다. 예를 들어, 5%는 기준 이동 평균보다 가격이 5% 변동할 때 포지션을 설정하는 것을 의미합니다. 봉투 라인의 수를 사용자 정의 할 수 있습니다.

진입 규칙에 관해서는, 가격이 하위 봉투 라인을 넘어 갈 때 길고, 가격이 상위 봉투 라인을 넘어 갈 때 짧습니다. 규칙은 간단하고 간단합니다.

마지막으로, 가격이 기본 이동 평균 아래로 넘어갈 때 모든 포지션을 닫습니다. 이것은 트렌드를 추적하는 출구 포인트입니다.

특히 이 전략은 부분적 위치 확립을 구현합니다. 여러 개의 봉투 라인이있는 경우 자본은 비례적으로 할당됩니다. 이것은 일방적인 베팅의 위험을 방지합니다.

이점 분석

이 전략의 가장 큰 장점:

  1. 자동 트렌드 추적. 트렌드 방향을 결정하기 위해 이동 평균을 사용하는 것은 잘 정립된 방법입니다.

  2. 봉투 라인을 통해 약간의 소음을 필터링하여 과도한 민감한 거래를 방지합니다. 합리적인 매개 변수 설정은 전략 수익성을 크게 향상시킬 수 있습니다.

  3. 부분적인 위치 확립은 전략의 회복력을 향상시킵니다. 한쪽이 실패해도 다른 쪽은 계속 잘 작동 할 수 있습니다. 이것은 전반적인 위험 / 보상 비율을 최적화합니다.

  4. 조정 가능한 이동 평균 및 봉투 라인 번호. 이것은 다른 제품에 기반한 매개 변수 조정에 대한 유연성을 증가시킵니다.

위험 분석

이 전략의 주요 위험은:

  1. 이동 평균 시스템은 황금 십자가 신호에 민감하지 않습니다. 명백한 추세가 존재하지 않으면 몇 가지 기회를 놓칠 수 있습니다.

  2. 너무 넓은 봉투 라인 설정은 거래 빈도와 미끄러짐 위험을 증가시킬 수 있습니다. 너무 좁은 설정은 더 큰 움직임을 놓칠 수 있습니다. 균형을 찾는 것은 철저한 테스트가 필요합니다.

  3. 이 전략 은 아마 다른 시장 에서 더 많은 호기심 을 갖게 될 것 이다. 따라서 트렌딩 제품 들 이 바람직 하다.

  4. 부분적인 위치 설정 한계 거래 당 이익. 일방적인 베팅을 추구하는 경우 추가 최적화가 필요합니다.

최적화 방향

이 전략을 최적화하는 주요 방향:

  1. KDJ 등과 같은 다른 입력/출출 지표로 대체하거나 여러 지표가 있는 필터를 추가합니다.

  2. 스톱프로프트/러스 로직을 추가합니다. 이것은 수익을 확보하고 적극적으로 위험을 완화시킵니다.

  3. 최적화 매개 변수 가장 좋은 이동 평균과 봉투 조합을 찾기 위해. 광범위한 백테스팅과 최적화를 요구합니다.

  4. 스마트 매개 변수 조정을 위해 딥 러닝 등을 통합합니다. 끊임없이 배우고 시간이 지남에 따라 업데이트합니다.

  5. 제품과 시장의 차이점을 고려하고, 다양한 거래 환경에 맞는 여러 매개 변수 세트를 설정합니다. 이것은 전략 안정성을 크게 향상시킵니다.

결론

결론적으로,이 동적 봉투 이동 평균 전략은 트렌드 거래에 매우 잘 작동합니다. 그것은 간단하고 효율적이며 이해하기 쉽고 최적화 할 수 있습니다. 기본 전략으로서, 그것은 큰 유연성과 확장성을 가지고 있습니다. 더 복잡한 시스템과 결합하면 더 높은 수익과 더 나은 위험 조정 메트릭을 위해 추가로 향상 될 수 있습니다. 따라서 양적 거래 전략의 훌륭한 기초로 사용됩니다.


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

//@version=5
strategy("Envelope Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, pyramiding = 5, commission_type=strategy.commission.percent, commission_value=0.0)

// CopyRight Crypto Robot

src = input(ohlc4, title="Source", group = "Base MA")
ma_base_window = input.int(5, "Base Mooving Average Window", step = 1, group = "Base MA")
ma_type = input.string(defval='1. SMA', options=['1. SMA', '2. PCMA', '3. EMA', '4. WMA', '5. DEMA', '6. ZLEMA', '7. HMA'], title='MA Type', group = "Base MA")


envelope_1_pct = input.float(0.05, "Envelope 1", step = 0.01, group = "Envelopes")
envelope_2_pct = input.float(0.10, "Envelope 2", step = 0.01, group = "Envelopes")
envelope_3_pct = input.float(0.15, "Envelope 3", step = 0.01, group = "Envelopes")
envelope_4_pct = input.float(0.0, "Envelope 4", step = 0.01, group = "Envelopes")
envelope_5_pct = input.float(0.0, "Envelope 5", step = 0.01, group = "Envelopes")

use_longs = input.bool(true, 'Long Positions') 
use_short = input.bool(true, 'Short Positions')

total_envelope = 0
if envelope_1_pct > 0
    total_envelope := total_envelope + 1
if envelope_2_pct > 0
    total_envelope := total_envelope + 1
if envelope_3_pct > 0
    total_envelope := total_envelope + 1
if envelope_4_pct > 0
    total_envelope := total_envelope + 1
if envelope_5_pct > 0
    total_envelope := total_envelope + 1

// ---------------------------------------------
// -------------- INDICATORS -------------------
ma_function(MA_type, MA_length) =>
    zlema_lag = (MA_length - 1) / 2
    hma_src = MA_type == '7. HMA' ? 2 * ta.wma(src, math.floor(MA_length / 2)) - ta.wma(src, MA_length) : na
    MA_type == '1. SMA' ? ta.sma(src, MA_length) : MA_type == '2. PCMA' ? (ta.highest(high, MA_length) + ta.lowest(low, MA_length)) / 2 : MA_type == '3. EMA' ? ta.ema(src, MA_length) : MA_type == '4. WMA' ? ta.wma(src, MA_length) : MA_type == '5. DEMA' ? 2 * ta.ema(src, MA_length) - ta.ema(ta.ema(src, MA_length), MA_length) : MA_type == '6. ZLEMA' ? ta.ema(src + src - src[zlema_lag], MA_length) : MA_type == '7. HMA' ? ta.wma(hma_src, math.floor(math.sqrt(MA_length))) : na

    
ma_base = ma_function(ma_type, ma_base_window)

ma_high_1 = envelope_1_pct > 0 ? ma_base * (1 + envelope_1_pct) : na
ma_high_2 = envelope_2_pct > 0 ? ma_base * (1 + envelope_2_pct) : na
ma_high_3 = envelope_3_pct > 0 ? ma_base * (1 + envelope_3_pct) : na
ma_high_4 = envelope_4_pct > 0 ? ma_base * (1 + envelope_4_pct) : na
ma_high_5 = envelope_5_pct > 0 ? ma_base * (1 + envelope_5_pct) : na

ma_low_1 = envelope_1_pct > 0 ? ma_base * (1 - envelope_1_pct) : na
ma_low_2 = envelope_2_pct > 0 ? ma_base * (1 - envelope_2_pct) : na
ma_low_3 = envelope_3_pct > 0 ? ma_base * (1 - envelope_3_pct) : na
ma_low_4 = envelope_4_pct > 0 ? ma_base * (1 - envelope_4_pct) : na
ma_low_5 = envelope_5_pct > 0 ? ma_base * (1 - envelope_5_pct) : na

// ---------------------------------------------
// --------------- STRATEGY --------------------
if use_longs
    if envelope_1_pct > 0 and strategy.opentrades < 1
        strategy.entry('long 1', strategy.long, limit=ma_low_1, qty=(strategy.equity / ma_low_1) * (1 / total_envelope))
    if envelope_2_pct > 0 and strategy.opentrades < 2
        strategy.entry('long 2', strategy.long, limit=ma_low_2, qty=(strategy.equity / ma_low_2) * (1 / total_envelope))
    if envelope_3_pct > 0 and strategy.opentrades < 3
        strategy.entry('long 3', strategy.long, limit=ma_low_3, qty=(strategy.equity / ma_low_3) * (1 / total_envelope))
    if envelope_4_pct > 0 and strategy.opentrades < 4
        strategy.entry('long 4', strategy.long, limit=ma_low_4, qty=(strategy.equity / ma_low_4) * (1 / total_envelope))
    if envelope_5_pct > 0 and strategy.opentrades < 5
        strategy.entry('long 5', strategy.long, limit=ma_low_5, qty=(strategy.equity / ma_low_5) * (1 / total_envelope))


  
if use_short
    if envelope_1_pct > 0 and strategy.opentrades < 1
        strategy.entry('short 1', strategy.short, limit=ma_high_1, qty=(strategy.equity / ma_high_1) * (1 / total_envelope))
    if envelope_2_pct > 0 and strategy.opentrades < 2
        strategy.entry('short 2', strategy.short, limit=ma_high_2, qty=(strategy.equity / ma_high_2) * (1 / total_envelope))
    if envelope_3_pct > 0 and strategy.opentrades < 3
        strategy.entry('short 3', strategy.short, limit=ma_high_3, qty=(strategy.equity / ma_high_3) * (1 / total_envelope))
    if envelope_4_pct > 0 and strategy.opentrades < 4
        strategy.entry('short 4', strategy.short, limit=ma_high_4, qty=(strategy.equity / ma_high_4) * (1 / total_envelope))
    if envelope_5_pct > 0 and strategy.opentrades < 5
        strategy.entry('short 5', strategy.short, limit=ma_high_5, qty=(strategy.equity / ma_high_5) * (1 / total_envelope))


strategy.exit('close', limit=ma_base)


// ---------------------------------------------
// ------------------ PLOT ---------------------

ma_base_plot = plot(ma_base, title = "Base MA", color = color.orange, linewidth = 3, offset = 1)

ma_high_1_plot = plot(ma_high_1, title = "MA high 1", color = color.red, offset = 1)
ma_high_2_plot = plot(ma_high_2, title = "MA high 2", color = color.red, offset = 1)
ma_high_3_plot = plot(ma_high_3, title = "MA high 3", color = color.red, offset = 1)
ma_high_4_plot = plot(ma_high_4, title = "MA high 4", color = color.red, offset = 1)
ma_high_5_plot = plot(ma_high_5, title = "MA high 5", color = color.red, offset = 1)

ma_low_1_plot = plot(ma_low_1, title = "MA low 1", color = color.green, offset = 1)
ma_low_2_plot = plot(ma_low_2, title = "MA low 2", color = color.green, offset = 1)
ma_low_3_plot = plot(ma_low_3, title = "MA low 3", color = color.green, offset = 1)
ma_low_4_plot = plot(ma_low_4, title = "MA low 4", color = color.green, offset = 1)
ma_low_5_plot = plot(ma_low_5, title = "MA low 5", color = color.green, offset = 1)

plot(ohlc4, color=color.purple)

// use_period = input.bool(false, "Période spécifique ?", group="periode")
// startDate = input.time(timestamp("01 Jan 2020"), "Date de début", group="periode")
// endDate = input.time(timestamp("01 Jan 2025"), "Date de fin", group="periode")


//------------------------------------------
//-------------Indicateurs------------------

// inDateRange = use_period ? ((time >= startDate) and (time < endDate)) : true

// //--------------Backtest-------------------

// strategy_pnl = strategy.netprofit + strategy.openprofit
// bnh_strategy_pnl_pcnt = (strategy_pnl / strategy.initial_capital) * 100

// float bnh_start_bar = na
// bnh_start_bar := na(bnh_start_bar[1]) or inDateRange != true? close : bnh_start_bar[1]
// float bnl_buy_hold_equity = na
// bnl_buy_hold_equity :=  inDateRange == true ? ((close - bnh_start_bar)/bnh_start_bar) * 100 : bnl_buy_hold_equity[1]

// bnh_vs_diff = bnh_strategy_pnl_pcnt - bnl_buy_hold_equity
// bnh_diff_color = bnh_vs_diff > 0 ? color.new(color.green, inDateRange ? 60 : 100) : color.new(color.red, inDateRange ? 60 : 100)

// var Table = table.new(position.top_right, columns = 2, rows = 4, border_width = 1, bgcolor = color.black, border_color = color.gray)
// table.cell(table_id = Table, column = 0, row = 0, text_color=(bnh_strategy_pnl_pcnt>bnl_buy_hold_equity)?color.gray:color.green, text_size = size.normal, text = "Buy & hold profit")
// table.cell(table_id = Table, column = 1, row = 0, text_color=(bnh_strategy_pnl_pcnt>bnl_buy_hold_equity)?color.gray:color.green, text_size = size.normal, text = str.tostring(bnl_buy_hold_equity, '#.##') + ' %')
// table.cell(table_id = Table, column = 0, row = 1, text_color=(bnh_strategy_pnl_pcnt<bnl_buy_hold_equity)?color.gray:color.green, text_size = size.normal, text = "Strategy profit")
// table.cell(table_id = Table, column = 1, row = 1, text_color=(bnh_strategy_pnl_pcnt<bnl_buy_hold_equity)?color.gray:color.green, text_size = size.normal, text = str.tostring(bnh_strategy_pnl_pcnt, '#.##') + ' %')
// table.cell(table_id = Table, column = 0, row = 2, text_color=color.yellow, text_size = size.normal, text = "Date de début")
// table.cell(table_id = Table, column = 1, row = 2, text_color=color.yellow, text_size = size.normal, text = str.format("{0,date,dd-MM-YYYY}",strategy.closedtrades.entry_time(1)))

더 많은