가격 내부 변동 채널을 기반으로 한 강세 및 약세 전략


생성 날짜: 2023-12-11 15:56:28 마지막으로 수정됨: 2023-12-11 15:56:28
복사: 2 클릭수: 590
avatar of ChaoZhang ChaoZhang
1
집중하다
1621
수행원

가격 내부 변동 채널을 기반으로 한 강세 및 약세 전략

개요

이 전략은 가격 내부 채널을 사용하여 미래의 가격 움직임을 판단하는 경향 추적 전략에 속한다. 가격이 일정 수의 내부 가격 변동 채널을 형성할 때, 추세 전환 신호로 판단하여 구매 또는 판매 작업을 수행한다. 또한 이동 평균 필터링과 스톱 손실 스톱 설정을 결합하여 수익을 잠금하는 것이 더 일반적인 양적 거래 전략에 속한다.

전략 원칙

이 전략은 내부 통로의 형성을 판단하는 것은 앞뒤의 두 개의 K 라인의 최고 가격과 최저 가격의 크기의 관계에 따라 결정된다. 특정 수의 K 라인이 최고 가격이 이전 K 라인 최고 가격보다 낮고 최저 가격이 이전 K 라인 최저 가격보다 높다는 조건을 충족하면 가격 내부 통로로 판단된다.

가격 내부 통로가 형성되는 것을 판단하는 동시에, 전략은 그 내부 통로의 방향을 판단한다. 낙점 내부 통로가 있다면, 구매 신호를 생성한다. 낙점 내부 통로가 있다면, 판매 신호를 생성한다. 따라서, 이 전략은 양방향 거래 전략에 속한다.

가짜 신호를 필터링하기 위해 이 전략은 이동 평균 지표를 도입하기도 한다. 가격이 above 또는 below 이동 평균일 때만 실제 거래 신호를 생성한다. 이것은 시장의 정리를 위한 잘못된 거래를 어느 정도 피할 수 있다.

입시 후, 전략은 또한 사용자의 선택에 따라, 중지 손실 막점을 설정할 수 있다. 선택 가능한 중지 방식은 세 가지로 나눌 수 있다: 고정 포인트 중지, 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)