전략에 따른 역동적 경향

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

img

전반적인 설명

이 전략의 주요 아이디어는 트렌드가 상승할 때 구매하고 트렌드가 하락할 때 판매함으로써 시장 트렌드를 동적으로 추적하는 것입니다. 선형 회귀, 수정된 헐 이동 평균 등과 같은 트렌드 방향을 결정하기 위해 여러 기술적 지표를 결합합니다.

전략 논리

이 전략은 트렌드 방향을 결정하기 위해 다양한 기술적 지표를 사용합니다. 먼저, 그것은 닫는 간단한 이동 평균과 입력 매개 변수에 기초한 상부 및 하부 한계를 가진 가격 채널을 계산합니다. 그런 다음, 트렌드를 묘사하는 데 더 나은 것으로 간주되는 수정 된 헐 이동 평균을 계산합니다. 또한, 선형 회귀 지표도 계산됩니다. 수정 된 HMA가 선형 회귀선을 넘을 때 구매 신호를 생성하고, 아래를 넘을 때 판매 신호를 생성합니다. 이것은 동적으로 트렌드의 변화를 추적 할 수 있습니다.

잘못된 신호를 줄이기 위해 전략은 EMA를 사용하여 하락 추세인지 확인하는 것과 RSI 분리를 확인하는 창 표시기를 사용하는 것과 같은 여러 필터를 포함합니다. 이러한 필터는 흔들리는 측면 시장에서 거래를 피하는 데 도움이됩니다.

엔트리 및 출구의 경우, 전략은 마지막 오픈 포지션의 가격을 기록하고, 수익을 취하고 손실을 멈추는 비율을 설정합니다. 예를 들어, 마지막 긴 엔트리 가격이 100 달러라면, 수익을 취하는 목표를 102 달러로 설정하고 손실을 멈추는 가격을 95 달러로 설정할 수 있습니다. 이것은 트렌드의 동적 추적을 달성합니다.

이점 분석

이 전략은 다음과 같은 장점을 가지고 있습니다.

  1. 동적으로 트렌드 변화를 추적하면 장기적인 방향 움직임을 부드럽게 잡을 수 있습니다.
  2. 여러 필터를 사용하면 소음을 줄이고 불안한 시장에서 과도한 거래를 피합니다.
  3. 자동으로 스톱 로즈와 수익을 취하는 레벨을 조정하면 트렌드를 따라가게 됩니다.
  4. 매개 변수는 백테스팅을 통해 최적화되어 자동으로 최상의 조합을 찾을 수 있습니다.

위험 분석

이 전략에는 몇 가지 위험도 있습니다.

  1. 여전히 트렌드 반전으로 완전히 잡히지 않을 수 없습니다. 트렌드가 반전되면 더 큰 부동 손실로 이어질 수 있습니다.
  2. 부적절한 매개 변수 설정은 나쁜 전략 성능을 초래할 수 있습니다. 최적화를 필요로 합니다.
  3. 긴 데이터 처리 시간이 신호 지연을 유발할 수 있습니다. 가능한 한 실시간으로 지표 계산을 최적화해야합니다.

위험을 제어하기 위해, Stop Loss를 설정하고, Trailing Stop 또는 Options를 사용하여 수익을 잠금 할 수 있습니다. 또한, 신뢰할 수있는 범위를 찾기 위해 매개 변수 조합의 광범위한 테스트가 필요합니다. 마지막으로, 시시 신호를 보장하기 위해 지표의 실행 시간을 모니터링해야합니다.

최적화 방향

이 전략은 다음과 같은 측면에서 개선될 수 있습니다.

  1. 더 많은 지표의 조합을 테스트하여 추세를 결정하는 더 신뢰할 수있는 방법을 찾습니다.
  2. 최적의 매개 변수를 찾기 위해 매개 변수 범위를 조정합니다.
  3. 신호 필터를 최적화하여 소음 감소와 지연 사이의 균형을 찾으십시오.
  4. 자동으로 거래 규칙을 생성하기 위해 기계 학습 방법을 시도하십시오.

최적화 과정에서 신호 품질과 안정성을 평가하기 위해 백테스팅과 종이 거래가 광범위하게 활용되어야 합니다. 라이브 거래에서는 잘 검증된 최적화만 적용되어야 합니다.

결론

