모멘텀 브레이크업 및 잉글링 패턴 알고리즘 거래 전략

저자:차오장, 날짜: 2024-01-30 17:20:59
태그:

img

전반적인 설명

이 문서에서는 포괄 패턴을 통해 수익 기회를 식별하고 이동 평균과 가격 크로스오버를 입력 신호로 사용하는 알고리즘 거래 전략을 소개합니다. 이 전략은 기술 분석과 트렌드 다음 방법을 결합하여 통합 및 트렌드 역전 지점에서 수익을 창출하는 것을 목표로합니다.

원칙

이 전략의 핵심 논리는 서로 관련이 없는 두 가지 지표의 융합에 기반합니다.

  1. 잉글링 패턴: 두 개의 촛불 반전 패턴으로 두 번째 촛불의 몸체가 첫 번째의 몸체를 완전히 글빙 하는 경우, 역전 기회를 식별하는 데 사용됩니다.

  2. 이동 평균과 함께 가격 교차: 가격이 아래에서 이동 평균 라인을 넘을 때 구매 신호가 생성됩니다. 판매 신호는 가격이 위에서 이동 평균 라인을 넘을 때 발생합니다.

잠재적인 시장 전환의 시기를 포용 패턴으로 판단하고 이동 평균과 가격 크로스오버를 확인 신호로 사용하여 수익의 확률을 향상시킬 수 있습니다.

구체적으로, 이 전략은 세 가지 유형의 포괄 패턴 - 상승, 하락 및 그림자 포괄이 없는 포괄 패턴 - 을 추적하여 가능한 통합 및 반전을 결정합니다. 가격 및 이동 평균 크로스오버의 황금 십자 및 죽은 십자 신호와 함께, 개설 포지션의 방향은 최종적으로 결정됩니다.

장점

이 전략의 가장 큰 장점은 의사결정 효율성을 향상시키기 위해 관련없는 지표의 컨버전스를 활용하는 것입니다. 포용 패턴은 시장 반전의 시기와 확률을 판단합니다. 이동 평균과 가격 크로스오버는 반전의 방향과 동력을 확인합니다. 둘은 서로를 검증하고 잘못된 신호로 인한 거래 손실을 효과적으로 줄일 수 있습니다.

또 다른 장점은 매개 변수 설정의 유연성입니다. 사용자는 이동 평균 기간과 중지 손실 범위와 같은 매개 변수를 설정하여 전략을 최적화 할 수 있습니다.

위험성

여러 지표를 사용하면 판단이 향상되지만이 전략에는 여전히 잘못된 신호가 발생할 위험이 있습니다. 삼키는 패턴은 100% 신뢰할 수있는 반전 신호가 아니며 이동 평균과 가격 교차에서도 실패 시나리오가 있습니다. 이 모든 것이 조기 개시 지점으로 인한 손실로 이어질 수 있습니다.

또한, 대부분의 기술 분석 전략과 마찬가지로, 범위와 통합과 같은 충돌 트렌드 시장에서도 성능이 좋지 않습니다. 장기적인 측면 가격 움직임은 스톱 로스를 유발하거나 수익 포착 공간을 제한 할 수 있습니다.

위험을 통제하기 위해 이동 평균 기간 및 스톱 로스 범위와 같은 매개 변수는 그에 따라 조정 될 수 있습니다. 다른 지표도 동향 및 측면 시장을 식별하도록 고려 할 수 있으므로 전략 참여가 동적으로 관리 될 수 있습니다.

최적화 방향

이 전략에 따라 다음과 같은 영역을 최적화 할 수 있습니다.

  1. 가동 평균의 종류를 더 많이 테스트하여 가중화 가동 평균, 이중 평형 가동 평균 등 최적의 매개 변수 집합을 찾습니다.

  2. 측면 시장에서 포지션을 열지 않도록 트렌드 판단 지표를 추가하십시오. ADX, 볼링거 밴드 등을 예로 들 수 있습니다.

  3. 효율성을 높이기 위해 스톱 손실 방법을 최적화하십시오. 후속 스톱 손실, 캔들리어 출구가 고려 될 수 있습니다.

  4. 촛불 패턴을 판단하는 머신 러닝 방법을 늘리고 포식 인식 정확도를 향상시킵니다.

  5. 적응 조절을 위한 매개 변수 최적화 기능을 추가합니다.

