Chiến lược chốt lời theo xu hướng và dừng lỗ theo xu hướng


Ngày tạo: 2023-12-11 09:58:35 sửa đổi lần cuối: 2023-12-11 09:58:35
sao chép: 0 Số nhấp chuột: 849
1
tập trung vào
1621
Người theo dõi

Chiến lược chốt lời theo xu hướng và dừng lỗ theo xu hướng

Tổng quan

Chiến lược dừng theo dõi theo dõi theo dõi là một chiến lược giao dịch định lượng kết hợp các chức năng như theo dõi xu hướng, dừng một phần và dừng theo dõi toàn bộ, nhằm mục đích nắm bắt xu hướng tăng giá trong thị trường bò và kiếm lợi nhuận bằng cách dừng thông minh, đồng thời sử dụng dừng theo dõi để kiểm soát rủi ro đi xuống.

Nguyên tắc chiến lược

Chiến lược này sử dụng đường trung bình di chuyển nhanh và đường trung bình di chuyển chậm như một tín hiệu mua. Khi đường trung bình di chuyển nhanh vượt qua đường trung bình di chuyển chậm, cho thấy xu hướng tăng giá được hình thành, chiến lược sẽ mở nhiều vị trí.

Sau đó, chiến lược sẽ đặt một giá dừng, tương đương với giá mở vị trí nhân tỷ lệ dừng được đặt. Khi giá đạt đến giá dừng, chiến lược sẽ bán một phần và bán 50% vị trí theo mặc định. Điều này thực hiện một phần dừng và khóa một phần lợi nhuận.

Tiếp theo, chiến lược cũng sẽ khởi động các cơ chế theo dõi xu hướng dừng. Khi giá tiếp tục tăng, giá dừng sẽ theo dõi giá theo tỷ lệ bước được thiết lập trailingTakeProfitDeviationPerc. Điều này cho phép giá dừng theo sát xu hướng tăng giá, thực hiện xu hướng theo dõi dừng.

Đồng thời, chiến lược cũng sẽ khởi động theo dõi dừng lỗ. Khi giá đạt đến giá dừng, giá dừng sẽ bắt đầu di chuyển theo dõi lên, nó luôn luôn duy trì ở mức cao nhân với tỷ lệ giảm dừng. Điều này cho phép giá dừng để di chuyển theo dõi lên, do đó khóa nhiều lợi nhuận hơn, đồng thời cũng kiểm soát rủi ro đi xuống.

Khi giá bị điều chỉnh lại, chiến lược sẽ ngừng theo dõi nếu phá vỡ giá dừng lỗ, và trực tiếp giữ tất cả các vị trí còn lại tại mức giá thị trường. Từ đó, toàn bộ chu kỳ giao dịch được hoàn thành.

Phân tích lợi thế

Chiến lược này tích hợp nhiều tính năng như theo dõi xu hướng, dừng một phần và dừng toàn bộ, với các ưu điểm sau:

  1. Các nhà đầu tư cũng có thể sử dụng các công cụ này để thu thập các tín hiệu mua và mua chính xác.
  2. Các cơ chế ngăn chặn một phần cho phép khóa một phần lợi nhuận và tránh thu hồi toàn bộ lợi nhuận;
  3. Các cơ chế theo dõi xu hướng cho phép giá dừng lại để giữ giá tăng;
  4. Sau khi mở Tracking Stop, bạn có thể khóa nhiều lợi nhuận hơn, đồng thời kiểm soát rủi ro đi xuống.
  5. Các tham số chiến lược có thể được cấu hình và điều chỉnh theo mức độ rủi ro mà bạn có thể chịu được.

Phân tích rủi ro

