이동 평균 크로스오버 + MACD 느린 라인 모멘텀 전략

저자:차오장, 날짜: 2024-04-12 17:16:06
태그:SMAEMAMACD

img

전반적인 설명

이 전략은 이동 평균 크로스오버와 MACD 지표를 주요 거래 신호로 결합합니다. 이 전략은 출입 신호로 여러 느린 이동 평균과 빠른 이동 평균의 크로스오버를 사용하고, 트렌드 확인으로 MACD 느린 라인 히스토그램의 양적/부적 값을 사용합니다. 이 전략은 출입 시 여러 가지 수익 및 스톱-러스 수준을 설정하고, 보유 시간이 증가함에 따라 지속적으로 스톱-러스 수준을 조정하여 수익을 잠금합니다.

전략 원칙

  1. 빠른 MA가 느린 MA1을 넘을 때 닫기 가격은 느린 MA2보다 높고 MACD 히스토그램은 0보다 크다.
  2. 빠른 MA가 느린 MA1보다 낮을 때, 폐쇄 가격은 느린 MA2보다 낮고 MACD 히스토그램은 0보다 작을 때, 단축됩니다.
  3. 입시에 여러 가지 취업 이익 및 중단 손실 수준을 설정합니다. 취업 이익 수준은 위험 선호도에 기반하고 있으며 보유 시간이 증가함에 따라 중단 손실 수준은 지속적으로 조정되어 점차 수익을 고정합니다.
  4. 이동 평균, MACD 매개 변수, 취득 및 스톱 로스 수준 등이 다른 시장 조건에 적응하도록 유연하게 조정 될 수 있습니다.

이 전략은 트렌드를 캡처하기 위해 MA 크로스오버와 방향을 확인하기 위해 MACD를 사용하여 트렌드 판단의 신뢰성을 향상시킵니다. 다중 취득 및 중지 손실 디자인은 위험과 이익을 더 잘 제어하는 데 도움이됩니다.

전략적 장점

  1. MA 크로스오버는 트렌드를 추적하는 고전적인 방법이며, 트렌드 형성을 적시에 파악할 수 있습니다.
  2. 여러 MA를 이용하면 트렌드의 강도와 지속성을 보다 포괄적으로 판단할 수 있습니다.
  3. MACD 지표는 트렌드를 효과적으로 식별하고 동력을 판단하여 MA 크로스오버에 강력한 보완 역할을 합니다.
  4. 다중 수익 및 동적 스톱 로스 디자인은 위험을 제어하고 수익을 허용하여 시스템의 안정성을 향상시킬 수 있습니다.
  5. 매개 변수는 조정 가능하고 적응 가능하며 다른 도구와 시간 틀에 따라 유연하게 설정 할 수 있습니다.

전략 위험

  1. MA 크로스오버는 초기 트렌드를 놓칠 수 있거나 높은 것을 쫓을 수 있는 신호 지연의 위험이 있습니다.
  2. 부적절한 매개 변수 설정은 과잉 거래 또는 과도하게 긴 보유 기간을 초래하여 비용과 위험을 증가시킬 수 있습니다.
  3. 너무 공격적인 스톱 로스 레벨은 조기 스톱 아웃으로 이어질 수 있고, 너무 보수적인 스톱 로스 레벨은 수익에 영향을 줄 수 있습니다.
  4. 급격한 트렌드 변화 또는 시장 이상으로 인해 전략이 실패 할 수 있습니다.

이러한 위험은 매개 변수 최적화, 지점 조정, 추가 조건 설정 등으로 제어 될 수 있습니다. 그러나 어떤 전략도 위험을 완전히 피할 수 없으며 투자자는 신중하게 다루어야합니다.

