내부 가격 채널에 기반한 업 및 다운 전략

저자:차오장, 날짜: 2023-12-11 15:56:28
태그:

img

전반적인 설명

이 전략은 미래의 가격 트렌드를 결정하기 위해 내부 가격 채널을 활용하고 트렌드 다음 전략에 속한다. 가격이 특정 수의 내부 가격 변동 채널을 형성할 때, 그것은 긴 또는 짧은 엔트리를하기 위한 트렌드 역전 신호로 판단된다. 또한 이동 평균 필터링과 손익을 잠금하기 위한 스톱-로스/테이크-프로프트를 통합하고 있으며 비교적 일반적인 양적 거래 전략이다.

전략 원칙

전략은 이전 두 촛불의 가장 높고 가장 낮은 가격 사이의 크기 관계에 따라 내부 채널의 형성을 결정합니다. 특정 수의 촛불이 가장 높은 가격이 이전 촛불의 가장 높은 가격보다 낮고 가장 낮은 가격이 이전 촛불의 가장 낮은 가격보다 높다는 조건을 충족하면 내부 가격 채널이 식별됩니다.

내부 채널이 확인되면 전략은 또한 채널의 방향을 판단합니다. 상승 내부 채널이라면 긴 엔트리 신호가 생성됩니다. 하락 내부 채널이라면 짧은 엔트리 신호가 생성됩니다. 따라서 이것은 양방향 거래 전략입니다.

거짓 신호를 필터하기 위해 이동 평균 지표도 도입된다. 실제 거래 신호는 가격이 이동 평균 라인 이상 또는 아래에 있을 때만 생성된다. 이것은 옆 시장에서 어느 정도 잘못된 거래를 피할 수 있다.

엔트리 후, 스톱 로스 및 테이크 노프트 포인트도 사용자 선택에 따라 설정할 수 있습니다. 세 가지 사용 가능한 스톱 로스 방법이 있습니다: 고정 포인트 스톱 로스, ATR 스톱 로스, 이전 최고 / 최저 스톱 로스. 이윤은 위험 / 보상 비율에 따라 설정됩니다. 이것은 어느 정도 이익을 잠금하고 위험을 제어 할 수 있습니다.

이점 분석

이 전략의 가장 큰 장점은 트렌드 반전 지점을 식별 할 수있는 강력한 능력입니다. 가격이 특정 수의 내부 채널을 형성하면 상대적으로 큰 가격 상승/하락 움직임이 일어날 것이라는 신호가 종종 있습니다. 이 판단은 전통적인 기술 분석 이론과 매우 일치합니다.

또한, 전략 자체의 구성성은 매우 강하다. 사용자는 내부 채널의 수, 이동 평균 사이클, 스톱 로스/프로피트 메소드 등과 같은 매개 변수를 자유롭게 선택할 수 있다. 이것은 다양한 제품과 거래 스타일에 대한 큰 유연성을 제공한다.

마지막으로, 전략에 도입 된 이동 평균 필터 및 스톱 로스 / 취득 설정은 거래 위험을 크게 줄여 전략이 다양한 시장 환경에서 거래에 적응 할 수있게합니다.

위험 분석

이 전략의 가장 큰 위험은 잘못된 트렌드 판단의 상대적으로 높은 확률입니다. 내부 채널은 가격 반전을 완전히 결정할 수 없으며, 잘못된 판단의 가능성이 있습니다. 결정된 양이 충분하지 않으면 잘못된 신호가 발생할 수 있습니다.

또한, 전략은 측면 또는 변동적인 시장에서 완전히 쓸모가 없습니다. 추세를 설정하지 않고 가격이 상향과 하향 변동할 때 전략은 지속적으로 잘못된 신호를 생성합니다. 이것은 전략의 메커니즘에 의해 결정됩니다.

마지막으로, 스톱 로스가 너무 보수적으로 설정되면 전략은 주요 트렌드에서 이익을 얻기 위해 충분히 오랫동안 포지션을 유지할 수 없을 수 있습니다. 이것은 사용자가 스스로 균형을 맞추도록 요구합니다.

최적화 방향

