EMA 대역 + leledc + Bollinger 대역 트렌드 포스팅 전략

저자:차오장, 날짜: 2022-05-09 16:41:29
태그:EMA

기본 내용: 가장 간단한 형태로, 이 전략은 가격이 EMA 중간역을 넘어서면 긴 경로로 들어가고, 가격이 EMA 중간역을 넘어서면 닫거나 짧은 경로로 돌아가는 포지셔널 트렌드를 따르는 전략이다. 중간 EMA 중간역의 상단과 하단은 각각 촛불의 최고와 최저의 EMA에서 계산된다.

이 아이디어는 촛불 폐쇄를 기반으로하는 전형적인 EMA보다는 높은 EMA와 낮은 EMA의 브레이크에 거래를하는 것이 트렌드 강도를 조금 더 확인하고 쪼개지는 것을 최소화한다는 것입니다. 쪼개지는 것을 추가로 줄이기 위해 전략은 반대 EMA 대역을 넘어서면 닫습니다. (즉. 높은 EMA 중위 대역 위의 브레이크에서 길고 낮은 EMA 중위 대역 아래에 닫습니다.)

이 전략은 모든 시장에서 모든 시간 프레임에서 작동하지만 트렌드를 따르는 전략으로 암호화폐 및 기술 주식과 같은 트렌드에 취약한 시장에서 가장 잘 작동합니다. 낮은 시간 프레임에서는 더 긴 EMA가 가장 잘 작동합니다 (나는 EMA 길이에서 좋은 결과를 발견했습니다. 심지어 1000까지 높습니다.), 4H 차트 이상 EMA 길이 21 및 그 이하에서 더 잘 작동하는 경향이 있습니다.

트렌드를 확인하는 추가 필터로 두 번째 EMA를 사용할 수 있습니다. 느린 EMA 필터를 입력하면 장기 트렌드에 따라 거래가 입력되는 것을 보장 할 수 있습니다. 더 빠른 EMA 필터를 입력하면 브레이크오웃 강도를 확인 할 수 있습니다.

바 컬러링은 다른 지표나 전략과 동떨어지는 경향의 방향을 시각적으로 빠르게 식별할 수 있습니다.

상품은: 트렌드가 뒤집어지기 전에 트렌드를 기다리는 것 (특히 더 긴 기본 EMA가 사용되면) 은 종종 테이블에 돈을 남깁니다. 이 스크립트는 가장 좋은 초기 출구를 백테스트하기 위해 트렌드가 고갈되었을 때 확인하는 여러 가지 방법을 결합합니다.

중부 밴드 안의 지연된 바 - 중부 EMA 밴드 사이에 몇 개의 촛불이 연속적으로 열리고 닫히면 트렌드가 약하거나 새로운 트렌드의 시작이 아니라는 신호일 수 있습니다. 이것을 선택하면 몇 개의 바가 지나면 포지션을 닫을 것입니다.

Leledc 바 - 원래 glaz에 의해 도입, 이것은 일련의 바가 같은 방향으로 닫히고 기간 동안 최대 최고 / 낮은 결과를 초래 한 후 촛불을 강조하는 가격 행동 지표입니다. 그것은 종종 강한 트렌드가 더 이상 계속되기 전에 일시 중단되거나 트렌드의 끝을 표시 할 때 시작됩니다. 잘못된 Leledc 신호에 대한 폐쇄를 완화하기 위해이 전략에는 두 가지 옵션이 있습니다: 1. Leledc 바에 부피 증가 요구 사항을 도입하면 트렌드 중간에 발생하는 Leledc 신호를 필터링하는 데 도움이 될 수 있습니다. 2. 많은 Leledc 바가 열린 후 나타난 후 닫습니다. 이 두 옵션은 고립적으로 잘 작동하지만 테스트에서 잘 작동하지 않습니다.

볼링거 밴드 마감 바 - 이 바는 가격이 볼링거 밴드 내에 다시 닫히고 RSI가 지정된 과잉 구매 / 판매 구역 내에있을 때 강조됩니다. 아이디어는 가격이 볼링거 밴드 너머 거래 할 때 트렌드가 과잉 확장된다는 것입니다. 가격이 밴드 내에 다시 닫히면이 전략이 이상적으로 입장에 다시 들어갈 기본 EMA로 평균 회귀로 인해 발생할 수 있습니다. 추가된 RSI 요구 사항이 종종이 지표를 너무 엄격하게 만들기 때문에 충분히 큰 표본 크기를 다시 테스트하기 위해 촉발하기 때문에 나는 밴드와 RSI 두 가지 모두 기본 설정으로 볼 수있는 표준이 아닌 설정을 사용하는 것이 가장 좋습니다.

구매/판매 구역 - 폐쇄 신호로 볼링거 밴드 고갈 바를 사용하는 아이디어와 유사하다. 표준 오차를 계산하기 보다는 구매/판매 구역은 중간 EMA 밴드의 배수에서 계산된다. 이 구역을 넘어서 거래하고 나중에 내부로 다시 실패할 때, 가격은 기본 EMA로 다시 평균 회귀로 인해 발생할 수 있다. 구매/판매 구역에 대한 RSI 필터는 사용되지 않는다.

초기 폐쇄 조건이 선택되면, EMA 중위 밴드 반등에서 거래 재입구를 허용하는 것이 종종 가치가 있습니다. 촛불이 중위 EMA 밴드 내에 다시 닫을 때까지 기다리는 대신, 이 기능은 트렌드가 강할 때 때때로 일어나는 것처럼 중위 밴드에 다시 진입할 것입니다.

모든 초기 클로즈 조건이 결합될 수 있습니다. 이것들을 실험하면서 저는 더 적은 순이익을 얻을 수 있지만 거래에 더 적은 시간을 할애함에 따라 더 높은 승률과 날카로운 비율을 얻을 수 있음을 발견했습니다.