결론

이 전략은 굴복 시기를 포식 패턴으로 식별하고 이동 평균과 가격 크로스오버를 사용하여 방향을 검증합니다. 지표 컨버전스를 통해 의사 결정 효율성을 향상시킴으로써 기술적 분석 접근법입니다. 장점은 보완적 지표와 유연한 매개 변수입니다. 단점은 잘못된 신호의 위험과 측면 시장의 약점입니다. 이 전략을 더욱 향상시키는 방법은 이동 평균 매개 변수 최적화, 스톱 손실 방법, 트렌드 필터링 지표 등을 추가하는 것입니다.


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

//@version=4
//@author=Daveatt

StrategyName = "BEST Engulfing + MA"
ShortStrategyName = "BEST Engulfing + MA"

strategy(title=StrategyName, shorttitle=ShortStrategyName, overlay=true)

includeEngulfing = true

includeMA = true
source_ma = input(title="Source Price vs MA", type=input.source, defval=close)
typeofMA = input(title="Type of MA", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "KMA", "TMA", "HullMA", "DEMA", "TEMA"])
length_ma = input(32, title = "MA Length", type=input.integer)

// ---------- Candle components and states
GreenCandle = close > open
RedCandle = close < open
NoBody = close==open
Body = abs(close-open)


// bullish conditions
isBullishEngulfing1 = max(close[1],open[1]) < max(close,open) and min(close[1],open[1]) > min(close,open) and Body > Body[1] and GreenCandle and RedCandle[1]
isBullishEngulfing2 = max(close[1],open[1]) < max(close,open) and min(close[1],open[1]) <= min(close,open) and Body > Body[1] and GreenCandle and RedCandle[1]

// bearish conditions
isBearishEngulfing1 = max(close[1],open[1]) < max(close,open) and min(close[1],open[1]) > min(close,open) and Body > Body[1] and RedCandle and GreenCandle[1]
isBearishEngulfing2 = max(close[1],open[1]) >= max(close,open) and min(close[1],open[1]) > min(close,open) and Body > Body[1] and RedCandle and GreenCandle[1]

// consolidation of conditions
isBullishEngulfing = isBullishEngulfing1 or isBullishEngulfing2
isBearishEngulfing = isBearishEngulfing1 or isBearishEngulfing2

//isBullishEngulfing = max(close[1],open[1]) < max(close,open) and min(close[1],open[1]) > min(close,open) and Body > Body[1] and GreenCandle and RedCandle[1]
//isBearishEngulfing = max(close[1],open[1]) < max(close,open) and min(close[1],open[1]) > min(close,open) and Body > Body[1] and RedCandle and GreenCandle[1]

Engulf_curr = 0 - barssince(isBearishEngulfing) + barssince(isBullishEngulfing)
Engulf_Buy = Engulf_curr < 0 ? 1 : 0
Engulf_Sell = Engulf_curr > 0 ? 1 : 0


// Price vs MM


smma(src, len) =>
    smma = 0.0
    smma := na(smma[1]) ? sma(src, len) : (smma[1] * (len - 1) + src) / len
    smma

ma(smoothing, src, length) => 
    if smoothing == "RMA"
        rma(src, length)
    else
        if smoothing == "SMA"
            sma(src, length)
        else 
            if smoothing == "EMA"
                ema(src, length)
            else 
                if smoothing == "WMA"
                    wma(src, length)
				else
					if smoothing == "VWMA"
						vwma(src, length)
					else
						if smoothing == "SMMA"
						    smma(src, length)
						else
							if smoothing == "HullMA"
								wma(2 * wma(src, length / 2) - wma(src, length), round(sqrt(length)))
							else
								if smoothing == "LSMA"
									src
								else
								    if smoothing == "KMA"
								        xPrice = src
                                        xvnoise = abs(xPrice - xPrice[1])
                                        nfastend = 0.666
                                        nslowend = 0.0645
                                        nsignal = abs(xPrice - xPrice[length])
                                        nnoise = sum(xvnoise, length)
                                        nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
                                        nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2) 
                                        nAMA = 0.0
                                        nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))
                                        nAMA
								    else
								        if smoothing == "TMA"
									        sma(sma(close, length), length)
						                else
							                if smoothing == "DEMA"
							                    2 * src - ema(src, length)
							                else
							                    if smoothing == "TEMA"
							                        3 * (src - ema(src, length)) + ema(ema(src, length), length) 
							                    else
		    							            src
		    							                