전체적으로 이것은 트렌드를 따르는 좋은 전략이다. 트렌드를 측정하기 위해 여러 지표를 사용하고, 잘못된 신호를 줄이기 위해 필터를 설정하고, 트렌드를 따르기 위해 자동으로 정지 및 목표를 조정할 수 있다. 적절한 매개 변수 조정을 통해 중장기 트렌드를 원활하게 파악할 수 있다. 다음 단계는 최적의 매개 변수를 찾고, 전략을 검증하고 개선하는 것을 계속하는 것이다.


/*backtest
start: 2023-12-03 00:00:00
end: 2023-12-06 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/
// © RafaelZioni

//@version=4
strategy(title = " BTC 15 min", overlay = true, pyramiding=1,initial_capital = 10000, default_qty_type= strategy.percent_of_equity, default_qty_value = 20, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.075)
strat_dir_input = input(title="Strategy Direction", defval="all", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
strategy.risk.allow_entry_in(strat_dir_value)
price = close
length8 = input(30,title = 'length of channel')
upmult = input(title = 'upper percent',type=input.float, step=0.1, defval=5)
lowmult = input(title = 'lower percent',type=input.float, step=0.1, defval=5)

basis = sma(close, length8)

vup = upmult * price / 100
vlow = lowmult * price / 100

upper = basis + vup
lower = basis - vlow
plot(basis, color=color.red)


//
fastLength = input(3, title="Fast filter length ", minval=1)
slowLength = input(21,title="Slow filter length",  minval=1)
source=close
v1=ema(source,fastLength)
v2=ema(source,slowLength)
//

leng=1
p1=close[1]

len55 = 10
//taken from https://www.tradingview.com/script/Ql1FjjfX-security-free-MTF-example-JD/
HTF = input("1D", type=input.resolution)
ti = change( time(HTF) ) != 0
T_c = fixnan( ti ? close : na )

vrsi = rsi(cum(change(T_c) * volume), leng)
pp=wma(vrsi,len55)

d=(vrsi[1]-pp[1])
len100 = 10
x=ema(d,len100)
//
zx=x/-1
col=zx > 0? color.lime : color.orange

//

tf10 = input("1", title = "Timeframe", type = input.resolution, options = ["1", "5", "15", "30", "60","120", "240","360","720", "D", "W"])

length = input(50, title = "Period", type = input.integer)
shift = input(1, title = "Shift", type = input.integer)

hma(_src, _length)=>
    wma((2 * wma(_src, _length / 2)) - wma(_src, _length), round(sqrt(_length)))
    
hma3(_src, _length)=>
    p = length/2
    wma(wma(close,p/3)*3 - wma(close,p/2) - wma(close,p),p)

b =security(syminfo.tickerid, tf10, hma3(close[1], length)[shift])
//plot(a,color=color.gray)
//plot(b,color=color.yellow)
close_price = close[0]
len = input(25)

linear_reg = linreg(close_price, len, 0)




buy=crossover(linear_reg, b) 
sell=crossunder(linear_reg, b) or crossunder(close[1],upper)
//

src2=low
src3=high
Min =input(15)
leni = timeframe.isintraday and timeframe.multiplier >= 1 ? 
   Min / timeframe.multiplier * 7 : 
   timeframe.isintraday and timeframe.multiplier < 60 ? 
   60 / timeframe.multiplier * 24 * 7 : 7

l1 = wma(src2,leni)
h1 = wma(src3,leni)
//
m=(h1+l1)/2
//
len5 = 100

src5=m

//
multi = 2

mean = ema(src5, len5)  
stddev = multi * stdev(src5, len5)  
b5 = mean + stddev
s5 = mean - stddev


var bool long = na
var bool short = na

long :=crossover(src5, s5) 
short :=  crossunder(src5, b5)

var float last_open_long = na
var float last_open_short = na

last_open_long := long ? close : nz(last_open_long[1])
last_open_short := short ? close : nz(last_open_short[1])


entry_value =last_open_long
entry_value1=last_open_short

r=100
//
highb = highest(entry_value1, r)  
lowb = lowest(entry_value, r)  
d5 = highb - lowb  
me = (highb + lowb) / 2  
h4 = highb - d5 * 0.236  
c3 = highb - d5 * 0.382  
c4 = highb - d5 * 0.618  
l4 = highb - d5 * 0.764  
//
col2 = close >= me ? color.lime : color.red
       
p5 = plot(upper, color=col2)
p2 = plot(lower, color=col2)
fill(p5, p2,color=col2)
// Conditions

longCond = bool(na)
shortCond = bool(na)
longCond := crossover(zx,0) or buy 
shortCond := sell

// Count your long short conditions for more control with Pyramiding

sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])

if longCond
    sectionLongs := sectionLongs + 1
    sectionShorts := 0
    sectionShorts

if shortCond
    sectionLongs := 0
    sectionShorts := sectionShorts + 1
    sectionShorts

// Pyramiding

pyrl = 1


// These check to see your signal and cross references it against the pyramiding settings above

longCondition = longCond and sectionLongs <= pyrl
shortCondition = shortCond and sectionShorts <= pyrl

// Get the price of the last opened long or short

last_open_longCondition = float(na)
last_open_shortCondition = float(na)
last_open_longCondition := longCondition ? open : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? open : nz(last_open_shortCondition[1])

// Check if your last postion was a long or a short

last_longCondition = float(na)
last_shortCondition = float(na)
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])

in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition

// Take profit

isTPl = true
//isTPs = input(false, "Take Profit Short")
tp = input(2, "Exit Profit %", type=input.float)
long_tp = isTPl and crossover(high, (1 + tp / 100) * last_open_longCondition) and longCondition == 0 and in_longCondition == 1
//short_tp = isTPs and crossunder(low, (1 - tp / 100) * last_open_shortCondition) and 
   //shortCondition == 0 and in_shortCondition == 1

// Stop Loss

isSLl = input(true,"buy Loss Long")
//isSLs = input(false, "buy Loss Short")
sl = 0.0
sl := input(5, " rebuy %", type=input.float)
long_sl = isSLl and crossunder(low, (1 - sl / 100) * last_open_longCondition) and 
   longCondition == 0 and in_longCondition == 1
//short_sl = isSLs and crossover(high, (1 + sl / 100) * last_open_shortCondition) and 
   //shortCondition == 0 and in_shortCondition == 1

//
// Conditions

longCond5 = bool(na)
shortCond5 = bool(na)
longCond5 := longCondition
shortCond5 := long_tp

// 

sectionLongs5 = 0
sectionLongs5 := nz(sectionLongs5[1])
sectionShorts5 = 0
sectionShorts5 := nz(sectionShorts5[1])

if longCond5
    sectionLongs5 := sectionLongs5 + 1
    sectionShorts5 := 0
    sectionShorts5

if shortCond5
    sectionLongs5 := 0
    sectionShorts5 := sectionShorts5 + 1
    sectionShorts5

// 

pyr5 = 1


longCondition5 = longCond5 and sectionLongs5 <= pyr5
shortCondition5 = shortCond5 and sectionShorts5 <= pyr5

// Get the price of the last opened long or short

last_open_longCondition5 = float(na)
last_open_shortCondition5 = float(na)
last_open_longCondition5 := longCondition5 ? open : nz(last_open_longCondition5[1])
last_open_shortCondition5 := shortCondition5 ? open : nz(last_open_shortCondition5[1])

last_longCondition5 = float(na)
last_shortCondition5 = float(na)
last_longCondition5 := longCondition5 ? time : nz(last_longCondition5[1])
last_shortCondition5 := shortCondition5 ? time : nz(last_shortCondition5[1])

in_longCondition5 = last_longCondition5 > last_shortCondition5
in_shortCondition5 = last_shortCondition5 > last_longCondition5
//
filter=input(true)
g(v, p) => round(v * (pow(10, p))) / pow(10, p)
risk     = input(100)
leverage = input(1)
c = g((strategy.equity * leverage / open) * (risk / 100), 4)

//
l =(v1 > v2 or filter == false ) and longCondition or long_sl
//
//l = longCondition or long_sl
s=shortCondition5  
if l 
    strategy.entry("buy", strategy.long,c)
if s 
    strategy.entry("sell", strategy.short,c)


per(pcnt) =>
    strategy.position_size != 0 ? round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
stoploss=input(title=" stop loss", defval=5, minval=0.01)
los = per(stoploss)
q1=input(title=" qty_percent1", defval=50, minval=1)
q2=input(title=" qty_percent2", defval=50, minval=1)

tp10=input(title=" Take profit1", defval=1, minval=0.01)
tp20=input(title=" Take profit2", defval=2, minval=0.01)

strategy.exit("x1", qty_percent = q1, profit = per(tp10), loss = los)
strategy.exit("x2", qty_percent = q2, profit = per(tp20), loss = los)


더 많은