치명적인 것: 트렌드는 당신의 친구다. 하지만 트렌드를 일찍 파악하는 것이 좋을 수 없을까? 범위 시장에서 (또는이 전략에서 느린 기본 EMA를 사용하는 경우), EMA 밴드의 브레이크의 확인을 기다리는 것은 최선의 경우 이동의 절반을 놓칠 수 있으며 최악의 경우 지속적으로 쪼개질 수 있습니다. 이 전략에서 counter-trend 트레이드를 활성화하면 전략이 Leledc 바 또는 Bollinger Bands 고갈 바에 EMA 밴드의 반대편에 포지션을 입력 할 수 있습니다. 선택된 또는 외부 테스트 / 판매 구역 밖에서 높은 / 낮은 (Leledc) 또는 개방 (BB 바) 를 필요로하는 필터가 있습니다. 또한 테스트 및 테스트를 위해 여러 가지 다른 밀접 조건이 있습니다.

저는 역동 트렌드를 가장 잘 사용할 수 있는 두 가지 방법이 있습니다.

  1. 트렌드가 명백히 과도하게 확장되었을 때 평균 회전 스칼프 거래. 드롭다운 목록의 첫 5 개의 역 트렌드 종료 조건에서 선택하면 일반적으로 수익이 적지만 위험이 적어 빠르게 거래를 종료 할 수 있습니다.
  2. 트렌드를 일찍 파악하려고 노력합니다. 첫 번째 5 개 이하의 가까운 조건 중 하나를 선택하면 전략이 새로운 트렌드에 (잘못한 쪽에서) 들어가는 것처럼 행동 할 수 있습니다.

이 특징은 가격의 모든 움직임에서 이익을 얻는 데 치명적으로 효과적일 수 있으며, 올바르게 설정되지 않으면 전략의 PnL에 치명적일 수 있습니다. 반 트렌드 거래가 중간 밴드 반대편에 열리기 때문에 위험을 줄이기 위해 스톱 로스가 권장됩니다. 만약 반 트렌드 거래에 대한 스톱 로스가 비활성화되면 전략은 트렌드 시장에서 청산 될 때까지 종종 포지션을 열고 있습니다. 트레이드가 오프 사이드 인 경우. 느린 기본 EMA를 사용하면 구매/판매 구역 필터의 효과를 줄일 수 있기 때문에 트레이드를 개척하는 데 더 필요합니다. 가격이 선택된 구역 밖에서 더 빨리 트렌딩하는 데 많은 시간을 할 수 있기 때문에 첫 번째 몇 가지 폐쇄 조건이 거의 즉시 손실로 거래를 닫는 것을 유발합니다.

틈새: 나는 장기 또는 단위로 기본 설정하는 기능을 추가했습니다. 다른 기능 (EMA 중부 밴드 브레이크오웃에서 기본 장기 / 단위 이외에) 을 활성화하면 전략이 한 가지 또는 다른 방식으로 깨지는 경향이 있습니다. 기본 통화보다는 자산을 더 많이 획득하려는 시뮬레이션을 가능하게하는 기본 장기 작업합니다. 높은 FDV, 높은 인플레이션 동전에서 몇 달 동안만 하락하는 긍정적 인 결과를 얻을 수 있습니다. 그렇지 않으면 나는 내가 보유하고 주식 스팟을 보유하는 동전을위한 헤지로 기본 단위를 사용합니다. 나는 순 중립 위치를 유지함으로써 기본 자산을 보유하는 위험을 줄이는 동안 주식 사용의 유용성과 APR을 얻습니다.대부분그 시간.

면책: 이 스크립트는 EMA 밴드를 둘러싼 다양한 전략을 실험하고 백테스트하는 것을 목적으로 합니다. 이 스크립트를 라이브 트레이딩에 사용하는 것은 자신의 책임입니다. 저는 초보 코더입니다. 따라서 코드에 오류가 있을 수 있어 전략이 의도대로 동작하지 않을 수 있습니다. 제가 말할 수 있는 한, 그것은 재칠되지 않지만, 그렇지 않다는 것을 보장할 수 없습니다.

백테스트

img


