이윤을 추적하고 손실을 중단하는 전략

저자:차오장, 날짜: 2023-12-11 09:58:35
태그:

img

전반적인 설명

트레일링 테이크프로프트 트레일링 스톱 러스 전략은 트렌드 추적, 부분적 테이크프로프트, 전체 사이클 트레일링 스톱 러스 및 기타 기능을 결합한 정량적 거래 전략이다. 이는 황소 시장의 상승 가격 추세를 파악하고 트레일링 스톱을 사용하여 하향 위험을 제어하는 동시에 지능적으로 수익을 취하는 것을 목표로합니다.

전략 논리

이 전략은 빠른 및 느린 이동 평균의 황금 십자가를 구매 신호로 사용합니다. 빠른 MA가 느린 MA보다 높을 때 상승 추세가 형성되고 전략이 길어질 것을 나타냅니다.

긴 포지션에 진입한 후, 전략은 사전 정의된 수익 취득 비율로 곱한 입시 가격에 해당하는 수익을 취하는 가격을 설정합니다. 가격이 이 수준을 달성하면 전략은 양의 50%를 기본적으로 판매하여 포지션을 부분적으로 닫습니다. 이것은 부분적인 이익을 실현하고 일부 이익을 잠금합니다.

다음으로, 트레이닝 취리 수익 메커니즘이 활성화됩니다. 가격이 계속 상승함에 따라, 취리 수익 가격은 미리 정의된 트레이닝 단계로 가격을 추적합니다. 이것은 취리 수익 가격이 상승 추세를 면밀히 따라가도록 허용하며, 후속 취리 수익 기능을 실현합니다.

동시에 트레일링 스톱도 시작된다. 가격이 이윤을 취하는 가격에 도달하면, 트레일링 스톱 가격은 높은 가격 이하의 사전 정의된 스톱 손실 비율을 유지하면서 높은 가격에 따라 상승하기 시작합니다. 이것은 추후 스톱이 상승하면서 더 많은 이익을 잠금 할 수있게하며 하향 위험을 제어합니다.

마지막으로, 만약 인하가 트레일링 스톱 가격 아래로 가격의 침투를 유발한다면, 전략은 시장 가격에 전체 포지션을 평평하게 합니다. 거래 사이클은 끝납니다.

이점 분석

트렌드 추적, 부분 수익, 전체 주기의 후속 중지 및 더 많은 통합, 전략은 다음과 같은 가장자리를 가지고 있습니다:

  1. 정확한 구매 신호로 상승 추세를 효과적으로 파악합니다.
  2. 일부 수익을 부분적으로 취득하고 모든 수익을 반환하는 것을 피합니다.
  3. 이윤을 추월하는 가격 추세는 상승 추세에 밀접하게 붙어 있습니다.
  4. 트레일링을 활성화하면 더 많은 수익을 얻을 수 있고 위험을 통제할 수 있습니다.
  5. 개인 위험 허용 수준에 맞게 조정 가능한 매개 변수

위험 분석

이 전략은 또한 다음과 같은 영역에서 몇 가지 위험을 초래합니다.

  1. 이윤을 취하지 않거나 손실을 멈추지 않고 진입한 후 가격이 급격히 역전될 수 있으며 손실이 증폭될 수 있습니다.
  2. 트렌드가 끝나면 최선 출구점을 놓치면서 수익을 추적하는 것은 실패할 수 있습니다.
  3. 너무 큰 스톱 로스 비율을 설정하면 급격한 하락 시 과도한 손실이 발생할 수 있습니다.
  4. 높은 거래 빈도는 더 큰 거래 비용과 미끄러짐으로 이어집니다.

이에 따라 최적화 및 개선하는 몇 가지 방법은 다음과 같습니다.

  1. 잘못된 신호를 피하기 위해 이동 평균 매개 변수를 적절히 설정합니다.
  2. 부분적인 수익률을 낮추고 위험을 줄이세요.
  3. 손실을 제한하기 위해 스톱 로스 비율을 강화합니다.
  4. 후속 수익 효율을 최적화하기 위해 미세한 조율 후속 단계.

최적화 방향

더 많은 최적화를 할 수 있습니다.

  1. 가짜 파장을 방지하기 위해 추세를 결정하기 위해 더 많은 지표를 추가합니다.
  2. 포지션 크기를 포함하여 포지션 금액을 더 합리적으로 만듭니다.
  3. 이윤을 취하고 손실을 멈추는 수준에 대한 동적 메커니즘을 구축하여 매개 변수를 더 적응력있게 만듭니다.
  4. 매우 변동성 있는 자산에 대한 잘못된 거래를 피하기 위해 필터를 추가합니다.

이러한 최적화는 전략을 더 견고하게 만들고 성능을 향상시킬 수 있습니다.

결론

트레일링 테이크프로프트 트레일링 스톱 로스 전략은 트렌드 추적, 지능적인 테이크프로프트, 풀 사이클 트레일링 스톱 등의 조합을 능숙하게 활용한다. 상승 추세를 포착하는 것을 바탕으로, 트레일링 스톱 레벨을 높이는 것을 실현한다. 이는 전략이 황소 시장에서 이익을 얻는 동안 트렌드를 따라갈 수 있게 한다. 또한, 자본을 보호하기 위해 부분적인 테이크프로프트와 스톱 로스를 통해 위험을 제어한다. 결론적으로, 이것은 양적 거래에서 흔히 볼 수 있는 안정적인 전략이다.


/*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")

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

더 많은