이 전략의 최적화 공간은 여전히 상당히 크다. 몇 가지 가능한 최적화 방향은 다음과 같습니다.

  1. 내부 채널의 양과 패턴을 최적화합니다. 다른 양 또는 다른 조합 조정에 따라 거래 효과를 테스트하십시오.

  2. 트렌드 방향을 더 잘 결정하기 위해 이동 평균의 사이클 매개 변수를 최적화하십시오. 현재 기본 사이클은 모든 제품에 적합하지 않을 수 있습니다.

  3. 다른 지표 필터를 추가하십시오. 예를 들어 볼린거 밴드를 도입하고 가격이 밴드의 상부 또는 하부 레일을 뚫었을 때만 거래 신호를 생성하십시오.

  4. 전략이 더 오랫동안 포지션을 유지할 수 있도록 스톱 로스/프로피스 매개 변수를 최적화하여 슈퍼 트렌드에서 이윤을 포착합니다.

일반적으로 이 전략의 존재는 트렌드 판단의 정확성에 달려 있습니다. 판단의 정확성이 보장 될 수 있는 한 적절한 위험 관리 설정과 함께 효과적인 알고리즘 거래가 수행 될 수 있습니다.

결론

요약하자면, 이 전략은 내부 가격 채널을 기반으로 미래의 가격 추세를 결정하는 양적 거래 전략이다. 트렌드 추적 및 트렌드 역전 판단 방법을 결합하고 있으며 특정 장점을 가지고 있다. 그러나 특정 제품과 거래 환경을 충족시키기 위해 최적화 할 여지가 있다. 매개 변수 최적화 후에 가장 이상적인 양적 거래 전략 중 하나가 될 수 있다.


