트렌드 다음 이동 중지 손실 MA 전략

저자:차오장, 날짜: 2023-10-10 10:36:16
태그:

전반적인 설명

이 전략은 유동 평균과 상대 강도 지수의 조합을 사용하여 트렌드 방향을 결정하고 수익 목표를 달성하기 위해 후속 스톱 손실 메커니즘을 구현합니다. 트렌드가 형성된 후 빠른 시장 진출을 허용하고 스톱 손실과 수익을 통해 수익을 확보하는 고 변동성 시장에 적합합니다.

전략 논리

이 전략은 현재 시장 트렌드를 결정하기 위해 RSI 지표를 사용합니다. 30 이하의 RSI는 하향적이라고 간주되며, 70 이상은 상승적이라고 간주됩니다. RSI 크로스오버가 하향적 트렌드를 신호할 때 길게됩니다. RSI 크로스오버가 하향적 트렌드를 신호할 때 짧게됩니다.

포지션 개척 후, 전략은 가격 변화를 추적하고 이익을 잠금하기 위해 움직이는 스톱 로스 메커니즘을 사용합니다. 구체적으로, 각 포지션의 평균 입시 가격을 기록합니다. 가격이 입시 가격의 1%에 도달하면 이동 스톱 로스 메커니즘을 활성화하여 현재 가격과 가장 높은 가격의 차이에 따라 스톱 로스 라인을 이동합니다.

가격이 스톱 로스 수준에 도달하면 포지션을 종료합니다. 가격이 엔트리 가격의 3%에 도달하면 이윤을 취합니다. 스톱 로스 및 이윤을 취하는 두 가지 보호를 사용하여 이윤 목표를 달성합니다.

장점

  • 트렌드 방향을 결정하기 위해 RSI를 사용하면 시장 동력을 빠르게 판단 할 수 있습니다.
  • 이동 스톱 로스는 실시간 가격 변화에 따라 스톱 로스 수준을 유연하게 조정하여 조기 스톱 로스를 피할 수 있습니다.
  • 스톱 로스 및 취득으로부터의 이중 보호는 위험을 통제하면서 특정 수익을 보장합니다.

위험성

  • RSI는 단독으로 사용되면 잘못된 입력 신호가 될 수 있습니다.
  • 중지 손실 거리가 너무 작으면 쉽게 활성화 될 수 있지만 너무 느슨하면 손실을 멈추지 않을 수 있습니다.
  • 부적절한 취득 설정 또한 수익 목표에 실패 할 수 있습니다

추가 지표는 RSI 신호를 확인하고 잘못된 신호를 줄이기 위해 추가 될 수 있습니다. 백테스팅에 기반한 스톱 손실 및 수익 수준을 최적화하는 것도 최상의 매개 변수 조합을 찾는 데 도움이 될 수 있습니다.

최적화

  • 트렌드 신호를 확인하고 잘못된 항목을 피하기 위해 볼링거 밴드 또는 KD를 추가합니다.
  • 인디케이터 조합을 확장하기 위해 덧셈과 곱셈을 사용하는 연구
  • 단일 시간 프레임에 잘못된 신호를 피하기 위해 여러 시간 프레임 확인을 시도
  • 시장 변동성에 기초하여 정지 거리를 조정하기 위한 적응식 스톱 손실 메커니즘 연구

요약

전체적으로 이것은 매우 전문적이고 신뢰할 수있는 트렌드 다음 전략입니다. 그것은 빠르게 시장 방향을 결정하고 이동 스톱 손실과 이익을 통해 이익을 잠금 할 수 있습니다. 매개 변수를 더 이상 최적화하고 확인 지표를 추가하면 승률과 신뢰성을 향상시킬 수 있습니다. 명확한 논리와 유연한 매개 변수로 양 거래 전략을 배우는 데 매우 좋은 예입니다.


/*backtest
start: 2022-10-03 00:00:00
end: 2023-10-09 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=3
// Learn more about Autoview and how you can automate strategies like this one here: https://autoview.with.pink/
// strategy("Autoview Build-a-bot - 1m chart", "Strategy", overlay=true, pyramiding=2000, default_qty_value=10000)
// study("Autoview Build-a-bot", "Alerts")

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

//* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *//
//* https://www.tradingview.com/u/pbergden/ *//
//* Modifications made *//