전략 최적화 방향

  1. 추세와 신호를 더 확인하기 위해 RSI, 볼링거 밴드 등 더 많은 지표를 도입하는 것을 고려하십시오.
  2. ATR 또는 비율 기반의 레벨을 고려하는 것과 같은 취익 및 스톱 로스 레벨의 설정에 대한 더 정교한 최적화를 수행합니다.
  3. 시장 변동성에 기반한 매개 변수를 동적으로 조정하여 적응력을 향상시킵니다.
  4. 리스크 조건에 따라 포지션 크기를 조정할 수 있는 포지션 사이징 모듈을 도입한다.
  5. 위험 다양화를 위한 전략 포트폴리오를 구축하기 위해 전략을 통합합니다.

지속적인 최적화와 개선을 통해 전략은 더 견고하고 신뢰할 수 있으며 변화하는 시장 환경에 더 잘 적응 할 수 있습니다. 그러나 과도한 적합성을 피하기 위해 최적화는 신중하게 수행해야합니다.

요약

이 전략은 MA 크로스오버와 MACD 지표를 결합하여 비교적 완전한 거래 시스템을 구성합니다. 여러 MAs 및 여러 작업의 설계는 시스템의 트렌드 캡처 및 리스크 제어 기능을 향상시킵니다. 전략 논리는 명확하고 이해하기 쉽고 구현하기 쉽고 추가 최적화 및 개선에 적합합니다. 그러나 여전히 위험 통제에주의를 기울여 신중하게 적용해야합니다. 합리적인 최적화 및 구성으로이 전략은 견고하고 효과적인 거래 도구가 될 가능성이 있습니다.