MA = ma(typeofMA, source_ma, length_ma)

plot(MA, color=#006400FF, title="MA breakout", linewidth=3)

macrossover  = crossover (source_ma, MA)
macrossunder = crossunder(source_ma, MA)

since_ma_buy = barssince(macrossover)
since_ma_sell = barssince(macrossunder)
macross_curr = 0 - since_ma_sell + since_ma_buy
bullish_MA_cond = macross_curr < 0 ?  1 : 0
bearish_MA_cond = macross_curr > 0 ? 1  : 0

posUp = (Engulf_Buy ? 1 : 0) + (bullish_MA_cond ? 1 : 0) 
posDn = (Engulf_Sell ? 1 : 0) + (bearish_MA_cond ? 1 : 0) 

conditionUP = posUp == 2 and posUp[1] < 2
conditionDN = posDn == 2 and posDn[1] < 2


sinceUP = barssince(conditionUP)
sinceDN = barssince(conditionDN)

// primary-first signal of the trend
nUP = crossunder(sinceUP,sinceDN)
nDN = crossover(sinceUP,sinceDN)


// and the following secondary signals

// save of the primary signal
sinceNUP = barssince(nUP)
sinceNDN = barssince(nDN)

buy_trend   = sinceNDN > sinceNUP
sell_trend  = sinceNDN < sinceNUP

// engulfing by
barcolor(nUP ? color.orange : na, title="Bullish condition")
barcolor(nDN ? color.yellow : na, title="Bearish condition")

isLong  = nUP
isShort = nDN

long_entry_price    = valuewhen(nUP, close, 0)
short_entry_price   = valuewhen(nDN, close, 0)

longClose   = close[1] < MA
shortClose  = close[1] > MA

///////////////////////////////////////////////
//* Backtesting Period Selector | Component *//
///////////////////////////////////////////////


StartYear = input(2017, "Backtest Start Year",minval=1980)
StartMonth = input(1, "Backtest Start Month",minval=1,maxval=12)
StartDay = input(1, "Backtest Start Day",minval=1,maxval=31)
testPeriodStart = timestamp(StartYear,StartMonth,StartDay,0,0)

StopYear = input(2020, "Backtest Stop Year",minval=1980)
StopMonth = input(12, "Backtest Stop Month",minval=1,maxval=12)
StopDay = input(31, "Backtest Stop Day",minval=1,maxval=31)
testPeriodStop = timestamp(StopYear,StopMonth,StopDay,0,0)

testPeriod() => true


//////////////////////////
//* Profit Component *//
//////////////////////////

input_tp_pips = input(600, "Backtest Profit Goal (in USD)",minval=0)
input_sl_pips = input(300, "Backtest STOP Goal (in USD)",minval=0)


tp = buy_trend? long_entry_price + input_tp_pips : short_entry_price - input_tp_pips
sl = buy_trend? long_entry_price - input_sl_pips : short_entry_price + input_sl_pips


long_TP_exit  = buy_trend and high >= tp
short_TP_exit = sell_trend and low <= tp

plot(tp, title="TP", style=plot.style_circles, linewidth=3, color=color.blue)
plot(sl, title="SL", style=plot.style_circles, linewidth=3, color=color.red)

if testPeriod()
    strategy.entry("Long", 1, when=isLong)
    strategy.close("Long", when=longClose )
    strategy.exit("XL","Long", limit=tp,  when=buy_trend, stop=sl)


if testPeriod()
    strategy.entry("Short", 0,  when=isShort)
    strategy.close("Short", when=shortClose )
    strategy.exit("XS","Short", when=sell_trend, limit=tp, stop=sl)


더 많은