다중 이동 평균 거래 전략

저자:차오장, 날짜: 2024-02-29 14:32:29
태그:

img

전반적인 설명

이 전략은 Multiple Moving Average Trading Strategy라고 불린다. 이 전략은 트렌드를 결정하기 위해 ZLSMA 지표의 도움을 받아 MACD 지표와 여러 이동 평균의 교차를 거래 신호로 활용하고 자동화 거래를 실현하기 위해 수익 취득 및 손실 중지 출출 논리를 설정한다.

전략 원칙

  1. MACD 지표의 빠른 라인, 느린 라인 및 MACD 히스토그램을 계산합니다. 금색 십자가를 볼 때 길고 죽음의 십자가를 볼 때 짧게 설정하십시오.

  2. 5일, 25일, 45일 및 100일 이동 평균을 계산합니다. 이동 평균이 길어질수록 그 트렌드 지속성이 강합니다.

  3. 이동 평균의 두 그룹 사이의 거리를 계산합니다. 거리가 특정 임계치를 초과하는 경우, 그것은 거래 신호로 설정 할 수있는 이동 평균의 분리를 의미합니다.

  4. ZLSMA 지표를 계산하여 가격의 중장기 트렌드 방향을 나타냅니다. ZLSMA가 전환점을 형성 할 때 트렌드 역전을 결정할 수 있습니다.

  5. MACD 크로스오버, 이동 평균 오차 신호 및 ZLSMA 트렌드 판단을 결합하여 긴 및 짧은 거래 전략을 설정합니다.

  6. 자동 출구 논리를 실현하기 위해 수익을 취하고 손실을 멈추는 지점을 설정합니다.

이점 분석

  1. 멀티 필터 신호는 전략의 효율성을 향상시킵니다. MACD와 이동 평균 분차 신호는 거짓 브레이크오프를 피하기 위해 서로를 확인할 수 있습니다.

  2. ZLSMA는 중·장기적 동향 방향을 결정하는데 도움을 주고 동향에 반하는 거래를 피합니다.

  3. 이윤을 취득하고 손해를 멈추는 지점을 설정함으로써 자동화 된 출구는 인간의 개입의 빈도를 줄입니다.

위험 분석

  1. 부적절 한 매개 변수 설정 은 과도 한 거래 또는 놓친 주문 으로 이어질 수 있다. 매개 변수 를 최적화 하는 것이 최선 이다.

  2. 고정된 이익 취득 및 손해 중지 포인트는 수익 잠재력을 제한하거나 손실을 증가시킵니다. ATR에 기반한 동적 중지가 고려 될 수 있습니다.

  3. 이동 평균 전략은 범위 제한 시장에서 잘 작동하지 않습니다. 다른 지표 또는 수동 개입이 필요할 수 있습니다.

최적화 방향

  1. 다른 길이의 이동 평균을 테스트함으로써 이동 평균 매개 변수 조합을 최적화합니다.

  2. KDJ 및 BOLL와 같은 다른 지표를 추가하여 입구와 출구 지점을 결정하는 테스트

  3. 변동성 측정에 기반한 동적 스톱 로스 전략을 시도해보세요.

  4. 기계 학습 모델을 추가하면 최적의 매개 변수를 자동으로 찾을 수 있습니다.

결론

이 전략은 자동화 된 거래를 달성하기 위해 MACD, 여러 이동 평균 및 ZLSMA 트렌드 결정을 통합합니다. 여러 신호로 필터링함으로써 전략 안정성이 향상됩니다. 출구 논리를 설정함으로써 위험이 감소합니다. 실제 거래에 대한 특정 실용적 가치가 있습니다. 후속 매개 변수 최적화, 지표 확장, 동적 중지 등은 전략 성능을 더욱 향상시킬 수 있습니다.


