전략에 따른 RSI 트렌드

저자:차오장, 날짜: 2023-11-16 15:33:40
태그:

전반적인 설명

이 전략은 트렌드를 따르는 트렌드를 위해 RSI 지표와 가중화 이동 평균을 결합합니다. RSI가 60보다 높을 때 길고 RSI가 40보다 낮을 때 짧습니다. 이동 평균은 트렌드 상태를 검증합니다. 40 기간 RSI는 트렌드를 따르는 지표로 작용합니다. 가중화 이동 평균은 단기 변동의 영향을 줄이기 위해 다른 무게를 사용합니다. 전략은 또한 위험을 제어하기 위해 스톱 로스와 트레일 리프트를 사용합니다.

전략 논리

이 전략은 우선 RSI와 가중화 이동 평균을 계산합니다. RSI 길이는 20 기간이고 가중된 MA 길이는 20이며, 단기 변동성의 영향을 줄이는 더 높은 무게가 있습니다. RSI가 60보다 높고 가중된 MA 변화율이 -1% 미만일 때 길게됩니다. RSI가 40보다 낮고 가중된 MA 변화율이 1% 이상일 때 짧게됩니다.

긴 또는 짧은 열기 후, 스톱 로스와 트레일링 테이프 오더는 동시에 배치됩니다. 스톱 로스는 현재 가격에서 3 ATR로 설정됩니다. 초기 트레일링 테이프 오더 활성화는 4 ATR 떨어져 있으며 3% 인크림으로 트레일됩니다. 가격이 스톱 로스 또는 트레일링 테이프 오더 활성화를 달성하면 포지션이 종료됩니다.

이 전략은 또한 고정 분수 포지션 사이즈 접근법에 기반한 돈 관리 규칙을 포함합니다. PNL가 고정 금액을 달성 할 때마다 주문 크기는 고정 금액으로 증가하거나 감소합니다.

이점 분석

  • RSI 인디케이터는 트렌드를 효과적으로 추적할 수 있습니다.
  • 가중된 MA는 단기 변동의 영향을 줄이고, 윙사 (whipsaws) 를 피합니다.
  • 이윤을 추월하면 이윤을 극대화 할 수 있습니다.
  • 고정 분자 위치 크기 제어 위험 효과적으로

전체적인 장점은 트렌드를 따라가면서 위험 통제를 위해 스톱 로스 및 트래일 어프프리 조치를 취하여 강력한 트렌드에서 상당한 이득을 얻을 수 있다는 것입니다.

위험 분석

  • RSI의 잘못된 신호는 불필요한 거래를 유발할 수 있습니다.
  • 가격 침해가 중단되거나 수익 수준이 떨어지면 중단해야 합니다. 추세를 따라가지 못하죠.
  • 공격적인 돈 관리 규칙은 큰 손실로 이어질 수 있습니다.

주요 위험은 RSI 신호의 신뢰성 및 스톱 로스 / 트레일링 트레이프 설정에서 비롯됩니다. 잘못된 매개 변수는 불필요한 거래 종료 또는 위험 욕구를 초과하는 손실로 이어질 수 있습니다. 스톱 로스 / 트레이프 수익을 깨는 것은 또한 타당하지 않은 스톱 아웃을 강요하여 트렌드 거래를 계속할 기회를 잃을 수 있습니다.

솔루션으로는 RSI 매개 변수를 최적화하거나 신호 확인을 위해 다른 지표를 추가하는 것이 포함됩니다. 다른 제품과 변동성 조건에 따라 스톱 / 트레일 인프트 수준을 조정하십시오. 또한 과도한 위험을 피하기 위해 돈 관리 규칙에 신중하십시오.

최적화 방향

  • 신호 확인을 위해 RSI와 함께 다른 지표를 테스트하십시오. 예를 들어 KD, MACD 등
  • 제품 특성 및 변동 범위에 기초한 스톱 로스 및 후속 수익 매개 변수를 최적화합니다.
  • 고정 크기의 거래, 켈리 공식 등과 같은 다른 돈 관리 기술을 시도하십시오
  • 볼린거 브레이크오웃, RSI 오차 등과 같은 입시 조건을 추가합니다.
  • 강한 트렌드에 대한 포지션을 추가하는 것을 고려하십시오.