/*backtest
start: 2023-12-03 00:00:00
end: 2023-12-10 00:00:00
period: 3m
basePeriod: 1m
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/

// From "Day Trading Cryptocurrency 
// Strategies, Tactics, Mindset, and Tools Required To Build Your 
// New Income Stream"
// by Phil C. Senior

// "Inside bars are a two -bar pattern. They can indicate either a continuation of the 
// existing move or a reversal. A continuation occurs when there is no significant 
// support or resistance level in sight, while a reversal occurs close to a strong sup- 
// port or resistance level...
// ...A lot of traders are aware of inside bars but few manage to make money with 
// them. Why is this so? It goes back to interpreting price action. A lot of traders look 
// to trade in geometric ways. What I mean is that they search for fancy shapes on a 
// chart and think that this is what represents true price action. 
// This is not the case. A shape is just a shape. The formation by itself means 
// nothing unless underlying order flow backs it up. This is why it’s extremely impor- 
// tant that you look for inside bars when a trend is already in place. The best place to 
// look for them is in the beginning of trends."

// © tweakerID

//@version=4
strategy("Inside Bar Strategy w/ SL", 
     overlay=true, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100, 
     initial_capital=10000, 
     commission_value=0.04, 
     calc_on_every_tick=false, 
     slippage=0)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))

/////////////////////// STRATEGY INPUTS ////////////////////////////////////////
title1=input(true, "-----------------Strategy Inputs-------------------")  

i_NBars = input(defval=1, type=input.integer, title="# Of Inside Bars in pattern", options=[1, 2, 3, 4])
i_BarsDirection = input(false, title="Only trade using complete bullish or bearish patterns")
i_MAFilter = input(true, title="Use MA Trend Filter")
i_MALen = input(65, title="MA Length")

/////////////////////// BACKTESTER /////////////////////////////////////////////
title2=input(true, "-----------------General Inputs-------------------")  

// Backtester General Inputs
i_SL=input(true, title="Use Stop Loss and Take Profit")
i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])
i_SPL=input(defval=10, title="Swing Point Lookback")
i_PercIncrement=input(defval=1, step=.1, title="Swing Point SL Perc Increment")*0.01
i_ATR = input(14, title="ATR Length")
i_ATRMult = input(5, step=.1, title="ATR Multiple")
i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio")
TS=input(false, title="Trailing Stop")

// Bought and Sold Boolean Signal
bought = strategy.position_size > strategy.position_size[1] 
 or strategy.position_size < strategy.position_size[1]

// Price Action Stop and Take Profit
LL=(lowest(i_SPL))*(1-i_PercIncrement)
HH=(highest(i_SPL))*(1+i_PercIncrement)
LL_price = valuewhen(bought, LL, 0)
HH_price = valuewhen(bought, HH, 0)
entry_LL_price = strategy.position_size > 0 ? LL_price : na 
entry_HH_price = strategy.position_size < 0 ? HH_price : na 
tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR
stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR

// ATR Stop
ATR=atr(i_ATR)*i_ATRMult
ATRLong = ohlc4 - ATR
ATRShort = ohlc4 + ATR
ATRLongStop = valuewhen(bought, ATRLong, 0)
ATRShortStop = valuewhen(bought, ATRShort, 0)
LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na 
ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na 
ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR
ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR


// Strategy Stop
float LongStop = valuewhen(bought,low[1],0)*(1-i_PercIncrement)
float ShortStop = valuewhen(bought,high[1],0)*(1+i_PercIncrement)
float StratTP = na
float StratSTP = na

/////////////////////// STRATEGY LOGIC /////////////////////////////////////////

MAFilter=close > sma(close, i_MALen)
plot(i_MAFilter ? sma(close, i_MALen) : na)
bullBar=close > open
bearBar=close < open
contbullBar=barssince(not bullBar) >= (i_NBars+1)
contbearBar=barssince(not bearBar) >= (i_NBars+1)

InsideBar(NBars) =>
    Inside1Bar=high < high[1] and low > low[1] 
    Inside2Bar=high < high[2] and low > low[2] and Inside1Bar
    Inside3Bar=high < high[3] and low > low[3] and Inside1Bar and Inside2Bar
    Inside4Bar=high < high[4] and low > low[4] and Inside1Bar and Inside2Bar and Inside3Bar
    if NBars == 1
        inside1Bar=Inside1Bar
        [inside1Bar]
    else if NBars == 2
        inside2Bar=Inside2Bar
        [inside2Bar]
    else if NBars == 3
        inside3Bar=Inside3Bar   
        [inside3Bar]
    else if NBars == 4
        inside4Bar=Inside4Bar
        [inside4Bar]
    else
        [na]
[insideBar] = InsideBar(i_NBars) 
    
bullInsideBar=bar_index > 40 and insideBar and bullBar 
     and (i_BarsDirection ? contbullBar : true) and (i_MAFilter ? MAFilter : true)
bearInsideBar=bar_index > 40 and insideBar and bearBar 
     and (i_BarsDirection ? contbearBar : true) and (i_MAFilter ? not MAFilter : true)

BUY = bullInsideBar
SELL = bearInsideBar

//Debugging Plots
plot(contbullBar ? 1:0, transp=100, title="contbullBar")
plot(contbearBar ? 1:0, transp=100, title="contbearBar")

//Trading Inputs
DPR=input(true, "Allow Direct Position Reverse")
reverse=input(false, "Reverse Trades")

// Entries
if reverse
    if not DPR
        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)
    else     
        strategy.entry("long", strategy.long, when=SELL)
        strategy.entry("short", strategy.short, when=BUY)
else
    if not DPR 
        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)
    else
        strategy.entry("long", strategy.long, when=BUY)
        strategy.entry("short", strategy.short, when=SELL)

SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop
SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop
TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP
STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP

//TrailingStop
dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))
 -strategy.position_avg_price
trailOffset     = strategy.position_avg_price - SL
var tstop = float(na)
if strategy.position_size > 0
    tstop := high- trailOffset - dif
    if tstop<tstop[1]
        tstop:=tstop[1]
else
    tstop := na
StrailOffset     = SSL - strategy.position_avg_price
var Ststop = float(na)
Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 
 and strategy.position_size[1]>=0, low,0))
if strategy.position_size < 0
    Ststop := low+ StrailOffset + Sdif
    if Ststop>Ststop[1]
        Ststop:=Ststop[1]
else
    Ststop := na

strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL)
strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL)

/////////////////////// PLOTS //////////////////////////////////////////////////

plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red)
plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red)
plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green)
plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green)
// Draw price action setup arrows
plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, 
 color=color.green, title="Bullish Setup", size=size.auto)
plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, 
 color=color.red, title="Bearish Setup", size=size.auto)
 



더 많은