Chiến lược này cũng có một số rủi ro, đặc biệt là ở những khía cạnh sau:

  1. Sau khi mua, giá có thể giảm mạnh, không thể dừng hoặc dừng lỗ, dẫn đến tổn thất mở rộng;
  2. Khi giá dừng ở cuối xu hướng, giá dừng sẽ không theo kịp và có thể bỏ lỡ điểm dừng tốt nhất.
  3. Giá dừng lỗ được thiết lập quá rộng, giá giảm mạnh dẫn đến tổn thất quá lớn;
  4. Tỷ lệ giao dịch có thể quá cao, chi phí giao dịch và mất điểm trượt cao.

Theo đó, có thể tối ưu hóa và cải thiện các khía cạnh sau:

  1. Cài đặt các tham số trung bình di chuyển hợp lý để tránh các tín hiệu sai;
  2. Giảm tỷ lệ ngưng tụ một phần một cách thích hợp để giảm nguy cơ;
  3. Cắt chặt mức dừng lỗ thích hợp, kiểm soát tổn thất đơn lẻ;
  4. Điều chỉnh tham số tỷ lệ bước để tối ưu hóa hiệu quả của việc theo dõi dừng.

Hướng tối ưu hóa

Chiến lược này có thể được tối ưu hóa hơn nữa:

  1. Có thể đưa ra nhiều chỉ số hơn để đánh giá xu hướng và tránh các đột phá giả mạo.
  2. Thêm mô-đun quản lý vị thế để kích thước vị thế hợp lý hơn;
  3. Tăng cơ chế điều chỉnh động của Stop Loss để các tham số được tự động hơn;
  4. Thêm cơ chế lọc để tránh giao dịch sai lầm với các giống năng lượng cao.

Những tối ưu hóa này có thể làm cho chiến lược ổn định hơn, hiệu quả hơn và hiệu suất được nâng cao.

Tóm tắt

Chiến lược dừng lỗ theo dõi theo dõi xu hướng sử dụng các phương tiện kỹ thuật như theo dõi xu hướng, dừng lỗ thông minh, theo dõi toàn bộ, dựa trên xu hướng tăng giá, cũng thực hiện theo dõi xu hướng của giá dừng và theo dõi mức độ dừng lỗ. Điều này cho phép chiến lược hoạt động theo xu hướng, thu được nhiều lợi nhuận hơn trong thị trường bò. Đồng thời, chiến lược cũng xem xét kiểm soát rủi ro, sử dụng một phần dừng và dừng lỗ để bảo vệ tài chính.