/*backtest
start: 2023-04-06 00:00:00
end: 2024-04-11 00:00: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/
// © maxmirus

//@version=5
strategy("My strategy_Cross_SMA(EMA)+Macd,slow3",overlay=true)
// ver 4
// Date Inputs
startDate     = input(timestamp('2019-01-01T00:00:00+0300'), ''                              , inline='time1',
  tooltip=' Время первого бара расчета стратегии. Первый ордер может быть выставлен на следующем баре после стартового.')
finishDate    = input(timestamp('2044-01-01T00:00:00+0300'), ''                              , inline='time2',
  tooltip=' Время после которого больше не будут размещаться ордера входа в позицию.')

// Calculate start/end date and time condition
time_cond = true

//SMA(EMA) Inputs

fast=input.int(12, title="Fastlength",group="MA")
slow1=input.int(54,title="Slowlength1",group="MA")
slow2=input.int(100, title="Slowlength2",group="MA")
slow3=input.int(365, title="Slowlength3",group="MA")

fastma=input.string(title="Fastlength", defval="EMA",options=["SMA","EMA"],group="MA")
slowma1=input.string(title="Slowlength1", defval="EMA",options=["SMA","EMA"],group="MA")
slowma2=input.string(title="Slowlength2", defval="EMA",options=["SMA","EMA"],group="MA")
slowma3=input.string(title="Slowlength3", defval="EMA",options=["SMA","EMA"],group="MA")

fastlength = fastma == "EMA" ? ta.ema(close, fast) : ta.sma(close, fast)
slowlength1 = slowma1 == "EMA" ? ta.ema(close, slow1) : ta.sma(close, slow1)
slowlength2 = slowma2 == "EMA" ? ta.ema(close, slow2) : ta.sma(close, slow2)
slowlength3 = slowma3 == "EMA" ? ta.ema(close, slow3) : ta.sma(close, slow3)

//Macd Inputs

macdfastline = input.int(12, title="FastMacd",group="MACD")
macdslowline = input.int(26,title="SlowMacd",group="MACD")
macdhistline = input.int(9,title="HistMacd",group="MACD")
src=input(defval=close,title="Source",group="MACD")
sma_source = input.string(title="Oscillator MA Type",  defval="EMA", options=["SMA", "EMA"],group="MACD")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"],group="MACD")


fast_ma = sma_source == "SMA" ? ta.sma(src, macdfastline) : ta.ema(src, macdfastline)
slow_ma = sma_source == "SMA" ? ta.sma(src, macdslowline) : ta.ema(src, macdslowline)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, macdhistline) : ta.ema(macd, macdhistline)
hist = macd - signal
//fastMACD = ta.ema(close, macdline) - ta.ema(close, signalline)
//signalMACD = ta.ema(MACD, histline)
//histMACD = MACD - aMACD

//EMA Plot

plot(fastlength,title="SMAfast",color=color.blue)
plot(slowlength1,title="SMAslow1",color=color.orange)
plot(slowlength2,title="SMAslow2",color=color.red)
plot(slowlength3,title="SMAslow3",color=color.black)

//Macd plot
//col_macd = input(#2962FF, "MACD Line  ", group="Color Settings", inline="MACD")
//col_signal = input(#FF6D00, "Signal Line  ", group="Color Settings", inline="Signal")
//col_grow_above = input(#26A69A, "Above   Grow", group="Histogram", inline="Above")
//col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
//col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
//col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")

//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
//plot(macd, title="MACD", color=col_macd)
//plot(signal, title="Signal", color=col_signal)

//Take profit
tp1=input.float(5.1,title="Take Profit1_%",step=0.1)/100
tp2=input.float(10.1,title="Take Profit2_%",step=0.1)/100

//Stop loss
sl1=input.float(5.1,title="Stop loss1_%",step=0.1)/100
sl2=input.float(0.1,title="Stop loss2_%",step=0.1)/100
sl3=input.float(-5.5,title="Stop loss3_%", step=0.1)/100

//Qty closing position

Qty1 = input.float(0.5, title="QtyClosingPosition1",step=0.01)
Qty2 = input.float(0.25, title="QtyClosingPosition2",step=0.01)

//Take profit Long and Short

LongTake1=strategy.position_avg_price*(1+tp1)
LongTake2=strategy.position_avg_price*(1+tp2)

ShortTake1=strategy.position_avg_price*(1-tp1)
ShortTake2=strategy.position_avg_price*(1-tp2)

//Plot Levels Take 
plot(strategy.position_size > 0 ? LongTake1 : na,color=color.green,style=plot.style_linebr)
plot(strategy.position_size > 0 ? LongTake2 : na,color=color.green,style=plot.style_linebr)
plot(strategy.position_size < 0 ? ShortTake1 : na,color=color.green,style=plot.style_linebr)
plot(strategy.position_size < 0 ? ShortTake2 : na,color=color.green,style=plot.style_linebr)

//Stop loss long and short

LongStop1=strategy.position_avg_price*(1-sl1)
LongStop2=strategy.position_avg_price*(1-sl2)
LongStop3=strategy.position_avg_price*(1-sl3)
ShortStop1=strategy.position_avg_price*(1+sl1)
ShortStop2=strategy.position_avg_price*(1+sl2)
ShortStop3=strategy.position_avg_price*(1+sl3)
//Stop=strategy.position_avg_price


//Plot Levels Stop
plot(strategy.position_size > 0 ? LongStop1 : na,color=color.red,style=plot.style_linebr)
plot(strategy.position_size > 0 ? LongStop2 : na,color=color.red,style=plot.style_linebr)
plot(strategy.position_size > 0 ? LongStop3 : na,color=color.red,style=plot.style_linebr)
plot(strategy.position_size < 0 ? ShortStop1 : na,color=color.red,style=plot.style_linebr)
plot(strategy.position_size < 0 ? ShortStop2 : na,color=color.red,style=plot.style_linebr)
plot(strategy.position_size < 0 ? ShortStop3 : na,color=color.red,style=plot.style_linebr)


//Entry condition

LongCondition1 = ta.crossover(fastlength, slowlength1)
LongCondition2 = close>slowlength2
LongCondition3 = time_cond
LongCondition4=close>slowlength3
//LongCondition5=slowlength100>slowlength3
LongCondition6 = hist > 0
buy=(LongCondition1 and LongCondition2 and LongCondition3 and LongCondition4 and LongCondition6 ) and strategy.position_size<=0
//longCondition3 = nz(strategy.position_size) == 0//если отсутствует открытая позиция


ShortCondition1 = ta.crossunder(fastlength, slowlength1)
ShortCondition2 = close<slowlength2
ShortCondition3 = time_cond
ShortCondition4=close<slowlength3
//ShortCondition5=slowlength100<slowlength3
ShortCondition6=hist < 0
sell=(ShortCondition1 and ShortCondition2 and ShortCondition3 and ShortCondition4 and ShortCondition6 ) and strategy.position_size>=0



//Strategy entry

strategy.cancel_all(not strategy.position_size)

if(buy)
    strategy.cancel_all()
    strategy.entry("Buy",strategy.long)
if(sell)
    strategy.cancel_all()
    strategy.entry("Sell",strategy.short)
    
//Strategy Long exit    

var int exitCounter=0

exitCounter := not strategy.position_size or strategy.position_size > 0 and strategy.position_size[1] < 0 or strategy.position_size < 0  and strategy.position_size[1] > 0 ? 0:
               strategy.position_size > 0 and strategy.position_size[1]>strategy.position_size?  exitCounter[1] + 1:
               strategy.position_size < 0 and strategy.position_size[1]<strategy.position_size?  exitCounter[1] - 1:
               exitCounter[1]
if strategy.position_size > 0 and strategy.position_size[1]<=0
    strategy.order("Take Long1",strategy.short, qty=math.abs(strategy.position_size*Qty1), limit=LongTake1, oca_name='Long1', oca_type=strategy.oca.cancel)
if strategy.position_size > 0  and strategy.position_size[1]<=0   
    strategy.order("Take Long2",strategy.short, qty=math.abs(strategy.position_size*Qty2), limit=LongTake2, oca_name='Long2', oca_type=strategy.oca.cancel)

    
if strategy.position_size > 0  and strategy.position_size[1]<=0   
    strategy.order("Stop Long1",strategy.short, qty=math.abs(strategy.position_size),stop=LongStop1,oca_name='Long1',oca_type=strategy.oca.cancel)
if ta.change(exitCounter) and exitCounter==1
    strategy.order("Stop Long2",strategy.short, qty=math.abs(strategy.position_size),stop=LongStop2,oca_name='Long2',oca_type=strategy.oca.cancel)
if ta.change(exitCounter) and exitCounter==2
    strategy.order("Stop Long3",strategy.short, qty=math.abs(strategy.position_size),stop=LongStop3)
    
    
    
    
//  Strategy Short exit  
    
    
if strategy.position_size < 0 and strategy.position_size[1]>=0
    strategy.order("Take Short1", strategy.long, qty=math.abs(strategy.position_size*Qty1), limit=ShortTake1, oca_name='Short1', oca_type=strategy.oca.cancel)
if strategy.position_size < 0 and strategy.position_size[1]>=0 
    strategy.order("Take Short2", strategy.long, qty=math.abs(strategy.position_size*Qty2), limit=ShortTake2, oca_name='Short2', oca_type=strategy.oca.cancel)


    
if strategy.position_size < 0 and strategy.position_size[1]>=0
    strategy.order("Stop Short1",strategy.long, qty=math.abs(strategy.position_size),stop=ShortStop1,oca_name='Short1',oca_type=strategy.oca.cancel)
if ta.change(exitCounter) and exitCounter==-1
    strategy.order("Stop Short2",strategy.long, qty=math.abs(strategy.position_size),stop=ShortStop2,oca_name='Short2',oca_type=strategy.oca.cancel)
if ta.change(exitCounter) and exitCounter==-2
    strategy.order("Stop Short3",strategy.long,qty=math.abs(strategy.position_size),stop=ShortStop3)
    



관련

더 많은