최적화 할 수있는 많은 측면이 있습니다. 첫째는 RSI 신호를 보완하기 위해 다른 지표를 식별하는 것입니다. 다음 중요한 단계는 역사적 성과에 기반한 스톱 로스 / 트레일링 취득 매개 변수를 최적화하는 것입니다. 돈 관리 또한 다른 유형으로 전환 할 수 있습니다. 마지막으로, 엔트리, 부가 조건은 강력한 트렌드에 피라미드 포지션으로 향상 될 수 있습니다.

요약

트렌드를 따르는 RSI 전략은 트렌드 방향을 나타내는 RSI와 확인을 위한 가중된 MA를 사용하여 명확한 논리를 가지고 있다. 그것의 강점은 트렌드 트레이딩에 있으며, 위험을 제어하는 스톱/돈 관리로 수익을 극대화하는 것이다. 그러나 RSI 신뢰성과 매개 변수 최적화는 개선이 필요하다. 우리는 다른 제품에 걸쳐 전략을 더 견고하게 만들기 위해 신호 지표, 스톱/트레일 매개 변수, 돈 관리 방법 등을 향상시킬 수 있다.

[/trans]


/*backtest
start: 2023-01-01 00:00:00
end: 2023-06-24 00:00:00
period: 1d
basePeriod: 1h
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/
// © gsanson66


//This code is based on RSI and a backed weighted MA
//@version=5
strategy("RSI + MA BACKTESTING", overlay=true, initial_capital=1000, default_qty_type=strategy.fixed, commission_type=strategy.commission.percent, commission_value=0.18)


//------------------------FUNCTIONS---------------------------//

//@function which calculate a retro weighted moving average to minimize the impact of short term reversal
rwma(source, length) =>
    sum = 0.0
    denominator = 0.0
    weight = 0.0
    weight_x = 100/(4+(length-4)*1.30)
    weight_y = 1.30*weight_x
    for i=0 to length - 1
        if i <= 3
            weight := weight_x
        else
            weight := weight_y
        sum := sum + source[i] * weight
        denominator := denominator + weight
    rwma = sum/denominator

//@function which permits the user to choose a moving average type
ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "RWMA" => rwma(source, length)

//@function Displays text passed to `txt` when called.
debugLabel(txt, color) =>
    label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)

//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)


//--------------------------------USER INPUTS-------------------------------//

//Technical parameters
rsiLengthInput = input.int(20, minval=1, title="RSI Length", group="RSI Settings")
maTypeInput = input.string("RWMA", title="MA Type", options=["SMA", "RWMA"], group="MA Settings", inline="1")
maLenghtInput = input.int(20, minval=1, title="MA Length", group="MA Settings", inline="1")
rsiLongSignalValue = input.int(60, minval=1, maxval=99, title="RSI Long Signal", group="Strategy parameters", inline="3")
rsiShortSignalValue = input.int(40, minval=1, maxval=99, title="RSI Short Signal", group="Strategy parameters", inline="3")
rocMovAverLongSignalValue = input.float(-1, maxval=0, title="ROC MA Long Signal", group="Strategy parameters", inline="4")
rocMovAverShortSignalValue = input.float(1, minval=0, title="ROC MA Short Signal", group="Strategy parameters", inline="4")
//TP Activation and Trailing TP
takeProfitActivationInput = input.float(4, minval=1.0, title="TP activation in multiple of ATR", group="Strategy parameters")
trailingStopInput = input.float(3, minval=0, title="Trailing TP in percentage", group="Strategy parameters")
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management")
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management")
//Backtesting period
startDate = input(title="Start Date", defval=timestamp("1 Jan 2018 00:00:00"), group="Backtesting Period")
endDate = input(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")

strategy.initial_capital = 50000

//------------------------------VARIABLES INITIALISATION-----------------------------//

float rsi = ta.rsi(close, rsiLengthInput)
float ma = ma(close, maLenghtInput, maTypeInput)
float roc_ma = ((ma/ma[maLenghtInput]) - 1)*100
float atr = ta.atr(20)
var float trailingStopOffset = na
var float trailingStopActivation = na
var float trailingStop = na
var float stopLoss = na
var bool long = na
var bool short = na
var bool bufferTrailingStopDrawing = na
float theoreticalStopPrice = na
bool inRange = na
equity = strategy.equity - strategy.openprofit
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95


//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//

//Checking if the date belong to the range
inRange := true

//Checking performances of the strategy
if equity > capital_ref + fixedRatio
    spread = (equity - capital_ref)/fixedRatio
    nb_level = int(spread)
    increasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder + increasingOrder
    capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
    spread = (capital_ref - equity)/fixedRatio
    nb_level = int(spread)
    decreasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder - decreasingOrder
    capital_ref := capital_ref - nb_level*fixedRatio

//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
    debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))
    strategy.close_all()
    bufferTrailingStopDrawing := false
    stopLoss := na
    trailingStopActivation := na
    trailingStop := na
    short := false
    long := false


//------------------------------STOP LOSS AND TRAILING STOP ACTIVATION----------------------------//

// We handle the stop loss and trailing stop activation 
if (low <= stopLoss or high >= trailingStopActivation) and long
    if high >= trailingStopActivation
        bufferTrailingStopDrawing := true
    else if low <= stopLoss
        long := false
    stopLoss := na
    trailingStopActivation := na
if (low <= trailingStopActivation or high >= stopLoss) and short
    if low <= trailingStopActivation
        bufferTrailingStopDrawing := true
    else if high >= stopLoss
        short := false
    stopLoss := na
    trailingStopActivation := na


//-------------------------------------TRAILING STOP--------------------------------------//

// If the traling stop is activated, we manage its plotting with the bufferTrailingStopDrawing
if bufferTrailingStopDrawing and long
    theoreticalStopPrice := high - trailingStopOffset * syminfo.mintick
    if na(trailingStop)
        trailingStop := theoreticalStopPrice
    else if theoreticalStopPrice > trailingStop
        trailingStop := theoreticalStopPrice
    else if low <= trailingStop
        trailingStop := na
        bufferTrailingStopDrawing := false
        long := false
if bufferTrailingStopDrawing and short
    theoreticalStopPrice := low + trailingStopOffset * syminfo.mintick
    if na(trailingStop)
        trailingStop := theoreticalStopPrice
    else if theoreticalStopPrice < trailingStop
        trailingStop := theoreticalStopPrice
    else if high >= trailingStop
        trailingStop := na
        bufferTrailingStopDrawing := false
        short := false


//---------------------------------LONG CONDITION--------------------------//

if rsi >= 60 and roc_ma <= rocMovAverLongSignalValue and inRange and not long
    if short
        bufferTrailingStopDrawing := false
        stopLoss := na
        trailingStopActivation := na
        trailingStop := na
        short := false
    trailingStopActivation := close + takeProfitActivationInput*atr
    trailingStopOffset := (trailingStopActivation * trailingStopInput/100) / syminfo.mintick
    stopLoss := close - 3*atr
    long := true
    qty = cashOrder/close
    strategy.entry("Long", strategy.long, qty)
    strategy.exit("Exit Long", "Long", stop = stopLoss, trail_price = trailingStopActivation,
                 trail_offset = trailingStopOffset)


//--------------------------------SHORT CONDITION-------------------------------//

if rsi <= 40 and roc_ma >= rocMovAverShortSignalValue and inRange and not short
    if long
        bufferTrailingStopDrawing := false
        stopLoss := na
        trailingStopActivation := na
        trailingStop := na
        long := false
    trailingStopActivation := close - takeProfitActivationInput*atr
    trailingStopOffset := (trailingStopActivation * trailingStopInput/100) / syminfo.mintick
    stopLoss := close + 3*atr
    short := true
    qty = cashOrder/close
    strategy.entry("Short", strategy.short, qty)
    strategy.exit("Exit Short", "Short", stop = stopLoss, trail_price = trailingStopActivation,
                 trail_offset = trailingStopOffset)


//--------------------------------PLOTTING ELEMENT---------------------------------//

// Plotting of element in the graph
plotchar(rsi, "RSI", "", location.top, color.rgb(0, 214, 243))
plot(ma, "MA", color.rgb(219, 219, 18))
plotchar(roc_ma, "ROC MA", "", location.top, color=color.orange)
// Visualizer trailing stop and stop loss movement
plot(stopLoss, "SL", color.red, 3, plot.style_linebr)
plot(trailingStopActivation, "Trigger Trail", color.green, 3, plot.style_linebr)
plot(trailingStop, "Trailing Stop",  color.blue, 3, plot.style_linebr)


더 많은