testStartYear = input(1, "Backtest Start Year") 
testStartMonth = input(11, "Backtest Start Month")
testStartDay = input(10, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)

testStopYear = input(77777777, "Backtest Stop Year")
testStopMonth = input(11, "Backtest Stop Month")
testStopDay = input(15, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)

testPeriod() => true

/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
RSIlength = input(6,title="RSI Period Length") 
price = close
vrsi = (rsi(price, RSIlength))
src = close
len = input(2, minval=1, title="Length")

up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))

rsin = input(14)
sn = 100 - rsin
ln = 0 + rsin

// Put your long and short rules here
longLocic = crossunder(rsi, ln)
shortLogic = crossover(rsi, sn)

//////////////////////////
//* Strategy Component *//
//////////////////////////

isLong = input(true, "Longs Only")
isShort = input(false, "Shorts Only")
isFlip = input(false, "Flip the Opens")

long = longLocic
short = shortLogic

if isFlip
    long := shortLogic
    short := longLocic
else
    long := longLocic
    short := shortLogic

if isLong
    long := long
    short := na

if isShort
    long := na
    short := short
    
////////////////////////////////
//======[ Signal Count ]======//
////////////////////////////////

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

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

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

//////////////////////////////
//======[ Pyramiding ]======//
//////////////////////////////

pyrl = input(2, "Pyramiding less than") // If your count is less than this number
pyre = input(1, "Pyramiding equal to") // If your count is equal to this number
pyrg = input(1000000, "Pyramiding greater than") // If your count is greater than this number

longCondition = long and sectionLongs <= pyrl or long and sectionLongs >= pyrg or long and sectionLongs == pyre ? 1 : 0 and vrsi < 20
shortCondition = short and sectionShorts <= pyrl or short and sectionShorts >= pyrg or short and sectionShorts == pyre ? 1 : 0

////////////////////////////////
//======[ Entry Prices ]======//
////////////////////////////////

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

////////////////////////////////////
//======[ Open Order Count ]======//
////////////////////////////////////

sectionLongConditions = 0
sectionLongConditions := nz(sectionLongConditions[1])
sectionShortConditions = 0
sectionShortConditions := nz(sectionShortConditions[1])

if longCondition
    sectionLongConditions := sectionLongConditions + 1
    sectionShortConditions := 0

if shortCondition
    sectionLongConditions := 0
    sectionShortConditions := sectionShortConditions + 1
    
///////////////////////////////////////////////
//======[ Position Check (long/short) ]======//
///////////////////////////////////////////////

last_longCondition = na
last_shortCondition = 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

/////////////////////////////////////
//======[ Position Averages ]======//
/////////////////////////////////////

totalLongs = 0.0
totalLongs := nz(totalLongs[1])
totalShorts = 0.0
totalShorts := nz(totalShorts[1])
averageLongs = 0.0
averageLongs := nz(averageLongs[1])
averageShorts = 0.0
averageShorts := nz(averageShorts[1]) 

if longCondition
    totalLongs := totalLongs + last_open_longCondition
    totalShorts := 0.0

if shortCondition
    totalLongs := 0.0
    totalShorts := totalShorts + last_open_shortCondition

averageLongs := totalLongs / sectionLongConditions
averageShorts := totalShorts / sectionShortConditions

/////////////////////////////////
//======[ Trailing Stop ]======//
/////////////////////////////////

isTS = input(false, "Trailing Stop")
tsi = input(100, "Activate Trailing Stop Price (%). Divided by 100 (1 = 0.01%)") / 100 
ts = input(100, "Trailing Stop (%). Divided by 100 (1 = 0.01%)") / 100

last_high = na
last_low = na
last_high_short = na
last_low_short = na
last_high := not in_longCondition ? na : in_longCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : nz(last_high[1])
last_high_short := not in_shortCondition ? na : in_shortCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : nz(last_high[1])
last_low := not in_shortCondition ? na : in_shortCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : nz(last_low[1])
last_low_short := not in_longCondition ? na : in_longCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : nz(last_low[1])

long_ts = isTS and not na(last_high) and low <= last_high - last_high / 100 * ts and longCondition == 0 and last_high >= averageLongs + averageLongs / 100 * tsi
short_ts = isTS and not na(last_low) and high >= last_low + last_low / 100 * ts and shortCondition == 0 and last_low <= averageShorts - averageShorts/ 100 * tsi

