Xu hướng RSI theo chiến lược

Tác giả:ChaoZhang, Ngày: 2023-11-16 15:33:40
Tags:

Tổng quan

Chiến lược này kết hợp chỉ số RSI và trung bình di chuyển cân đối cho xu hướng sau khi giao dịch. Nó đi dài khi RSI trên 60 và đi ngắn khi RSI dưới 40, với trung bình di chuyển xác minh điều kiện xu hướng. RSI 40 giai đoạn hoạt động như một chỉ số theo xu hướng.

Chiến lược logic

Chiến lược đầu tiên tính toán chỉ số RSI và đường trung bình động cân nhắc. Độ dài RSI là 20 giai đoạn và chiều dài MA cân nhắc là 20 với trọng lượng cao hơn làm giảm tác động của biến động ngắn hạn. Nó đi dài khi RSI trên 60 và tỷ lệ thay đổi MA cân nhắc dưới -1%. Nó đi ngắn khi RSI dưới 40 và tỷ lệ thay đổi MA cân nhắc trên 1%.

Sau khi mở dài hoặc ngắn, lệnh dừng lỗ và lệnh lấy lợi nhuận theo sau được đặt đồng thời. Lệnh dừng lỗ được đặt ở mức 3 ATR từ giá hiện tại. Việc kích hoạt lợi nhuận bắt đầu là 4 ATR, và theo sau tăng 3%. Khi giá đạt hoặc dừng lỗ hoặc kích hoạt lợi nhuận theo sau, vị trí sẽ được đóng.

Chiến lược cũng kết hợp các quy tắc quản lý tiền dựa trên phương pháp định hình kích thước vị trí phân số cố định.

Phân tích lợi thế

  • Chỉ số RSI có thể theo dõi các xu hướng hiệu quả
  • MA được cân nhắc làm giảm tác động của biến động ngắn hạn, tránh các biến động
  • Theo dõi lợi nhuận cho phép lợi nhuận được tối đa hóa
  • Kiểm soát kích thước vị trí phân số cố định rủi ro hiệu quả

Ưu điểm tổng thể là khả năng theo dõi xu hướng, trong khi thực hiện các biện pháp dừng lỗ và lợi nhuận để kiểm soát rủi ro, do đó thu được lợi nhuận đáng kể trong các xu hướng mạnh.

Phân tích rủi ro

  • Các tín hiệu sai từ RSI có thể gây ra các giao dịch không cần thiết
  • Bị buộc phải dừng lại khi vi phạm giá dừng lại hoặc giảm mức lợi nhuận, không thể theo dõi xu hướng
  • Các quy tắc quản lý tiền bạc có thể dẫn đến tổn thất lớn

Các rủi ro chính đến từ độ tin cậy của tín hiệu RSI và cài đặt stop loss / trailing take profit. Các thông số không chính xác có thể dẫn đến việc đóng giao dịch không cần thiết hoặc thua lỗ vượt quá sự thèm mạo hiểm. Bỏ stop loss / take profit cũng có thể buộc phải dừng lại không hợp lý, mất cơ hội tiếp tục giao dịch xu hướng.

Các giải pháp bao gồm tối ưu hóa các thông số RSI hoặc thêm các chỉ số khác để xác nhận tín hiệu. Điều chỉnh mức dừng / theo dõi lấy lợi nhuận dựa trên các sản phẩm khác nhau và điều kiện biến động.

Hướng dẫn tối ưu hóa

  • Kiểm tra các chỉ số khác cùng với RSI để xác nhận tín hiệu, ví dụ: KD, MACD vv
  • Tối ưu hóa các thông số dừng lỗ và kéo dài lợi nhuận dựa trên đặc điểm sản phẩm và phạm vi biến động
  • Hãy thử các kỹ thuật quản lý tiền khác như giao dịch kích thước cố định, công thức Kelly vv
  • Thêm các điều kiện đầu vào như Bollinger breakout, RSI phân kỳ vv
  • Xem xét thêm các vị trí về xu hướng mạnh

Có nhiều khía cạnh để tối ưu hóa. Đầu tiên là xác định các chỉ số khác để bổ sung cho các tín hiệu RSI. Bước quan trọng tiếp theo là tối ưu hóa các thông số dừng lỗ / theo dõi lợi nhuận dựa trên hiệu suất lịch sử. Quản lý tiền cũng có thể chuyển sang các loại khác. Cuối cùng, các điều kiện nhập cảnh, bổ sung có thể được tăng cường cho các vị trí kim tự tháp trong xu hướng mạnh.

Tóm lại

Chiến lược theo xu hướng RSI có logic rõ ràng, sử dụng RSI cho hướng xu hướng và MA cân nhắc để xác nhận. Sức mạnh của nó nằm trong giao dịch xu hướng, tối đa hóa lợi nhuận với dừng / quản lý tiền kiểm soát rủi ro. Nhưng độ tin cậy và tối ưu hóa tham số RSI cần cải thiện. Chúng ta có thể xem xét nâng cao các chỉ số tín hiệu, tham số dừng / theo dõi, phương pháp quản lý tiền vv để làm cho chiến lược mạnh mẽ hơn trên các sản phẩm khác nhau.

[/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)


Thêm nữa