トレンドフォロー型の利益確定とトレーリングストップロス戦略


作成日: 2023-12-11 09:58:35 最終変更日: 2023-12-11 09:58:35
コピー: 0 クリック数: 849
1
フォロー
1621
フォロワー

トレンドフォロー型の利益確定とトレーリングストップロス戦略

概要

トレンドフォローストップフォローストップ戦略は,トレンドフォロー,部分ストップ,全過程のストップフォローなどの機能を組み合わせた量化取引戦略であり,牛市情勢で価格上昇の傾向を捕捉し,スマートストップを使用して利益を得ることを目的としており,同時にストップフォローストップを利用して下行リスクを制御します.

戦略原則

この戦略は,迅速な移動平均と遅い移動平均の金叉を買い信号として使用する. 迅速な移動平均の上に遅い移動平均が横切るときは,価格上昇傾向が形成され,この戦略は,より多くのポジションを開く.

その後,ストップ価格が設定され,これは開設価格に設定されたストップの比率を掛けることと等しくなります.価格がストップ価格に達すると,戦略は部分的に平仓し,デフォルトで50%のポジションを販売します.これは部分的にストップを実現し,部分的に利益をロックします.

次に,戦略は,トレンド追跡ストップの仕組みを起動します.価格が上昇し続けると,ストップ価格は,設定されたステップ割合 trailingTakeProfitDeviationPercで価格を追跡します.これは,ストップ価格が価格上昇の傾向に緊密に追いついて,トレンド追跡ストップを実現します.

同時に,戦略は,ストップ・ロスの追跡を起動します.価格がストップ・価格に達すると,ストップ・ロスの価格は上位に移動し,常に高点の倍数で,ストップ・ロスの下位比率を設定するレベルを維持します.これは,ストップ・ロスの価格を上位に移動させ,より多くの利益をロックし,下位リスクも制御します.

価格が反動したときに,ストップ・ロスの追跡価格を下破した場合,戦略は追跡を停止し,市場価格平仓の残りの全ポジションを直接行います. この時点で,取引のサイクル全体が完了します.

優位分析

この戦略は,トレンド追跡,部分停止,全コース追跡ストップなどの複数の機能を統合し,以下の利点があります.

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

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