리소스 로딩... 로딩...

멀티 타임프레임 MACD 이동 평균 거래 전략

저자:차오장, 날짜: 2024-01-16 14:06:10
태그:

img

전반적인 설명

이 전략은 여러 시간 프레임에 걸쳐 MACD 지표와 이동 평균을 기반으로 거래 신호를 생성합니다. 그것은 다른 기간에 MACD의 성능을 활용하고 또한 긴 위치와 짧은 위치에 대한 입출장 규칙을 설계하기 위해 다른 이동 평균에 대한 가격의 위치를 사용합니다.

전략 논리

1. MACD 지표

  • 5분, 15분, 1시간, 4시간 이동 평균을 계산합니다.
  • 다른 기간의 이동 평균과 가격의 관계를 기반으로 추세를 판단

2. RSI 지표

  • 현재 기간 및 더 높은 시간 프레임에 대한 RSI 값을 계산합니다.
  • 반전 신호를 식별하기 위해 RSI 상위 및 하위 반전을 사용합니다.

3. 촛불 모양

  • 회전 신호를 식별하기 위해 다양한 상승 및 하락 촛불 조합을 계산합니다.
  • 가격 수준과 결합한 주요 지원 및 저항 수준에주의를 기울이십시오.

4. 입국 규칙

긴 상태:

  • 현재 기간의 RSI는 하위선 이상으로 깨집니다.
  • 더 높은 기간 RSI는 상승적 분리를 나타내고 있으며, 임박한 반전을 신호합니다.

짧은 조건:

  • 현재 기간의 RSI는 상위선 아래로 떨어집니다.
  • 더 높은 기간 RSI는 하향적 분리를 나타내고 있으며, 임박한 반전을 신호합니다.

5. 출입 규칙

긴 상태에서 닫습니다:

  • 촛불은 반전 신호를 보여줍니다: 추세 반전 하향 촛불, 예를 들어 쏘닝 스타와 어두운 구름 덮개

닫기 짧은 조건:

  • 촛불은 반전 신호를 보여줍니다: 추세 반전이 상승 촛불, 예를 들어 해머 및 피어싱 패턴

6. 위험 관리

손해를 막고 수익 기준을 설정하여 손실과 수익 침식을 제한합니다.

이점 분석

  1. 더 정확한 신호를 위해 여러 표시기 조합
  2. 수익성 향상을 위해 기간별 정보를 최대한 활용합니다.
  3. 엄격한 입국 및 출입 규칙은 통제 가능한 위험을 보장합니다.

위험 과 최적화

  1. 부적절한 매개 변수 최적화가 과도한 거래로 이어질 수 있습니다.
  2. 지표 매개 변수는 다양한 제품에 최적화가 필요합니다.
  3. 동적 스톱 로스 및 수익을 취하는 것은 수익을 확보하는 데 도움이 될 수 있습니다.

요약

이것은 전반적으로 견고한 전략입니다. 여러 지표와 엄격한 입출입 규칙을 사용하여 시장 추세를 효과적으로 파악하고 거래 위험을 피할 수 있습니다. 그러나 수익 안정성을 향상시키기 위해 추가 최적화가 필요합니다.


