멀티 타임프레임 이동 평균 및 MACD를 기반으로 한 긴 및 짧은 오픈 전략

저자:차오장, 날짜: 2024-01-03 12:15:46
태그:

img

전반적인 설명

이 전략은 트렌드 방향을 결정하기 위해 멀티 타임프레임 기하급수적 이동 평균 (MTF EMA) 과 트렌드 신호를 생성하기 위해 MACD 지표의 기능을 최대한 활용하며, ATR 지표로 스톱 로스 및 영리 가격을 설정합니다. 이 전략은 강력한 트렌드를 가진 디지털 및 피아트 통화 쌍에 적합하며 강한 트렌드를 가진 시장에서 더 잘 수행합니다.

전략 원칙

1. MTF EMA를 이용한 트렌드 판단

멀티 타임프레임 기하급수적 이동 평균 (MTF EMA) 은 자산의 전체 장기/단기 상태를 결정하기 위해 동일한 차트에서 여러 시간 프레임의 이동 평균을 표시할 수 있습니다. 이 전략은 1 시간 및 15 분 MTF EMA를 채택합니다.

가격이 1시간 MTF EMA 이상이고 1시간 MTF EMA가 15분 MTF EMA 이하일 때 상승 추세로 정의됩니다. 가격이 1시간 MTF EMA 이하이고 1시간 MTF EMA가 15분 MTF EMA 이상일 때 하락 추세로 정의됩니다.

2. MACD 생성 거래 신호

MACD 라인이 아래에서 신호 라인의 위를 넘을 때 구매 신호가 생성됩니다. 위에서 아래를 넘을 때 판매 신호가 생성됩니다. 동시에 잘못된 신호를 피하기 위해 MACD 라인과 신호 라인에 크로스오버 제한이 설정됩니다.

3. ATR로 손해를 멈추고 이익을 취하는 설정

ATR 지표는 스톱 로스 및 취리 가격을 설정하는 데 사용됩니다. ATR은 시장 변동성에 따라 합리적인 스톱 로스 및 취리 거리를 동적으로 설정할 수 있습니다. 동시에 스톱 로스 및 취리 곱자는 더 유연하게 만들기 위해 최고와 최저의 백테스트를 기반으로 설정됩니다.

거래 전략

오픈 포지션 신호

긴 신호: 상향 트렌드와 MACD가 신호 라인과 크로스오버 값의 한도 이하를 넘는다. 짧은 신호: 하락 추세와 MACD가 경계선 아래로 넘는다. 신호선과 크로스오버 값은 경계보다 크다.

포지션 닫기 신호

긴 수익: ATR를 통해 가격 파업이익 가격 롱 스톱 로스: ATR 스톱 로스 가격의 경로를 통과하는 가격 단기 취득: ATR를 통해 가격 파기 취득 가격 코트 스톱 로스: ATR 스톱 로스 가격의 경로를 통과하는 가격

이점 분석

이 전략의 가장 큰 장점은 트렌드를 결정하는 데 MTF EMA와 거래 신호를 생성하는 데 MACD의 장점을 완전히 활용한다는 것입니다. MTF EMA는 전반적인 트렌드 방향을 명확히 판단하고 불안정한 시장에서 빈번한 거래를 피할 수 있습니다. MACD 지표는 가격 패턴의 단기 변화를 더 잘 파악하고 거래 신호를 생성 할 수 있습니다. 둘을 함께 사용하면 더 많은 거래 기회를 얻는 동시에 트렌드를 파악 할 수 있습니다. 또한 동적으로 스톱 로스를 추적하고 이익을 취하기 위해 ATR 지표를 사용하면 개별 거래의 위험을 효과적으로 제어 할 수 있습니다.

위험 과 해결책

이 전략에는 두 가지 주요 위험이 있습니다. 첫째, 명확한 트렌드가 없으면 MTF EMA는 손실로 이어지는 잘못된 신호를 생성 할 수 있습니다. 둘째, MACD 지표는 가격이 급격히 변하면 종종 잘못된 신호를 생성하여 과도한 거래로 이어질 수 있습니다. 첫 번째 위험에 대해, MTF EMA 매개 변수는 가격 트렌드 변화에 더 잘 맞추기 위해 적절히 조정 할 수 있습니다. 두 번째 위험은 MACD 지표에 대한 크로스 오버 제한을 설정함으로써 완화 할 수 있습니다.