/*backtest
start: 2022-04-08 00:00:00
end: 2022-05-07 23:59:00
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/
// © danielx888
// Credits to Joy_Bangla for the Leledc exhaustion bar code
// Credits to VishvaP for the 34 EMA bands code
// Credits to SlumdogTrader for the BB exhaustion code (edited for functionality)

//@version=5
//strategy(title='EMA bands + leledc + bollinger bands trend catching strategy w/ countertrend scalp', shorttitle='Trend Pooristics', overlay=true, initial_capital = 1000, commission_value= 0.036, pyramiding= 0, default_qty_type= strategy.percent_of_equity, default_qty_value= 100, margin_long=0, margin_short=0, max_bars_back=200)

EMAlength = input.int(title='EMA Length', defval=34, minval=1, step=1)

//get user inputs
needLong = input.bool(true, title = "Enable middle EMA band breakout: Long", group="Open Conditions")
needShort = input.bool(true, title = "Enable middle EMA band breakdown: Short", group="Open Conditions")
midClose = input.string('Opposite band', title='Close on crosses through middle EMA bands', tooltip='Selecting -Delayed bars inside- will delay closing positions by the specified amount of bars if candles close inside the middle EMA bands but do not breakout the opposite side.', options=['Nearest band', 'Opposite band', 'Delayed bars inside'], group='Close Conditions')
needCTlong = input.bool(false, title = "Enable counter-trend trades: Long", tooltip='Does not work with -default positioning: short- enabled',  group="Counter Trade Settings")
CTlongType = input.string('Leledc', title = 'Trigger', options=['Leledc', 'BB Exhaustion'], group='Counter Trade Settings')
needCTshort = input.bool(false, title = "Enable counter-trend trades: Short", tooltip='Does not work with -default positioning: long- enabled', group="Counter Trade Settings")
CTshortType = input.string('Leledc', title = 'Trigger', options=['Leledc', 'BB Exhaustion'], group='Counter Trade Settings')
alwaysLong = input.bool(false, title = "Enable default positioning: Long", tooltip='Does not work with -Default to short- also selected. Works best when early close conditions are used', group = 'Open Conditions')
alwaysShort = input.bool(false, title = "Enable default positioning: Short", tooltip='Does not work with -Default to long- also selected. Works best when early close conditions are used', group = 'Open Conditions')
s_longBounce = input.bool(false, 'Enable middle EMA band bounce re-entry: Long', tooltip='Works best when early close conditions are used', group= 'Open Conditions')
s_shortBounce = input.bool(false, 'Enable middle EMA band bounce re-entry: Short', tooltip='Works best when early close conditions are used', group= 'Open Conditions')
numBars = input.int(4, title='Delayed close no. of bars', minval=1, maxval=10, step=1, group='Close Conditions')
useSlowEMA = input.bool(false, title='Use slow EMA filter',tooltip='Has no effect on counter-trend trades', group='Open Conditions')
useLele = input.bool(false, title='Close on Leledc bars', group='Close Conditions')
string whichLele = input.string('First', title='Which Leledc bar?', options=['First', 'Second', 'Third', 'Fourth', 'Fifth'], group='Close Conditions')
useBBExtend = input.bool(false, title='Close on Bollinger Band exhaustion bars', tooltip='Bollinger Band Exhaustion bars are candles that close back inside the Bollinger Bands when RSI is overbought or oversold. Settings for both can be changed under the -Bollinger Bands Exhaustion Bar Settings- header.', group='Close Conditions')
string whichBBext = input.string('First', title='Which BB exhaustion bar?', options=['First', 'Second', 'Third'], group='Close Conditions')
reverBandClose = input.bool(false, title='Close on loss of Buy/Sell zone', group='Close Conditions')
whichCTband = input.string(defval = 'Inner', title = 'Leledc/BB must be outside which Buy/Sell zone to open', options=['Inner', 'Outer'], group="Counter Trade Settings")
i_CTlongCloseCond = input.string(title='Closing conditions for counter-trend longs', defval='Cross Top Middle Band', tooltip='-Cross- type close conditions market close position on candle closes above selected region \n\n-Touch- type enable trailing limit orders that follow the selected region', options=['Cross Outer Buy Zone', 'Cross Inner Buy Zone', 'Touch Inner Buy Zone', 'Cross Bottom Middle Band', 'Touch Bottom Middle Band', 'Cross Top Middle Band', 'Touch Top Middle Band', 'Cross Inner Sell Zone', 'Touch Inner Sell Zone', 'Cross Outer Sell Zone', 'Touch Outer Sell Zone', 'First Leledc', 'First BB Exhaustion'], group='Counter Trade Settings')
i_CTshortCloseCond = input.string(title='Closing conditions for counter-trend shorts', defval='First Leledc', tooltip='-Cross- type close conditions market close position on candle closes below selected region \n\n-Touch- type enable trailing limit orders that follow the selected region',options=['Cross Outer Sell Zone', 'Cross Inner Sell Zone', 'Touch Inner Sell Zone', 'Cross Top Middle Band', 'Touch Top Middle Band', 'Cross Bottom Middle Band', 'Touch Bottom Middle Band', 'Cross Inner Buy Zone', 'Touch Inner Buy Zone', 'Cross Outer Buy Zone', 'Touch Outer Buy Zone', 'First Leledc', 'First BB Exhaustion'], group='Counter Trade Settings')
i_CTlongSL = input.float(10, 'Flat stop-loss % for counter-trend longs', 0, 100, 0.1, 'Input 0 to disable stop-loss for counter-trend trades. Enabling stop-loss will not apply to middle band breakout, bounce, or default positional trades',group='Counter Trade Settings')
i_CTshortSL = input.float(10, 'Flat stop-loss % for counter-trend shorts', 0, 100, 0.1, 'Input 0 to disable stop-loss for counter-trend trades. Enabling stop-loss will not apply to middle band breakout, bounce, or default positional trades',group='Counter Trade Settings')


// calculate and plot slow EMA
showSlowEMA = input.bool(false, title='Show Slow EMA', group='Visual Elements')
slowEMAlen = input.int(200, title='Slow EMA Length', step=1, minval=1, group='Open Conditions')
slowEMA = ta.ema(close, slowEMAlen)
plot(showSlowEMA ? slowEMA : na)


maj = input(true, 'Show Leledc Exhausion Bars', group='Visual Elements')


//*****************************
// SlumdogTrader's Bollinger Bands + RSI Double Strategy - Profit Trailer
//====================================================================================================//

///////////// Bollinger Bands Settings
BBlength = input.int(20, minval=1, title='Bollinger Bands SMA Period Length', group='Bollinger Bands Exhaustion Bar Settings')
BBmult = input.float(1.8, minval=0.001, maxval=50, title='Bollinger Bands Standard Deviation', group='Bollinger Bands Exhaustion Bar Settings')
price = input(close, title='Source')
BBbasis = ta.sma(price, BBlength)
BBdev = BBmult * ta.stdev(price, BBlength)
BBupper = BBbasis + BBdev
BBlower = BBbasis - BBdev
source = close
buyEntry = ta.crossover(source, BBlower)
sellEntry = ta.crossunder(source, BBupper)
plot(BBbasis, color=color.new(color.aqua, 0), title='BBs SMA Basis Line', display=display.none)
p1 = plot(BBupper, color=color.new(color.silver, 0), title='BBs Upper Line', display=display.none)
p2 = plot(BBlower, color=color.new(color.silver, 0), title='BBs Lower Line', display=display.none)
//fill(p1, p2, display=display.none)

///////////// RSI Settings
RSIlength = input.int(8, minval=1, step=1, title='RSI Period Length', group='Bollinger Bands Exhaustion Bar Settings')
RSIos = input.int(30, minval=0, maxval=50, step=1,title='RSI Oversold Value', group='Bollinger Bands Exhaustion Bar Settings')
RSIob = input.int(70, minval=50, maxval=100, step=1, title='RSI Overbought value', group='Bollinger Bands Exhaustion Bar Settings')
vrsi = ta.rsi(price, RSIlength)
RSIoverSold = vrsi < RSIos
RSIoverBought = vrsi > RSIob

///////////// Colour Settings
switch1 = input(true, title='Enable Bollinger Bands exhaustion bar coloring', group='Visual Elements')
switch2 = input(false, title='Enable Bollinger bands exhaustion bar background coloring', tooltip='Enabling this can help visualize when dialing in Bollinger Bands and RSI settings', group='Visual Elements')
OSOBcolor = RSIoverBought and price[1] > BBupper and price < BBupper ? color.yellow : RSIoverSold and price[1] < BBlower and price > BBlower ? color.blue : na
bgcolor(switch2 ? color.new(OSOBcolor,70) : na)


///////////// RSI + Bollinger Bands Strategy
//if not na(vrsi)
//
//    if ta.crossover(vrsi, RSIoverSold) and ta.crossover(source, BBlower)
//        strategy.entry('RSI_BB_L', strategy.long, stop=BBlower, oca_type=strategy.oca.cancel, comment='RSI_BB_L')
//    else
//        strategy.cancel(id='RSI_BB_L')
//
//    if ta.crossunder(vrsi, RSIoverBought) and ta.crossunder(source, BBupper)
//        strategy.entry('RSI_BB_S', strategy.short, stop=BBupper, oca_type=strategy.oca.cancel, comment='RSI_BB_S')
//    else
//        strategy.cancel(id='RSI_BB_S')
//
//plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
//====================================================================================================//
//*****************************


//*****************************
// © Joy_Bangla Leledc Exhaustion V4
//====================================================================================================//
//min = input(false, 'Minor Leledc Exhaustion Bar ::  Show')
i_leleVol = input.bool(false, 'Require Volume breakout for Leledc bars', group='Leledc Exhaustion Bar Settings')
i_volMult = input.float(1.5,'Volume Multiplier', 0.1,20,0.1, group='Leledc Exhaustion Bar Settings')
leleVol = volume > ta.sma(volume,100)*i_volMult

leledcSrc = input(close, 'Source', group='Leledc Exhaustion Bar Settings')
maj_qual = input(6, 'Bar count no', group='Leledc Exhaustion Bar Settings')
maj_len = input(30, 'Highest / Lowest', group='Leledc Exhaustion Bar Settings')
//min_qual = input(5, 'Minor Leledc Exhausion Bar ::  Bar count no')
//min_len = input(5, 'Minor Leledc Exhausion Bar ::  Bar count no')
bindexSindex = input(1, 'bindexSindex', group='Leledc Exhaustion Bar Settings')
closeVal = input(4, 'Close', group='Leledc Exhaustion Bar Settings')

lele(qual, len) =>
    bindex = 0
    sindex = 0
    bindex := nz(bindex[bindexSindex], 0)
    sindex := nz(sindex[bindexSindex], 0)
    ret = 0
    if close > close[closeVal]
        bindex += 1
        bindex
    if close < close[closeVal]
        sindex += 1
        sindex
    
    if i_leleVol and not leleVol
        ret := 0
        ret
    else
        if bindex > qual and close < open and high >= ta.highest(high, len)
            bindex := 0
            ret := -1
            ret
        if sindex > qual and close > open and low <= ta.lowest(low, len)
            sindex := 0
            ret := 1
            ret
    return_1 = ret
    return_1

major = lele(maj_qual, maj_len)
//minor = lele(min_qual, min_len)

plotchar(maj ? major == -1 ? high : na : na, char='•', location=location.absolute, color=color.new(color.red, 0), size=size.small)
plotchar(maj ? major == 1 ? low : na : na, char='•', location=location.absolute, color=color.new(color.lime, 0), size=size.small)

//plotchar(min ? minor == 1 ? high : na : na, char='x', location=location.absolute, color=color.new(color.red, 0), size=size.small)
//plotchar(min ? minor == -1 ? low : na : na, char='x', location=location.absolute, color=color.new(color.lime, 0), size=size.small)

//leledcMajorBullish = major == 1 ? low : na
//leledcMajorBearish = major == -1 ? high : na

//leledcMinorBullish = minor == 1 ? low : na
//leledcMinorBearish = minor == -1 ? high : na

//==============================================//

//alertcondition(leledcMajorBullish, title='Major Bullish Leledc', message='Major Bullish Leledc')
//alertcondition(leledcMajorBearish, title='Major Bearish Leledc', message='Major Bearish Leledc')

//alertcondition(leledcMinorBullish, title='Minor Bullish Leledc', message='Minor Bullish Leledc')
//alertcondition(leledcMinorBearish, title='Minor Bearish Leledc', message='Minor Bearish Leledc')
//====================================================================================================//
//*****************************


//*****************************
// © VishvaP 34 EMA Bands v2
//====================================================================================================//

//Constants
//price = close
highShortEMA = ta.ema(high, EMAlength)
lowShortEMA = ta.ema(low, EMAlength)
EMA = ta.ema(close, EMAlength)

//==============================================//

//1D Bands [Not Used]
//bandsHigh = highShortEMA * math.phi
//bandsLow = lowShortEMA * math.rphi

//==============================================//

//Lower reversion zone bands (buy zone)
shortbandsHigh = ((highShortEMA - EMA) * math.phi) * math.pi + EMA
shortbandsLow = (-(EMA - lowShortEMA) * math.phi) * math.pi + EMA

//Lower reversion zone bands smoothed
shortbandsHighEMA = ta.wma(shortbandsHigh, 8)
shortbandsLowEMA = ta.wma(shortbandsLow, 8)

//==============================================//

//Higher reversion zone bands (sell zone)
phiExtensionHigh = ((highShortEMA - EMA) * math.phi) * (math.phi + 4) + EMA
phiExtensionLow = (-(EMA - lowShortEMA) * math.phi) * (math.phi + 4) + EMA

//Higher reversion zone bands smoothed
phiExtensionHighEMA = ta.wma(phiExtensionHigh, 8)
phiExtensionLowEMA = ta.wma(phiExtensionLow, 8)

//==============================================//

//Median zone bands [plot]
highP1 = plot(highShortEMA, color = color.new(color.blue, 100), title = "Top median zone")
lowP1 = plot(lowShortEMA, color = color.new(color.blue, 100), title = "Bottom median zone")
plot(EMA, color = color.new(color.gray, 100), title = "EMA")

//1D bands [not used]
//highP2 = plot(bandsHigh)
//lowP2 = plot(bandsLow)

//Lower reversion zone bands [plot]
highP3 = plot(shortbandsHighEMA, color = color.new(color.yellow, 100), title = "Lower sell zone")
lowP3 = plot(shortbandsLowEMA, color = color.new(color.teal, 100), title = "Higher buy zone")

//Higher reversion zone bands [plot]
phiPlotHigh = plot(phiExtensionHighEMA, color = color.new(color.red, 100), title = "Top sell zone")
phiPlotLow = plot(phiExtensionLowEMA, color = color.new(color.green, 100), title = "Bottom buy zone")


//==============================================//

//Sell zone region [fill]
//fill(phiPlotHigh, highP3, color.new(color.red, 85), title = "Sell zone")

//Buy zone region [fill]
//fill(lowP3, phiPlotLow, color.new(color.green, 85), title = "Buy zone")

//Median zone region [fill]
//fill(highP1, lowP1, color.new(color.gray, 70), title = "Median zone")
//====================================================================================================//
//*****************************

//assign bands for counter trend entry
float CTbandTop = na
float CTbandBottom = na 

if whichCTband == 'Inner'
    CTbandTop := shortbandsHighEMA
    CTbandBottom := shortbandsLowEMA
else 
    CTbandTop := phiExtensionHighEMA
    CTbandBottom := phiExtensionLowEMA

//build variables for open/closing conditions on crosses of middle EMA bands
crossUpTopMB = open < highShortEMA and close > highShortEMA
wiggleUpTopMB = open > highShortEMA and close > highShortEMA and close[1] <= highShortEMA[1]
crossDownTopMB = open > highShortEMA and close < highShortEMA
wiggleDownTopMB = open < highShortEMA and close < highShortEMA and close[1] >= highShortEMA[1]

crossUpBotMB = open < lowShortEMA and close > lowShortEMA
wiggleUpBotMB = open > lowShortEMA and close > lowShortEMA and close[1] <= lowShortEMA[1]
crossDownBotMB = open > lowShortEMA and close < lowShortEMA
wiggleDownBotMB = open < lowShortEMA and close < lowShortEMA and close[1] >= lowShortEMA[1]

crossUpBotInnerRB = open < shortbandsLowEMA and close > shortbandsLowEMA
wiggleUpBotInnerRB = open > shortbandsLowEMA and close > shortbandsLowEMA and close[1] <= shortbandsLowEMA[1]
crossUpBotOuterRB = open < phiExtensionLowEMA and close > phiExtensionLowEMA
wiggleUpBotOuterRB = open > phiExtensionLowEMA and close > phiExtensionLowEMA and close[1] <= phiExtensionLowEMA[1]

crossUpTopInnerRB = open < shortbandsHighEMA and close > shortbandsHighEMA
wiggleUpTopInnerRB = open > shortbandsHighEMA and close > shortbandsHighEMA and close[1] <= shortbandsHighEMA[1]
crossUpTopOuterRB = open < phiExtensionHighEMA and close > phiExtensionHighEMA
wiggleUpTopOuterRB = open > phiExtensionHighEMA and close > phiExtensionHighEMA and close[1] <= phiExtensionHighEMA[1]

crossDownBotInnerRB = open > shortbandsLowEMA and close < shortbandsLowEMA
wiggleDownBotInnerRB = open < shortbandsLowEMA and close < shortbandsLowEMA and close[1] >= shortbandsLowEMA[1]
crossDownBotOuterRB = open > phiExtensionLowEMA and close < phiExtensionLowEMA
wiggleDownBotOuterRB = open < phiExtensionLowEMA and close < phiExtensionLowEMA and close[1] >= phiExtensionLowEMA[1]

crossDownTopInnerRB = open > shortbandsHighEMA and close < shortbandsHighEMA
wiggleDownTopInnerRB = open < shortbandsHighEMA and close < shortbandsHighEMA and close[1] >= shortbandsHighEMA[1]
crossDownTopOuterRB = open > phiExtensionHighEMA and close < phiExtensionHighEMA
wiggleDownTopOuterRB = open < phiExtensionHighEMA and close < phiExtensionHighEMA and close[1] >= phiExtensionHighEMA[1]

longBounce = open > highShortEMA and close > highShortEMA and low < highShortEMA
shortBounce = open < lowShortEMA and close < lowShortEMA and high > lowShortEMA

//build variables for counter trend trades closing conditions
CTlongCloseCond = (i_CTlongCloseCond == 'Cross Inner Sell Zone' ? (crossUpTopInnerRB or wiggleUpTopInnerRB) : (i_CTlongCloseCond == 'Cross Outer Sell Zone' ? (crossUpTopOuterRB or wiggleUpTopOuterRB) : (i_CTlongCloseCond == 'Cross Top Middle Band' ? (crossUpTopMB or wiggleUpTopMB) : (i_CTlongCloseCond == 'Cross Bottom Middle Band' ? (crossUpBotMB or wiggleUpBotMB) : (i_CTlongCloseCond == 'Cross Inner Buy Zone' ? (crossUpBotInnerRB or wiggleUpBotInnerRB) : (i_CTlongCloseCond == 'Cross Outer Buy Zone' ? (crossUpBotOuterRB or crossUpBotOuterRB) : (i_CTlongCloseCond == 'First Leledc' ? major == -1 : (i_CTlongCloseCond == 'First BB Exhaustion' ? OSOBcolor == color.yellow : na))))))))
CTlongTP = (i_CTlongCloseCond == 'Touch Inner Buy Zone' ? shortbandsLowEMA : (i_CTlongCloseCond == 'Touch Top Middle Band' ? highShortEMA : (i_CTlongCloseCond == 'Touch Bottom Middle Band' ? lowShortEMA : (i_CTlongCloseCond == 'Touch Inner Sell Zone' ? shortbandsHighEMA : (i_CTlongCloseCond == 'Touch Outer Sell Zone' ? phiExtensionHighEMA : na)))))

CTshortCloseCond =  (i_CTshortCloseCond == 'Cross Inner Buy Zone' ? (crossDownBotInnerRB or wiggleDownBotInnerRB) : (i_CTshortCloseCond == 'Cross Outer Buy Zone' ? (crossDownBotOuterRB or wiggleDownBotOuterRB) : (i_CTshortCloseCond == 'Cross Bottom Middle Band' ? (crossDownBotMB or wiggleDownBotMB) : (i_CTshortCloseCond == 'Cross Top Middle Band' ? (crossDownTopMB or wiggleDownTopMB) : (i_CTshortCloseCond == 'Cross Inner Sell Zone' ? (crossDownTopInnerRB or wiggleDownTopInnerRB) : (i_CTshortCloseCond == 'Cross Outer Sell Zone' ? (crossDownTopOuterRB or crossDownTopOuterRB) : (i_CTshortCloseCond == 'First Leledc' ? major == 1 : (i_CTshortCloseCond == 'First BB Exhaustion' ? OSOBcolor == color.blue : na))))))))
CTshortTP = (i_CTshortCloseCond == 'Touch Inner Sell Zone' ? shortbandsHighEMA : (i_CTshortCloseCond == 'Touch Bottom Middle Band' ? lowShortEMA : (i_CTshortCloseCond == 'Touch Top Middle Band' ? highShortEMA : (i_CTshortCloseCond == 'Touch Inner Buy Zone' ? shortbandsLowEMA : (i_CTshortCloseCond == 'Touch Outer Buy Zone' ? phiExtensionLowEMA : na)))))

shortMidBreak = crossDownBotMB or wiggleDownBotMB
longMidBreak = crossUpTopMB or wiggleUpTopMB

//==============================================//
//longs open
if needLong
    if useSlowEMA
        if longMidBreak and close > slowEMA and open < highShortEMA
            strategy.entry('Long', strategy.long)
    else if longMidBreak
        strategy.entry('Long', strategy.long)
if strategy.position_size == 0 and s_longBounce
    if useSlowEMA
        if close > slowEMA and longBounce
            strategy.entry('Long', strategy.long)
    else if longBounce
        strategy.entry('Long', strategy.long)
//shorts open
if needShort
    if useSlowEMA
        if shortMidBreak and close < slowEMA and open > lowShortEMA
            strategy.entry('Short', strategy.short)
    else if shortMidBreak
        strategy.entry('Short', strategy.short)
if strategy.position_size == 0 and s_shortBounce
    if useSlowEMA
        if close < slowEMA and shortBounce
            strategy.entry('Short', strategy.short)
    else if shortBounce
        strategy.entry('Short', strategy.short)
//==============================================//

//calculate how many leledc bars between current bar and current position entry
int countLongLele = 0
int countShortLele = 0
int numLele = switch whichLele
    'First' => 1
    'Second' => 2
    'Third' => 3
    'Fourth' => 4
    'Fifth' => 5
int i = 0

//count leles for longs
if strategy.position_size > 0
    if useLele and numLele > 1
        while i <= 200
            if strategy.position_size[i] <= 0
                break
            if bar_index[i] == 0
                break
            if major[i] == -1
                countLongLele += 1 
            if countLongLele == numLele
                break
            i += 1
//count leles for shorts
if strategy.position_size < 0 
    if useLele and numLele > 1
        while i <= 200
            if strategy.position_size[i] >= 0
                break
            if bar_index[i] == 0
                break
            if major[i] == 1
                countShortLele += 1
            if countShortLele == numLele
                break
            i += 1

//countBullLeles() =>
//    count = 0
//    int n = 0
//    while n <= 200 and strategy.position_size[n] > 0
//        if major[n] == -1
//            count += 1
//    return_1 = count
//    return_1
//countBearLeles() =>
//    count = 0
//    int n = 0
//    while n <= 200 and strategy.position_size[n] < 0
//        if major[n] == 1
//            count += 1
//    return_1 = count
//    return_1

//calculate how many BB extension bars between current bar and current position entry
int countLongBBs = 0
int countShortBBs = 0
int numBBs = switch whichBBext
    'First' => 1
    'Second' => 2
    'Third' => 3
int n = 0

//count BB Extension bars for longs
if strategy.position_size > 0
    if useBBExtend and numBBs > 1
        while n <= 200
            if strategy.position_size[n] <= 0
                break
            if bar_index[n] == 0
                break
            if OSOBcolor[n] == color.yellow
                countLongBBs += 1 
            if countLongBBs == numBBs
                break
            n+= 1
//count BB Extension bars for shorts
if strategy.position_size < 0
    if useBBExtend and numBBs > 1
        while n <= 200
            if strategy.position_size[n] >= 0
                break
            if bar_index[n] == 0
                break
            if OSOBcolor[n] == color.blue
                countShortBBs += 1 
            if countShortBBs == numBBs
                break
            n+= 1

//identify bars crossing under extreme overbought/oversold reversion bands for strategy exits and color
showReverBars = input.bool(title='Enable Buy/Sell zone failure bar coloring', defval=false, group='Visual Elements')
whichReverBand = input.string(title='Which Buy/Sell zone?', defval='Inner', options=['Inner', 'Outer'], group='Close Conditions')

float reverBandTop = na
float reverBandBottom = na
if whichReverBand == 'Inner'
    reverBandTop := shortbandsHighEMA
    reverBandBottom := shortbandsLowEMA
else 
    reverBandTop := phiExtensionHighEMA
    reverBandBottom := phiExtensionLowEMA
crossUpRB = open < reverBandBottom and close > reverBandBottom
wiggleUpRB = open > reverBandBottom and close > reverBandBottom and close[1] <= reverBandBottom[1]
crossDownRB = open > reverBandTop and close < reverBandTop
wiggleDownRB = open < reverBandTop and close < reverBandTop and close[1] >= reverBandTop[1]

reverBarColor = crossDownRB or (wiggleDownRB and not crossDownRB[1]) ? color.orange : crossUpRB or (wiggleUpRB and not crossUpRB[1]) ? color.purple : na

//return true after specified number of bars (numBars) closes inside the mid bands but no breakout
inMid = close > lowShortEMA and close < highShortEMA and open > lowShortEMA and open < highShortEMA

isAllMid() =>
    AllMid = true
    for t = 0 to numBars by 1
        if longMidBreak[t] or shortMidBreak[t]
            AllMid := false
    AllMid

//==============================================//
//longs close
if strategy.position_size > 0
    if reverBandClose
        if reverBarColor == color.orange
            strategy.close('Long', comment = 'Close Long')
    if useBBExtend and numBBs == 1
        if OSOBcolor == color.yellow
            strategy.close('Long', comment = 'Close Long')
            if needCTshort and CTshortType == 'BB Exhaustion'
                if open > CTbandTop
                    strategy.entry(id='Counter Trend Short', comment = 'CT Short', direction=strategy.short)
    if useBBExtend and numBBs > 1
        if countLongBBs == numBBs  
            strategy.close('Long', comment = 'Close Long')
            if needCTshort and CTshortType == 'BB Exhaustion'
                if open > CTbandTop
                    strategy.entry(id='Counter Trend Short', comment = 'CT Short', direction=strategy.short)
    if useLele and numLele == 1
        if major == -1
            strategy.close('Long', comment = 'Close Long')
            if needCTshort and CTshortType == 'Leledc'
                if high > CTbandTop
                    strategy.entry(id='Counter Trend Short', comment = 'CT Short', direction=strategy.short)
    if useLele and numLele > 1
        if countLongLele == numLele
            strategy.close('Long', comment = 'Close Long')
            if needCTshort and CTshortType == 'Leledc'
                if high > CTbandTop
                    strategy.entry(id='Counter Trend Short', comment = 'CT Short', direction=strategy.short)
    if midClose == 'Nearest band'
        if crossDownTopMB or wiggleDownTopMB
            strategy.close('Long', comment = 'Close Long')
    if midClose == 'Opposite band'
        if crossDownBotMB or wiggleDownBotMB
            strategy.close('Long', comment = 'Close Long')
    if midClose == 'Delayed bars inside'
        if crossDownBotMB or wiggleDownBotMB
            strategy.close('Long', comment = 'Close Long')
        if isAllMid()
            if open[numBars] > highShortEMA and close[numBars] < highShortEMA and inMid
                strategy.close('Long', comment = 'Close Long')

//shorts close 
if strategy.position_size < 0
    if reverBandClose
        if reverBarColor == color.purple
            strategy.close('Short', comment = 'Close Short')
    if useBBExtend and numBBs == 1
        if OSOBcolor == color.blue
            strategy.close('Short', comment = 'Close Short')
            if needCTlong and CTlongType == 'BB Exhaustion'
                if open < CTbandBottom
                    strategy.entry(id='Counter Trend Long', comment = 'CT Long', direction=strategy.long)
    if useBBExtend and numBBs > 1
        if countShortBBs == numBBs
            strategy.close('Short', comment = 'Close Short')
            if needCTlong and CTlongType == 'BB Exhaustion'
                if open < CTbandBottom
                    strategy.entry(id='Counter Trend Long', comment = 'CT Long', direction=strategy.long)
    if useLele and numLele == 1
        if major == 1
            strategy.close('Short', comment = 'Close Short')
            if needCTlong and CTlongType == 'Leledc'
                if low < CTbandBottom
                    strategy.entry(id='Counter Trend Long', comment= 'CT Long', direction=strategy.long)
    if useLele and numLele > 1
        if countShortLele == numLele
            strategy.close('Short', comment = 'Close Short')
            if needCTlong and CTlongType == 'Leledc'
                if low < CTbandBottom
                    strategy.entry(id='Counter Trend Long', comment= 'CT Long', direction=strategy.long)
    if midClose == 'Nearest band'
        if crossUpBotMB or wiggleUpBotMB
            strategy.close('Short', comment = 'Close Short')
    if midClose == 'Opposite band'
        if crossUpTopMB or wiggleUpTopMB
            strategy.close('Short', comment = 'Close Short')
    if midClose == 'Delayed bars inside'
        if crossUpTopMB or wiggleUpTopMB
            strategy.close('Short', comment = 'Close Short')
        if isAllMid() 
            if open[numBars] < lowShortEMA and close[numBars] > lowShortEMA and inMid
                strategy.close('Short', comment = 'Close Short')
//==============================================//

//counter trend opens and closes
CTlongSL = strategy.position_avg_price * (1 - i_CTlongSL / 100)
CTshortSL = strategy.position_avg_price * (1 + i_CTshortSL / 100)

//CT longs open
if needCTlong and strategy.position_size == 0
    if CTlongType == 'Leledc'
        if major == 1
            if low < CTbandBottom
                strategy.entry(id='Counter Trend Long', comment = 'CT Long', direction = strategy.long)
    else
        if OSOBcolor == color.blue
            strategy.entry(id='Counter Trend Long', comment = 'CT Long', direction = strategy.long)
//CT longs closed
if strategy.position_size > 0 and strategy.opentrades.entry_id(strategy.opentrades - 1) == 'Counter Trend Long'
    if i_CTlongSL > 0
        if na(CTlongTP)
            strategy.exit(id='Counter Trend Long', stop=CTlongSL, comment = 'CT Long SL')
        else
            strategy.exit(id='Counter Trend Long', stop=CTlongSL, limit=CTlongTP, comment = 'CT Long TP/SL')
    else if i_CTlongSL == 0
        strategy.exit(id='Counter Trend Long', limit=CTlongTP, comment = 'CT Long TP')
    if CTlongCloseCond
        strategy.close(id='Counter Trend Long', comment = 'Close CT Long')

//CT shorts open
if needCTshort and strategy.position_size == 0
    if CTshortType == 'Leledc'
        if major == -1
            if high > CTbandTop
                strategy.entry(id='Counter Trend Short', comment = 'CT Short', direction=strategy.short)
    else
        if OSOBcolor == color.yellow
            strategy.entry(id='Counter Trend Short', comment= 'CT Short', direction=strategy.short)
//CT shorts closed
if strategy.position_size < 0 and strategy.opentrades.entry_id(strategy.opentrades - 1) == 'Counter Trend Short'
    if i_CTshortSL > 0
        if na(CTshortTP)
            strategy.exit(id='Counter Trend Short', stop=CTshortSL, comment = 'CT Short SL')
        else
            strategy.exit(id='Counter Trend Short', stop=CTshortSL, limit=CTshortTP, comment = 'CT Short TP/SL')
    else if i_CTshortSL == 0
        strategy.exit(id='Counter Trend Short', limit=CTshortTP, comment = 'CT Short TP')
    if CTshortCloseCond
        strategy.close(id='Counter Trend Short', comment = "Close CT Short")

//default position
if alwaysLong and not alwaysShort and strategy.position_size == 0 
    if useSlowEMA
        if close > slowEMA
            strategy.entry(id='Default Long', comment = 'Default Long', direction=strategy.long)
    else
        strategy.entry(id='Default Long', comment='Default Long', direction=strategy.long)
if alwaysShort and not alwaysLong and strategy.position_size == 0 
    if useSlowEMA
        if close < slowEMA
            strategy.entry(id='Default Short', comment = 'Default Short', direction=strategy.short)
    else
        strategy.entry(id='Default Short', comment='Default Short', direction=strategy.short)
     
//set bar colors 
trendColor = input.bool(title='Enable Trend Bar Color', tooltip='Color bars green when above mid bands, red when below, and gray when inside. Dark green and dark red bars signal a position is kept open from the delayed close settings.', defval=false, group='Visual Elements')
var colorBar = color.new(color.white, 50)
if trendColor
    if switch1
        if showReverBars
            if reverBarColor == color.purple or reverBarColor == color.orange
                colorBar := reverBarColor
            else if OSOBcolor == color.yellow or OSOBcolor == color.blue
                colorBar := OSOBcolor
            else if close > highShortEMA
                if (alwaysShort or needCTshort) and strategy.position_size < 0
                    colorBar := color.new(color.red, 0)
                else
                    colorBar := color.new(color.green, 0)
            else if close < lowShortEMA
                if (alwaysLong or needCTlong) and strategy.position_size > 0
                    colorBar := color.new(color.green, 0)
                else
                    colorBar := color.new(color.red, 0)
            else if strategy.position_size > 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
                colorBar := color.new(#0a6136, 20)
            else if strategy.position_size < 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
                colorBar := color.new(#600008, 20)
            else
                colorBar := color.new(color.gray, 0)
        else
            if OSOBcolor == color.yellow or OSOBcolor == color.blue
                colorBar := OSOBcolor
            else if close > highShortEMA
                if (alwaysShort or needCTshort) and strategy.position_size < 0
                    colorBar := color.new(color.red, 0)    
                else    
                    colorBar := color.new(color.green, 0)
            else if close < lowShortEMA
                if (alwaysLong or needCTlong) and strategy.position_size > 0
                    colorBar := color.new(color.green, 0)
                else
                    colorBar := color.new(color.red, 0)
            else if strategy.position_size > 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
                colorBar := color.new(#0a6136, 20)
            else if strategy.position_size < 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
                colorBar := color.new(#600008, 20)
            else
                colorBar := color.new(color.gray, 0)
    else if showReverBars
        if reverBarColor == color.purple or reverBarColor == color.orange
            colorBar := reverBarColor
        else if close > highShortEMA
            if (alwaysShort or needCTshort) and strategy.position_size < 0
                colorBar := color.new(color.red, 0)
            else
                colorBar := color.new(color.green, 0)
        else if close < lowShortEMA
            if (alwaysLong or needCTlong) and strategy.position_size > 0
                colorBar := color.new(color.green, 0)
            else    
                colorBar := color.new(color.red, 0)
        else if strategy.position_size > 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
            colorBar := color.new(#0a6136, 20)
        else if strategy.position_size < 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
            colorBar := color.new(#600008, 20)
        else
            colorBar := color.new(color.gray, 0)
    else
        if close > highShortEMA
            if (alwaysShort or needCTshort) and strategy.position_size < 0
                colorBar := color.new(color.red, 0)
            else    
                colorBar := color.new(color.green, 0)
        else if close < lowShortEMA
            if (alwaysLong or needCTlong) and strategy.position_size > 0
                colorBar := color.new(color.green, 0)
            else    
                colorBar := color.new(color.red, 0)
        else if strategy.position_size > 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
            colorBar := color.new(#0a6136, 20)
        else if strategy.position_size < 0 and (midClose == 'Delayed bars inside' or midClose == 'Opposite band')
            colorBar := color.new(#600008, 20)
        else
            colorBar := color.new(color.gray, 0)
else if switch1 
    if showReverBars
        if reverBarColor == color.purple or reverBarColor == color.orange
            colorBar := reverBarColor
        else if OSOBcolor == color.yellow or OSOBcolor == color.blue
            colorBar := OSOBcolor
        else 
            colorBar := na
    else
        if OSOBcolor == color.yellow or OSOBcolor == color.blue
            colorBar := OSOBcolor
        else 
            colorBar := na
else if showReverBars
    if reverBarColor == color.purple or reverBarColor == color.orange
        colorBar := reverBarColor
    else
        colorBar := na
else
    colorBar := na

//barcolor(colorBar)



관련

더 많은