/*backtest
start: 2023-12-01 00:00:00
end: 2023-12-31 23:59:59
period: 3h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=2

//
// Author : Jacques CRETINON
// Last Version : V1.0 11-22-2016
// 
// Risk disclaimer : Do not use this script in production environment. We assume no liability or responsibility for any damage to you, your computer, or your other property, due to the use of this script.
//
// Purpose of this script : 
// 1- use same pine code for strategy or study script (with simple modifications)
// 2- be able to send alerts : enterlong, entershort, exitlong, exitshort, stoplosslong, stoplossshort, takeprofitlong, takeprofitshort in a study script like a strategy script should do
// 3- do not repaint (I HOPE)
//
// RoadMap :
// 1- manage : Trailing Stop Loss and Trailing Stop Loss offset
//
// I use this script :
// 1- with default value for XAUUSD, current chart resolution : 1mn, large timeframe : 15mn. 
// 2- That's why I hard code MACD5 (5mn average), MACD15 (15mn average), MACD60 (1h average) ...
// 3- MACD, RSI (1mn and 15mn) and Candles info are my inputs to take any decisions
//
// I do not publish my enterLong, enterShort, exitLong and exitShort conditions (lines 204 to 207 are sample !) as they are not as perfect as I'd like. Fell free to use your own conditions :)
//
// Please, report me any bug, fell free to discuss and share. English is not my natural language, so be clement ;) Happy safe trading :)

// If you use this pine script as a 
// * STRATEGY script => uncomment line 31 and lines 210 to 215 ; comment line 34 ; change value of study_script line 37 to false
// * STUDY    script => uncomment line 34 ; comment line 31 and lines 210 to 215 ; change value of study_script line 37 to true

// STRATEGY script => uncomment ; STUDY script => comment
strategy(title = "JC_MacD_RSI_Candle_Strat", shorttitle = "JMRCS", overlay = true)

// STUDY script => uncomment ; STRATEGY script => comment
//study(title="JC_MacD_RSI_Candle_Alert", shorttitle="JMRCA", precision=0, overlay = false )

// STUDY script => study_script = true ; STRATEGY script => study_script = false
study_script = false

useCurrentRes = input(false, title="Use Current Chart Resolution")
resCustom = input(title="Use Different Timeframe ? Uncheck Box Above",  defval='1')       
res = useCurrentRes ? period : resCustom
largeTimeframe = input(title="Large timeframe ? ",  defval='15')                          

// Strategy Time limiting
useTimeLimit    = input(defval = true, title = "Use Start Time Limiter?")
startYear       = input(defval = 2016, title = "Start From Year",  minval = 0, step = 1)
startMonth      = input(defval = 11, title = "Start From Month",  minval = 0,step = 1)
startDay        = input(defval = 22, title = "Start From Day",  minval = 0,step = 1)
startHour       = input(defval = 00, title = "Start From Hour",  minval = 0,step = 1)
startMinute     = input(defval = 00, title = "Start From Minute",  minval = 0,step = 1)
inputTime   = timestamp(syminfo.timezone, startYear, startMonth, startDay, startHour, startMinute)
timeOk      = true

// when do we apply this script
run_script = (useTimeLimit and timeOk) or not useTimeLimit

// MACD strat
res_macd5_cur_close           = request.security(syminfo.tickerid, res,            sma(close   ,5 ))
res_macd15_cur_close          = request.security(syminfo.tickerid, res,            sma(close   ,15 ))
res_macd60_cur_close          = request.security(syminfo.tickerid, res,            sma(close   ,60 ))
res_macd120_cur_close         = request.security(syminfo.tickerid, res,            sma(close   ,120))
res_macd240_cur_close         = request.security(syminfo.tickerid, res,            sma(close   ,240))

// Plot MACD info
plot_macd = input(true, title="plot macd (only strategy script) ?")
plot(not study_script and run_script and plot_macd ? res_macd5_cur_close : na, title = "macd5", color = red, linewidth = 2, style = line, transp = 50)
plot(not study_script and run_script and plot_macd ? res_macd15_cur_close : na, title = "macd15", color = green, linewidth = 2, style = line, transp = 50)
plot(not study_script and run_script and plot_macd ? res_macd60_cur_close : na, title = "macd60", color = blue, linewidth = 2, style = line, transp = 50)
plot(not study_script and run_script and plot_macd ? res_macd120_cur_close : na, title = "macd120", color = fuchsia, linewidth = 2, style = line, transp = 50)
plot(not study_script and run_script and plot_macd ? res_macd240_cur_close : na, title = "macd240", color = orange, linewidth = 2, style = line, transp = 50)

// This section based on RSI strat from ChrisMoody 8/15/2014
plot_rsi = input(true, title="plot rsi info ? ")
len = input(14, minval=1, title="Length")
upLine = input(65, minval=50, maxval=90, title="Upper Line Value?")
lowLine = input(35, minval=10, maxval=50, title="Lower Line Value?")

// current Time Frame RSI
res_up_cur_close = rma(max(change(close), 0), len)
res_down_cur_close = rma(-min(change(close), 0), len)
res_rsi_cur_close = res_down_cur_close == 0 ? 100 : res_up_cur_close == 0 ? 0 : 100 - (100 / (1 + res_up_cur_close / res_down_cur_close))
res_outRSI_cur_close = request.security(syminfo.tickerid, res, res_rsi_cur_close)

res_aboveLine = res_outRSI_cur_close > upLine ? 1 : 0
res_belowLine = res_outRSI_cur_close < lowLine ? 1 : 0
res_crossUp = res_outRSI_cur_close[1] < lowLine and res_outRSI_cur_close > lowLine ? 1 : 0
res_crossDn = res_outRSI_cur_close[1] > upLine and res_outRSI_cur_close < upLine ? 1 : 0

// Large Time Frame RSI
ltf_up_cur_close = rma(max(change(close), 0), len)
ltf_down_cur_close = rma(-min(change(close), 0), len)
ltf_rsi_cur_close = ltf_down_cur_close == 0 ? 100 : ltf_up_cur_close == 0 ? 0 : 100 - (100 / (1 + ltf_up_cur_close / ltf_down_cur_close))
ltf_outRSI_cur_close = request.security(syminfo.tickerid, largeTimeframe, ltf_rsi_cur_close)

ltf_aboveLine = ltf_outRSI_cur_close > upLine ? 1 : 0
ltf_belowLine = ltf_outRSI_cur_close < lowLine ? 1 : 0
ltf_crossUp = ltf_outRSI_cur_close[1] < lowLine and ltf_outRSI_cur_close > lowLine ? 1 : 0
ltf_crossDn = ltf_outRSI_cur_close[1] > upLine and ltf_outRSI_cur_close < upLine ? 1 : 0

// Plot RSI info
bgcolor(run_script and plot_rsi and res_aboveLine ? red : na, transp=70)
bgcolor(run_script and plot_rsi and res_crossDn ? red : na, transp=40)
bgcolor(run_script and plot_rsi and res_belowLine ? green : na, transp=70)
bgcolor(run_script and plot_rsi and res_crossUp ? green : na, transp=40)
bgcolor(run_script and plot_rsi and ltf_aboveLine ? orange : na, transp=70)
bgcolor(run_script and plot_rsi and ltf_crossDn ? orange : na, transp=40)
bgcolor(run_script and plot_rsi and ltf_belowLine ? blue : na, transp=70)
bgcolor(run_script and plot_rsi and ltf_crossUp ? blue : na, transp=40)

// This section based on [RS]Fractal Levels  by RicardoSantos
plot_candle = input(true, title="plot all candle info (only strategy script) ?")
showfractals = input(true, title="plot fractals info (only strategy script) ?")
showlevels = input(true, title="plot level info (only strategy script) ?")

topfractal = high[2] > high[1] and high[2] > high and high[2] > high[3] and high[2] > high[4]
botfractal = low[2] < low[1] and low[2] < low and low[2] < low[3] and low[2] < low[4]
topfractals = topfractal ? high[2] : topfractals[1]
botfractals = botfractal ? low[2] : botfractals[1]
topfcolor = topfractals != topfractals[1] ? na : green
botfcolor = botfractals != botfractals[1] ? na : red

// This section based on "Candlestick Trend Indicator v0.5"  by JustUncleL Date: 12-Aug-2016  Version: v0.5on Almost Zero Lag EMA [LazyBear]
// PBar Percentages
pctP = input(66, minval=1, maxval=99, title="Directional PBars, % of Range of Candle the Long Wick Has To Be")
pctCp = pctP * .01

// Shaved Bars Percentages
pctS = input(5, minval=1, maxval=99, title="Shaved Bars, % of Range it Has To Close On The Lows or Highs")
pctCs = pctS * .01
pctSPO = pctCs

// range
range = high - low

// discard candle with a little body (addon by cretinon)
tradable_val = input(3, minval=-1, title="min body size factor ? WARNING see pine code to understand") 
body = abs(open - close)
pbody = ((body  / max(high, low)) * 10000 ) > tradable_val ? true : false

// Reversal PinBars %
pctRP = input(72, minval=1, maxval=99, title="Reversal PBars, % of Range of Candle the Long Wick Has To Be")
pctCRp = pctRP * .01
pctCRPO = 1 - pctCRp

// Reversal Pin Bar Lookback Length
pblb =input(6,minval=1,title="Reversal Pin Bar Lookback Length")
pBarRUp = open > high - (range * pctCRPO) and close > high - (range * pctCRPO) and low <= lowest(pblb) ? 1 : 0
pBarRDn = open < high - (range *  pctCRp) and close < high-(range * pctCRp) and high >= highest(pblb) ? 1 : 0

// Shaved Bars filter to the MA50 line
sBarUp   = (close >= (high - (range * pctCs)))  
sBarDown = (close <= (low + (range * pctCs)))

// Inside Bars
insideBarUp = (high < high[1] and low > low[1])
insideBarDn = (high < high[1] and low > low[1])
outsideBarUp= (high > high[1] and low < low[1])
outsideBarDn= (high > high[1] and low < low[1])

// Calculing candles info (only if body is not too small - by cretinon)
pBarDn = open < high - (range * pctCp) and close < high - (range * pctCp)
pBarUp = open > low + (range * pctCp) and close > low + (range * pctCp)
dcc = pbody and ((close[1]>open[1] and abs(close[1]-open[1])/range[1]>=0.7 and close<open and abs(close-open)/range>=0.7 and open>=close[1] and close>open[1] and close<((open[1]+close[1])/2)))
pln= pbody and ((close[1]<open[1] and abs(open[1]-close[1])/range[1]>=0.7 and close>open and abs(close-open)/range>=0.7 and open<=close[1] and close<open[1] and close>((open[1]+close[1])/2)))
beh = pbody and ((close[1] > open[1] and open > close and open <= close[1] and low >= open[1] and open - close < close[1] - open[1] and (high < high[1] and low > low[1])))
blh = pbody and ((open[1] > close[1] and close > open and close <= open[1] and high <= open[1] and close - open < open[1] - close[1] and (high < high[1] and low > low[1])))
bee = pbody and ((close[1] > open[1] and close < open and close<=low[1] and open>= close[1]))
ble = pbody and ((close[1] < open[1] and close > open and close >= high[1] and open<=close[1]))
blfr = pbody and (crossover(close,topfractals))
befr = pbody and (crossunder(close,botfractals))
// Hammer and Inverted Hammer rewrite by cretinon
pHammer = pbody and (pBarUp and (not pBarRUp and not pBarRDn)) ? true :false
pIHammer = pbody and (pBarDn and (not pBarRUp and not pBarRDn)) ? true : false

// Plot candle info
location_Bearish = not study_script ? location.abovebar : location.bottom 
location_Bullish = not study_script ? location.belowbar : location.bottom
plotshape(run_script and plot_candle ? pIHammer : na, title= "Bearish Pin Bar",  color=red, style=shape.arrowdown, location=location_Bearish , text="Bearish\nPinBar")
plotshape(run_script and plot_candle and pHammer,  title= "Bullish Pin Bar", location=location_Bullish, color=green, style=shape.arrowup, text="Bullish\nPinBar")
plotshape(run_script and plot_candle and dcc, title="Dark Cloud Cover",text='DarkCloud\nCover',color=red, style=shape.arrowdown,location=location_Bearish)
plotshape(run_script and plot_candle and pln, title="Piercieng Line",text="Piercing\nLine",color=green, style=shape.arrowup,location=location_Bullish)
plotshape(run_script and plot_candle and beh and not dcc, title= "Bearish Harami",  color=red, style=shape.arrowdown,location=location_Bearish, text="Bear\nHarami")
plotshape(run_script and plot_candle and blh and not pln,  title= "Bullish Harami", location=location_Bullish, color=green, style=shape.arrowup, text="Bull\nHarami")
plotshape(run_script and plot_candle and bee, title= "Bearish Engulfing", color=red, style=shape.arrowdown, location=location_Bearish, text="Bearish\nEngulf")
plotshape(run_script and plot_candle and ble, title= "Bullish Engulfing", location=location_Bullish, color=green, style=shape.arrowup, text="Bullish\nEngulf")
plotshape(run_script and plot_candle and blfr and not ble and not blh and not sBarUp, title= "Bullish Fractal Cross", location=location_Bullish, color=green, style=shape.arrowup, text="Fractal\nCross")
plotshape(run_script and plot_candle and befr and not bee and not beh and not sBarDown,  title= "Bearish Fractal Cross", location=location_Bearish, color=red, style=shape.arrowdown, text="Fractal\nCross")
plotshape(run_script and showlevels ? topfractal : na, color=green, transp=0, style=shape.triangleup, location=location_Bearish, offset=-2, size=size.tiny)
plotshape(run_script and showfractals ? botfractal : na, color=red, transp=0, style=shape.triangledown, location=location_Bullish, offset=-2, size=size.tiny)
plot(study_script ? na : run_script and showlevels ? topfractals : na, color=topfcolor, transp=0, linewidth=2)
plot(study_script ? na : run_script and showfractals ? botfractals : na, color=botfcolor, transp=0, linewidth=2)

// Risk management
inpTakeProfit   = input(defval = 1500, title = "Take Profit", minval = 0)                        
inpStopLoss     = input(defval = 100, title = "Stop Loss", minval = 0)                           
inpTrailStop    = input(defval = 0, title = "Trailing Stop Loss", minval = 0)                    
inpTrailOffset  = input(defval = 0, title = "Trailing Stop Loss Offset", minval = 0)             
useTakeProfit   = inpTakeProfit  >= 1 ? inpTakeProfit  : na
useStopLoss     = inpStopLoss    >= 1 ? inpStopLoss    : na
useTrailStop    = inpTrailStop   >= 1 ? inpTrailStop   : na
useTrailOffset  = inpTrailOffset >= 1 ? inpTrailOffset : na

// Condition to enter/exit short/long
enterLong =  (run_script) and res_crossUp
enterShort = (run_script) and res_crossDn
exitLong =   (run_script) and pIHammer
exitShort =  (run_script) and pHammer

// STRATEGY script => uncomment ; STUDY script => comment
strategy.entry( id = "Long", long = true, when = enterLong )
strategy.close( id = "Long", when = exitLong )
strategy.entry( id = "Short", long = false, when = enterShort )
strategy.close( id = "Short", when = exitShort )
strategy.exit("Exit Long", from_entry = "Long", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Short", from_entry = "Short", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)

// Transform strtegy to alert by cretinon
last_long_trade_value = enterLong[1] ? close[1] : last_long_trade_value[1]
last_short_trade_value = enterShort[1] ? close[1] : last_short_trade_value[1]
are_we_long  = exitLong[1]  ? false : enterLong[1]  ? true : enterShort[1] ? false : are_we_long[1]  and last_long_trade_value  + useTakeProfit/100 <= high[1] ? false : are_we_long[1]  and last_long_trade_value  - useStopLoss/100 >= low[1]  ? false : are_we_long[1]
are_we_short = exitShort[1] ? false : enterShort[1] ? true : enterLong[1]  ? false : are_we_short[1] and last_short_trade_value - useTakeProfit/100 >= low[1]  ? false : are_we_short[1] and last_short_trade_value + useStopLoss/100 <= high[1] ? false : are_we_short[1]
plot_info = (not are_we_long[2] and not are_we_short[2] and enterLong[1])  ? 1 : (not are_we_long[2] and not are_we_short[2] and enterShort[1]) ? 2 : (not are_we_long[2] and not are_we_short[2] and exitLong[1]) ? -1 : (not are_we_long[2] and not are_we_short[2] and exitShort[1]) ? -2 : (are_we_long[2] and enterLong[1]) ? -3 : (are_we_long[2] and enterShort[1]) ? 3 : (are_we_long[2] and exitLong[1]) ? 4 : (are_we_long[2] and exitShort[1]) ? -4 : (are_we_long[2] and last_long_trade_value  + useTakeProfit/100 <= high[1]) ? 5 : (are_we_long[2] and last_long_trade_value  - useStopLoss/100 >= low[1]) ? 6 :(are_we_short[2] and enterLong[1]) ? 7 : (are_we_short[2] and enterShort[1]) ? -5 : (are_we_short[2] and exitLong[1]) ? -6 : (are_we_short[2] and exitShort[1]) ? 8 : (are_we_short[2] and last_short_trade_value - useTakeProfit/100 >= low[1]) ? 9 : (are_we_short[2] and last_short_trade_value + useStopLoss/100 <= high[1]) ? 10 : -7 

// plot : debbuging purpose
plot(study_script ? plot_info : na, title="plot_info", color=yellow, style=line, linewidth=4)

// alertcondition
// STRATEGY script => comment ; STUDY script => uncomment
alertcondition(plot_info == 1,title="enterLong", message="enterLong")
alertcondition(plot_info == 2,title="enterShort", message="enterShort")
alertcondition(plot_info == 3,title="enterShort", message="enterShort after Long")
alertcondition(plot_info == 4,title="exitLong", message="exitLong")
alertcondition(plot_info == 5,title="exitLong", message="TakeProfitLong")
alertcondition(plot_info == 6,title="exitLong", message="StopLossLong")
alertcondition(plot_info == 7,title="enterLong", message="enterLong after Short")
alertcondition(plot_info == 8,title="exitShort", message="exitShort")
alertcondition(plot_info == 9,title="exitShort", message="TakeProfitShort")
alertcondition(plot_info == 10,title="exitShort", message="StopLossShort") 

더 많은