최적화 방향

전략의 다음 측면은 최적화 될 수 있습니다.

  1. MTF EMA의 사이클 매개 변수를 다른 거래 도구의 가격 특성에 더 잘 맞추기 위해 조정

  2. 더 나은 신호를 위해 MACD 지표의 빠르고 느린 이동 평균 및 신호 라인 매개 변수를 최적화하십시오.

  3. ATR 사이클의 다른 매개 변수와 최대의 수익을 위해 스톱 로스/프로피트 취업 곱셈을 테스트합니다.

  4. 필터 신호에 다른 보조 표시기를 추가

요약

이 긴 및 짧은 오픈 전략은 트렌드 판단을 위해 MTF EMA, 거래 신호 생성을위한 MACD 및 동적 스톱 손실 및 수익을 취하기위한 ATR의 방법을 결합합니다. 명백한 트렌드가있는 시장에서 좋은 수익을 얻을 수 있습니다. 더 나은 성과를 달성하기 위해이 전략의 매개 변수 및 최적화를 최적화 할 수있는 공간이 많습니다. 그러나 위험을 제어하고 불안정한 시장에서 맹목적 인 거래를 피해야합니다.


/*backtest
start: 2023-12-01 00:00:00
end: 2023-12-31 23:59:59
period: 1h
basePeriod: 15m
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/
// © Steven A. Zmuda Burke / stevenz17
//@version=4
// From Date Inputs
fromDay = input(defval = 01, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 04, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2022, title = "From Year", minval = 1970)
 
// To Date Inputs
toDay = input(defval = 01, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 05, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2022, title = "To Year", minval = 1970)
 
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = true

// Input
strategy("LONG", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, slippage=1, commission_type=strategy.commission.percent, 
     commission_value=0.015)
SOURCE = input(title = "═════════════════════ SOURCE ═════════════════════", defval = false, type = input.bool)
sourcehl2 = input(title="Source hl2 or (open+close)/2 ?",type=input.bool,defval=true)
source = sourcehl2 ? hl2 : ((open+close)/2)

//MTF EMA
MTFEMA = input(title = "════════════════════ MTF EMA ════════════════════", defval = false, type = input.bool)

res1=input(title="MTF EMA 1", type=input.resolution, defval="60")
len1 = input(title = "EMA Period 1", type=input.integer, defval=70, minval=1)
ema1 = ema(source, len1)
emaStep1 = security (syminfo.tickerid, res1, ema1, barmerge.gaps_off, barmerge.lookahead_off)
mtf1 = emaStep1

res2=input(title="MTF EMA 2", type=input.resolution, defval="15")
len2 = input(title = "EMA Period 2", type=input.integer, defval=68, minval=1)
ema2 = ema(source, len2)
emaStep2 = security (syminfo.tickerid, res2, ema2, barmerge.gaps_off, barmerge.lookahead_off)
mtf2 = emaStep2

t1 = plot(mtf1, linewidth=4, color= color.aqua, title="EMA")
t2 = plot(mtf2, linewidth=4, color= color.navy, title="EMA")
fill(t1, t2, transp = 70, color = mtf1 > mtf2 ? color.red : color.green)

///MACD
MACD= input(title = "═════════════════════ MACD ══════════════════════", defval = false, type = input.bool)
MACDsource=close
fastLength = input(13, minval=1, title="MACD fast moving average")
slowLength=input(18,minval=1, title="MACD slow moving average")
signalLength=input(24,minval=1, title="MACD signal line moving average")
MacdEmaLength =input(9, title="MACD EMA period", minval=1)
useEma = input(true, title="Use EMA (otherwise SMA)")
useOldAlgo = input(false, title="Use normal MACD")
Lmacsig=input(title="LONG MACD and signal crossover limit",type=input.integer,defval=180)

// Fast line
ma1= useEma ? ema(MACDsource, fastLength) : sma(MACDsource, fastLength) 
ma2 = useEma ?  ema(ma1,fastLength) :  sma(ma1,fastLength) 
fastMA = ((2 * ma1) - ma2)

// Slow line
mas1=  useEma ? ema(MACDsource , slowLength) :  sma(MACDsource , slowLength)
mas2 =  useEma ? ema(mas1 , slowLength): sma(mas1 , slowLength)
slowMA = ((2 * mas1) - mas2)

// MACD line
macd = fastMA - slowMA

// Signal line
emasig1 = ema(macd, signalLength)
emasig2 = ema(emasig1, signalLength)
signal = useOldAlgo ? sma(macd, signalLength) : (2 * emasig1) - emasig2

hist = macd - signal

histline = hist > 0 ? color.green : color.red

//MACD ribbon
macdribbon=input(title="Show MACD ribbon?",type=input.bool,defval=false)
macdx=input(title="MACD ribbon multiplier", type=input.integer, defval=3, minval=1)

leadLine1 = macdribbon ? macd*macdx + source : na
leadLine2 = macdribbon ? signal*macdx + source : na
leadLine3 = hist + source

//MACD plot
p3 = plot(leadLine1, color= color.green, title="MACD", transp = 100, linewidth = 8)
p4 = plot(leadLine2, color= color.red, title="Signal", transp = 100, linewidth = 8)
fill(p3, p4, transp = 20, color = leadLine1 > leadLine2 ? #53b987 : #eb4d5c)

plot((leadLine3), color = histline, title="Histogram", linewidth = 3) 


l="TEst"

upHist = (hist > 0) ? hist : 0
downHist = (hist <= 0) ? hist : 0

p1 = plot(upHist, color=color.green, transp=40, style=plot.style_columns, title='Positive delta')
p2 = plot(downHist, color=color.green, transp=40, style=plot.style_columns, title='Negative delta') 

zeroLine = plot(macd, color=color.black, transp=0, linewidth=2, title='MACD line')
signalLine = plot(signal, color=color.gray, transp=0, linewidth=2, title='Signal')

ribbonDiff = color.green
fill(zeroLine, signalLine, color=ribbonDiff)

circleYPosition = signal
plot(ema(macd,MacdEmaLength) , color=color.red, transp=0, linewidth=2, title='EMA on MACD line')

ribbonDiff2 = hist > 0 ? color.green : color.red
plot(crossunder(signal,macd) ? circleYPosition : na,style=plot.style_circles, linewidth=4, color=ribbonDiff, title='Dots')


//STOCHASTIC
stochchch= input(title = "═══════════════════ STOCHASTIC ════════════════════", defval = false, type = input.bool)
StochOn = input(title="Stochastic On?",type=input.bool,defval=true)
periodK = input(10, title="K", minval=1)
periodD = input(1, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
stochlimit = input(30, title="Stoch value crossover", minval=1)
k = sma(stoch(close, high, low, periodK), smoothK)
d = sma(k, periodD)

stochSignal = StochOn ? (d < stochlimit ? true : false) : true

pp= input(1, title="avg price length", minval=1)
p = ema (source, pp)
K = k + p

plot(k, title="%K", color=#0094FF)
plot(d, title="%D", color=#FF6A00)
h0 = hline(72, "Upper Band", color=#606060)
h1 = hline(20, "Lower Band", color=#606060)
fill(h0, h1, color=#9915FF, transp=80, title="Background")



//Long 
LS= "════════════════════════════════ LONG CONDITIONS ═══════════════════════════"

uptrend = close > mtf1 and mtf1 < mtf2
downtrend = close < mtf1 and mtf1 > mtf2 

crossMACD = crossunder(macd,signal) 

LongBuy = uptrend and stochSignal? crossMACD and signal < Lmacsig and macd < Lmacsig : na

LONG = strategy.position_size > 0
SHORT = strategy.position_size < 0
FLAT = strategy.position_size == 0 

plotshape(LongBuy, style=shape.xcross, text="LONG", color=color.green)

//ATR & TP/SL

ATRTPSLX= input(title = "═════════════════ LONG SL ═════════════════", defval = false, type = input.bool)

maxIdLossPcnt = input(5, "Max Intraday Loss(%)", type=input.float, minval=0.0, step=0.1)
// strategy.risk.max_intraday_loss(maxIdLossPcnt, strategy.percent_of_equity)

SSL2=input(title="Long Stop Loss when MTF EMA cross?",type=input.bool,defval=false)

SSLOP = LONG  and crossunder(source, mtf1) 

SlossPercOn = input(title="Long Stop Loss (%) on?",type=input.bool,defval=false)
SlossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=4.7) * 0.01
SSpricePerc = LONG and SlossPercOn? strategy.position_avg_price * (-1 - SlossPerc) : na
plot(series = SSpricePerc, linewidth=2, color= color.maroon,style=plot.style_linebr, title="Long Stop Loss %") 
SSLX = LONG and crossunder(source, SSpricePerc)

SSLatr= input(title="Long Stop Loss ATR?",type=input.bool,defval=true)
useStructure=input(title="Look back for High/Lows?",type=input.bool,defval=true)
Slookback=input(title="How far to look back for High/Lows:",type=input.integer,defval=18,minval=1)
SatrLenghth=input(title="Long ATR Lenghth",type=input.integer,defval=9,minval=1)
SatrStopMultiplier=input(title="Long ATR Stop x ?", type=input.float,defval=4.3, minval=0.1,step=0.1)

Satr = atr(SatrLenghth)
LongStop = SSLatr ? ((useStructure ? lowest(low, Slookback) : source) - Satr * SatrStopMultiplier) : na

SStop = crossunder(source,LongStop)

plot(Satr, color=color.blue, title="ATR", transp=100)
plot(series = uptrend ? LongStop : na, color=color.red, style=plot.style_linebr, title="Long Trailing Stop", transp=0)


ATRTPSLXX= input(title = "═════════════════ LONG TP ═════════════════", defval = false, type = input.bool)

TpPercOn = input(title="Long Take Profit (%) on?",type=input.bool,defval=true)
TpPerc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=5.3) * 0.01
TppricePerc = LONG and TpPercOn? strategy.position_avg_price * (-1 + TpPerc) : na
plot(series = TppricePerc, linewidth=2, color= color.lime,style=plot.style_linebr, title="Long Take Profit %") 
TPLX = LONG and crossunder(source, TppricePerc)

TP1=input(title="1 Long Take Profit On?",type=input.bool,defval=true)

useStructure1=input(title="Look back for High/Lows?",type=input.bool,defval=true)
STplookback=input(title="How far to look back for High/Lows for 1 TP",type=input.integer,defval=12,minval=1)
STpatrLenghth=input(title="Long ATR Lenghth 1 TP",type=input.integer,defval=24,minval=1)
SatrProfitMultiplier = input(title="First Long ATR Take Profit x ?", type=input.float,defval=5.5, minval=0.1,step=0.1)
STpatr = atr(STpatrLenghth)
LongTakeProfit = (useStructure1 ? highest(high, STplookback) : source) + STpatr * SatrProfitMultiplier
LongTP = TP1 ? crossover(source, LongTakeProfit): false
plot(series = uptrend ? LongTakeProfit: na , color=color.green, style=plot.style_linebr, title="Long Trailing Take Profit", transp=0)


// Bar color
barcolor(cross(macd, signal) ? (macd - signal > 0 ? (uptrend and macd < 0 and signal < 0 ? color.yellow : na) : (downtrend and macd > 0 and signal > 0 ? color.blue : na)) : na)

// Strategy ATR

GOLONG = LongBuy and SSLatr and FLAT

if GOLONG and TP1
    strategy.entry(id="Entry LONG 1TP", long=true,comment="Entry Long")
    strategy.exit("Long Profit or Loss 1TP","Entry LONG 1TP", limit=LongTakeProfit, stop=LongStop)
if SSLX
    strategy.close(id="Entry LONG 1TP", comment="% Long SL EXIT")
if TPLX
    strategy.close(id="Entry LONG 1TP", comment="% Long TP EXIT")
    
if SSLOP and SSL2
    strategy.close(id="Entry LONG 1TP", comment="MTF EMA cross EXIT")    
    
if (not time_cond)
    strategy.close_all()
    strategy.cancel_all()    


//plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)

//@version=4

더 많은