Mã nguồn chiến lược
/*backtest
start: 2023-11-10 00:00:00
end: 2023-11-18 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 
//  -----------------------------------------------------------------------------
//  Copyright 2021 Iason Nikolas | jason5480
//  Trainiling Take Profit Trailing Stop Loss script may be freely distributed under the MIT license.
//
//  Permission is hereby granted, free of charge, 
//  to any person obtaining a copy of this software and associated documentation files (the "Software"), 
//  to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, 
//  publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
//  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//  -----------------------------------------------------------------------------
//
//  Authors:  @jason5480
//  Revision: v1.0.1
//  Date:     18-Apr-2021
//
//  Description
//  =============================================================================
//  This strategy will go long if fast MA crosses over slow MA.
//  The strategy will exit from long position when the price increases by a fixed percentage.
//  If the trailing take profit is checked then the strategy instead of setting a limit order in a predefined price (based on the percentage)
//  it will follow the price with small steps (percentagewise)
//  If the price drops by this percentage then the exit order will be executed
//
//  The strategy has the following parameters:
//
//  Fast SMA Length - How many candles back to calculte the fast SMA.
//  Slow SMA Length - How many candles back to calculte the slow SMA.
//  Take Profit % - The percentage of the price increase to set the take profit price target.
//  Enable Trailing - Enable or disable the trailing for take profit.
//  Training Take Profit Deviation % - The step to follow the price when the take profit limit is reached.
//  Trailing Stop Loss % - The stop loss percentage drop that will close your position. After the take profit price is reached the trailing stop loss price target will follow the price upwards (for long positions).
//  
//  -----------------------------------------------------------------------------
//  Disclaimer:
//    1. I am not licensed financial advisors or broker dealer. I do not tell you 
//       when or what to buy or sell. I developed this software which enables you 
//       execute manual or automated trades using TradingView. The 
//       software allows you to set the criteria you want for entering and exiting 
//       trades.
//    2. Do not trade with money you cannot afford to lose.
//    3. I do not guarantee consistent profits or that anyone can make money with no 
//       effort. And I am not selling the holy grail.
//    4. Every system can have winning and losing streaks.
//    5. Money management plays a large role in the results of your trading. For 
//       example: lot size, account size, broker leverage, and broker margin call 
//       rules all have an effect on results. Also, your Take Profit and Stop Loss 
//       settings for individual pair trades and for overall account equity have a 
//       major impact on results. If you are new to trading and do not understand 
//       these items, then I recommend you seek education materials to further your
//       knowledge.
//
//    YOU NEED TO FIND AND USE THE TRADING SYSTEM THAT WORKS BEST FOR YOU AND YOUR 
//    TRADING TOLERANCE.
//
//    I HAVE PROVIDED NOTHING MORE THAN A TOOL WITH OPTIONS FOR YOU TO TRADE WITH THIS PROGRAM ON TRADINGVIEW.
//    
//    I accept suggestions to improve the script.
//    If you encounter any problems I will be happy to share with me.
//  -----------------------------------------------------------------------------
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// SETUP ============================================================================================================
strategy(title = "Trailing Take Profit Trailing Stop Loss",
         shorttitle = "TTPTSL",
         overlay = true,
         pyramiding = 0,
         default_qty_type = strategy.cash,
         default_qty_value = 100000,
         initial_capital = 100000)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// INPUTS ===========================================================================================================

// STRATEGY INPUT ===================================================================================================
fastMALen = input(defval = 21, title = "Fast SMA Length", type = input.integer, group = "Strategy", tooltip = "How many candles back to calculte the fast SMA.")
slowMALen = input(defval = 49, title = "Slow SMA Length", type = input.integer, group = "Strategy", tooltip = "How many candles back to calculte the slow SMA.")

longTakeProfitPerc = input(defval = 12.0, title = 'Take Profit %', type = input.float, step = 0.1, group = "Strategy", tooltip = "The percentage of the price increase to set the take profit price target.") / 100
profitQuantityPerc = input(defval = 50, title = 'Take Profit Quantity %', type = input.float, step = 1.0, group = "Strategy", tooltip = "The percentage of the position that will be withdrawn when the take profit price target is hit.") / 100

enableTrailing = input(defval = true, title = "Enable Trailing", type = input.bool, group = "Strategy", tooltip = "Enable or disable the trailing for take profit.")
trailingTakeProfitDeviationPerc = input(defval = 1.0, title = 'Trailing Take Profit Deviation %', type = input.float, step = 0.05, group = "Strategy", tooltip = "The step to follow the price when the take profit limit is reached.") / 100

longTrailingStopLossPerc  = input(defval = 7.5, title = 'Trailing Stop Loss %',  type = input.float, step = 0.1, group = "Strategy", tooltip = "The stop loss percentage drop that will close your position. After the take profit price is reached the trailing stop loss price target will follow the price upwards (for long positions).") / 100

// BACKTEST PERIOD INPUT ============================================================================================
fromDate = input(defval = timestamp("01 Jan 2021 00:00 UTC"), title = "From Date", type = input.time, minval = timestamp("01 Jan 1970 00:00 UTC"), group = "Backtest Period") // backtest start date
toDate   = input(defval = timestamp("31 Dec 2121 23:59 UTC"), title = "To Date",   type = input.time, minval = timestamp("01 Jan 1970 00:00 UTC"), group = "Backtest Period") // backtest finish date

isWithinBacktestPeriod() => true // create function "within window of time"

// SHOW PLOT INPUT ==================================================================================================
showDate = input(defval = true, title = "Show Backtest Range", type = input.bool, group = "Plot", tooltip = "Gray out the backround of the backtest period.")

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// STRATEGY =========================================================================================================

fastMA = sma(close, fastMALen)
slowMA = sma(close, slowMALen)

startLongDeal = crossover(fastMA, slowMA)

longTakeProfitPrice = strategy.position_avg_price * (1 + longTakeProfitPerc)

longTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfitDeviationPerc / syminfo.mintick

// determine trailing stop loss price. Trailing starts when the take profit price is reached
longTrailingStarted = false
longTrailingStarted := if (strategy.position_size > 0)
    crossover(high, longTakeProfitPrice) or (high[1] >= longTakeProfitPrice) or longTrailingStarted[1]
else
    false

float longTrailingStopLossPrice = na
longTrailingStopLossPrice := if (strategy.position_size > 0)
    stopValue = longTrailingStarted == true ? high * (1 - longTrailingStopLossPerc) : strategy.position_avg_price * (1 - longTrailingStopLossPerc)
    max(stopValue, nz(longTrailingStopLossPrice[1]))
else
    na

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// STRATEGY EXECUTION ===============================================================================================

if (isWithinBacktestPeriod())
    // getting into LONG position
    strategy.entry(id = "Long", long = strategy.long, when = startLongDeal, comment = "Long", alert_message = "Long("  + syminfo.ticker + "): Started")
    if (strategy.position_size > 0)
        strategy.exit(id = "TTP", from_entry = "Long", qty = profitQuantityPerc * strategy.position_size, limit = enableTrailing ? na : longTakeProfitPrice, trail_price = enableTrailing ? longTakeProfitPrice : na, trail_offset = enableTrailing ? longTrailingTakeProfitStepTicks : na, oca_name = 'Exit Long', comment = "Long Take Profit", alert_message = "Long(" + syminfo.ticker + "): Trailing Take Profit activated")
        strategy.order(id = "TSL", long = strategy.short, qty = strategy.position_size, stop = longTrailingStopLossPrice, oca_name = 'Exit Long', oca_type = strategy.oca.cancel, comment = "Stop/Trail", when = true, alert_message = "Long("  + syminfo.ticker + "): Trailing Stop Loss activated")
    else
        strategy.cancel(id = "TTP", when = true)
        strategy.cancel(id = "TSL", when = true)
        
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// PLOT DATE POSITION MA AND TRAILING TAKE PROFIT STOP LOSS =========================================================

bgcolor(color = showDate and isWithinBacktestPeriod() ? color.gray : na, transp = 90)

plot(series = fastMA, color = #0056BD, style = plot.style_line, linewidth = 2, title = "Fast SMA")
plot(series = slowMA, color = #FF6A00, style = plot.style_line, linewidth = 2, title = "Slow SMA")
plotshape(series = isWithinBacktestPeriod() and startLongDeal and strategy.position_size <= 0 ? fastMA : na, title = "UpTrend Begins", location = location.absolute, style = shape.circle, size = size.tiny, color = color.green, transp = 0)
plotshape(series = isWithinBacktestPeriod() and startLongDeal and strategy.position_size <= 0 ? fastMA : na, title = "Buy", text = "Buy", location = location.absolute, style = shape.labelup, size = size.tiny, color = color.green, textcolor = color.black, transp = 0)

plot(series = strategy.position_avg_price, color = color.blue, style = plot.style_linebr, linewidth = 2, title = "Position")
plot(series = longTakeProfitPrice, color = #FFD700, style = plot.style_linebr, linewidth = 2, title = "Long Take Profit")
plot(series = longTrailingStopLossPrice, color = color.fuchsia, style = plot.style_linebr, linewidth = 2, title = "Long Trail Stop")

// ==================================================================================================================