/*backtest
start: 2023-02-22 00:00:00
end: 2024-02-28 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("MACD ZLSMA_izumi⑤(4つの条件、MCDがクロスしてたら)", overlay=true)

fast_length = input(title = "Fast Length", defval = 12)
slow_length = input(title = "Slow Length", defval = 26)
src = input(title = "Source", defval = close)
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)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal

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')

hline(0, "Zero Line", color = color.new(#787B86, 50))
plot(hist, title = "Histogram", style = plot.style_columns, color = (hist >= 0 ? (hist[1] < hist ? #26A69A : #B2DFDB) : (hist[1] < hist ? #FFCDD2 : #FF5252)))
plot(macd,   title = "MACD",   color = #2962FF)
plot(signal, title = "Signal", color = #FF6D00)

//MACDクロス設定
enterLong = ta.crossover(macd, signal)
enterShort = ta.crossunder(macd, signal)

//移動平均線の期間を設定
ema5 = input(5, title="ma期間5")
ema25 = input(25, title="ma期間25")
ema45 = input(45, title="ma期間45")
ema100 = input(100, title="ma期間100")

//移動平均線を計算
//sma関数で「ema25」バー分のcloseを移動平均線として「Kema」に設定
Kema5 = ta.sma(close,ema5)
Kema25 = ta.sma(close,ema25)
Kema45 = ta.sma(close,ema45)
Kema100 = ta.sma(close,ema100)



//移動平均線をプロット
plot(Kema5, color=color.rgb(82, 249, 255),title="ema5")
plot(Kema25, color=color.red,title="ema25")
plot(Kema45, color=color.blue,title="ema45")
plot(Kema100, color=color.green,title="ema100")

//ema同士の距離が30以上の時に「distancOK」にTureを返す
//distance1 = math.abs(Kema5-Kema25)
distance2 = math.abs(Kema25-Kema45)
distanceValue1 = input(0.030, title ="ema同士の乖離値") 
//distanceOk1 = distance1 > distanceValue1
distanceOk2 = distance2 > distanceValue1

//2区間のema同士の距離が30以上の時に「distanceOKK」にTrueを返す
//distanceOkK1 = distanceOk1 and distanceOk2
distanceOkK1 = distanceOk2

//5EMAとロウソクの乖離判定
//DistanceValue5ema = input(0.03, title ="5emaとロウソクの乖離率")
//emaDistance = math.abs(Kema5 - close)
//emaDistance5ema = emaDistance < DistanceValue5ema

//ZLSMA追加のコード
length = input.int(32, title="Length")
offset = input.int(0, title="offset")
src2 = input(close, title="Source")
lsma = ta.linreg(src2, length, offset)
lsma2 = ta.linreg(lsma, length, offset)
eq= lsma-lsma2
zlsma = lsma+eq
//ZLSMAのプロット
plot(zlsma, color=color.yellow, linewidth=3)

//ZLSMAの前回高値を検索
//var float zlsmaHigh = na
//var float zlsmaHighValue = na
//if ta.highest(zlsma,35) == zlsma[3]
//    zlsmaHighValue := zlsmaHigh
//    zlsmaHigh := zlsma[3]

//if (na(zlsmaHighValue))
 //   zlsmaHighValue := zlsmaHigh

//ZLSMAの前回安値を検索
//var float zlsmaLow = na
//var float zlsmaLowValue = na
//if ta.lowest(zlsma,35) == zlsma[3]
//    zlsmaLowValue := zlsmaLow
//    zlsmaLow := zlsma[3]

///if (na(zlsmaLowValue))
//    zlsmaLowValue := zlsmaLow

//利確・損切りポイントの初期化(変数の初期化)
var longProfit = 0.0
var longStop = 0.0
var shortProfit = 0.0
var shortStop = 0.0

//inputで設定画面の選択項目を設定
longProfitValue = input(0.06, title ="ロング利確pips")
shortProfitValue = input(-0.06, title ="ショート利確pips")
longStopValue = input(-0.06, title ="ロング損切pips")
shortStopValue = input(0.06, title ="ショート損切pips")

// クロスの強さを推定 
//angleThreshold = input(0.001, title = "クロスの強さ調節" )

// クロスの強さの閾値、この値を調整してクロスの強さの基準を変える 
//macdDiff = macdLine - signalLine 
//strongCross = math.abs(macdDiff) > angleThreshold 

// エントリー条件 (MACDラインとシグナルラインがクロス)
//ta.crossover(macdLine, signalLine) and strongCross 


//ロングエントリー条件
if  distanceOkK1 and enterLong
	strategy.entry("long", strategy.long, comment="long")
    longProfit := close + longProfitValue
    longStop := close + longStopValue

//    if na(strategy.position_avg_price) and close>strategy.position_avg_price + 0.05 * syminfo.mintick 
 //       longStop := strategy.position_avg_price + 10 * syminfo.mintick
  //  strategy.exit("exit", "long",stop = longStop)

strategy.exit("exit", "long", limit = longProfit,stop = longStop)


if  distanceOkK1 and enterShort
	strategy.entry("short", strategy.short, comment="short")
    shortProfit := close + shortProfitValue
    shortStop := close + shortStopValue

 //   if na(strategy.position_avg_price) and close>strategy.position_avg_price - 0.05 * syminfo.mintick 
  //      shortStop := strategy.position_avg_price - 0.1 * syminfo.mintick
  //  strategy.exit("exit", "long",stop = longStop)


strategy.exit("exit", "short", limit = shortProfit,stop = shortStop)
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)

더 많은