///////////////////////////////
//======[ Take Profit ]======//
///////////////////////////////

isTP = input(true, "Take Profit")
tp = input(33, "Take Profit (%). Divided by 100 (1 = 0.01%)") / 100
long_tp = isTP and close > averageLongs + averageLongs / 100 * tp and not longCondition
short_tp = isTP and close < averageShorts - averageShorts / 100 * tp and not shortCondition

/////////////////////////////
//======[ Stop Loss ]======//
/////////////////////////////

isSL = input(true, "Stop Loss")
sl = input(55, "Stop Loss (%). Divided by 100 (1 = 0.01%)") / 100
long_sl = isSL and close < averageLongs - averageLongs / 100 * sl and longCondition == 0
short_sl = isSL and close > averageShorts + averageShorts / 100 * sl and shortCondition == 0

/////////////////////////////////
//======[ Close Signals ]======//
/////////////////////////////////

longClose = long_tp or long_sl or long_ts ? 1 : 0
shortClose = short_tp or short_sl or short_ts ? 1: 0

///////////////////////////////
//======[ Plot Colors ]======//
///////////////////////////////

longCloseCol = na
shortCloseCol = na
longCloseCol := long_tp ? purple : long_sl ? maroon : long_ts ? blue : longCloseCol[1]
shortCloseCol := short_tp ? purple : short_sl ? maroon : short_ts ? blue : shortCloseCol[1]
tpColor = isTP and in_longCondition ? purple : isTP and in_shortCondition ? purple : white
slColor = isSL and in_longCondition ? red : isSL and in_shortCondition ? red : white

//////////////////////////////////
//======[ Strategy Plots ]======//
//////////////////////////////////

plot(isTS and in_longCondition ? averageLongs + averageLongs / 100 * tsi : na, "Long Trailing Activate", blue, style=3, linewidth=2)
plot(isTS and in_longCondition and last_high >= averageLongs +  averageLongs / 100 * tsi ? last_high - last_high / 100 * ts : na, "Long Trailing", fuchsia, style=2, linewidth=3)
plot(isTS and in_shortCondition ? averageShorts - averageShorts/ 100 * tsi : na, "Short Trailing Activate", blue, style=3, linewidth=2)
plot(isTS and in_shortCondition and last_low <= averageShorts - averageShorts/ 100 * tsi ? last_low + last_low / 100 * ts : na, "Short Trailing", fuchsia, style=2, linewidth=3)
plot(isTP and in_longCondition and last_high < averageLongs + averageLongs / 100 * tp ? averageLongs + averageLongs / 100 * tp : na, "Long TP", tpColor, style=3, linewidth=2)
plot(isTP and in_shortCondition and last_low > averageShorts - averageShorts / 100 * tp ? averageShorts - averageShorts / 100 * tp : na, "Short TP", tpColor, style=3, linewidth=2)
plot(isSL and in_longCondition and last_low_short > averageLongs - averageLongs / 100 * sl ? averageLongs - averageLongs / 100 * sl : na, "Long SL", slColor, style=3, linewidth=2)
plot(isSL and in_shortCondition and last_high_short < averageShorts + averageShorts / 100 * sl ? averageShorts + averageShorts / 100 * sl : na, "Short SL", slColor, style=3, linewidth=2)

///////////////////////////////
//======[ Alert Plots ]======//
///////////////////////////////

// plot(longCondition, "Long", green)
// plot(shortCondition, "Short", red)
// plot(longClose, "Long Close", longCloseCol)
// plot(shortClose, "Short Close", shortCloseCol)

///////////////////////////////////
//======[ Reset Variables ]======//
///////////////////////////////////

if longClose or not in_longCondition
    averageLongs := 0
    totalLongs := 0.0
    sectionLongs := 0
    sectionLongConditions := 0

if shortClose or not in_shortCondition
    averageShorts := 0
    totalShorts := 0.0
    sectionShorts := 0
    sectionShortConditions := 0

////////////////////////////////////////////
//======[ Strategy Entry and Exits ]======//
////////////////////////////////////////////

if testPeriod()
    strategy.entry("Long", 1, when=longCondition)
    strategy.entry("Short", 0,  when=shortCondition)
    strategy.close("Long", when=longClose)
    strategy.close("Short", when=shortClose)
    


더 많은