
이 전략은 빠른 이동 평균과 느린 이동 평균의 교차를 계산하여 추세를 판단하고, 빠른 이동 평균에서 느린 이동 평균을 통과 할 때 더 많이하고, 수익을 고정하기 위해 동적으로 추적 된 스톱 라인을 설정하여 가격의 변화의 일정한 비율에 스톱 손실을 철회합니다.
이 전략은 빠른 이동 평균과 느린 이동 평균의 골드 포크를 사용하여 다면 트렌드의 시작을 판단한다. 구체적으로, 특정 주기 내의 종결 가격의 간단한 이동 평균을 계산하여 빠른 평균과 느린 평균의 값을 비교합니다. 빠른 이동 평균에서 느린 이동 평균을 통과하면 다면 트렌드가 시작되었다고 판단되며, 이 때 더 많은 위치를 열습니다.
포지션을 열고 더 많이 한 후, 전략은 고정된 스톱 로드를 설정하지 않고, 동적으로 추적되는 스톱 라인을 사용하여 수익을 잠금합니다. 이 스톱 라인을 설정하는 방법은 다음과 같습니다: 최고 가격*(1-설정된 스톱로스 비율) ᅳ 이렇게 하면 스톱로스 라인이 가격 상승에 따라 상승하고, 일정 비율이 떨어지면 스톱로스 철수할 수 있다.
이 방식의 장점은 무한히 회수할 수 있고, 수익이 일정 수준에 도달한 후 스톱로스로 수익을 잠금할 수 있다는 것이다.
이 전략의 주요 장점은 다음과 같습니다.
무한히 추격할 수 있고, 큰 행태를 놓치지 않는다. 고정된 스톱더는 큰 행태가 시작된 후 손해가 막히기 쉽다.
중지 손실 비율을 설정하여 수익을 잠금 할 수 있습니다. 손실을 추적 할 수없는 경우, 전체 거래가 끝날 때 손실이 발생할 수 있습니다. 중지 손실을 설정하면 수익을 잠금 할 수 있습니다.
고정 스톱보다 더 유연하다. 고정 스톱은 오직 하나의 가격을 설정할 수 있으며, 여기서 스톱은 최고 가격에 따라 변한다.
철회 위험은 작다. 고정된 스톱로드를 적용할 때, 스톱로드는 최고 가격으로부터 큰 거리이며, 정상적인 회귀에서는 스톱로드가 될 수 있다. 여기서 스톱로드는 최고 가격으로부터 가까운 거리이며, 정상적인 회귀는 스톱로드가 되지 않는다.
이 전략에는 몇 가지 위험도 있습니다.
출입 신호의 지표가 불안정하여 잘못된 신호가 발생할 수 있다.
단 하나의 손실 방식, 다른 요소를 고려하지 않습니다. 시장의 급격한 중대한 변화가 전략의 실패로 이어질 수 있습니다.
정지 제한이 없고, 손실을 막는 것에 의존한다. 정지 효과가 없다면, 큰 손실이 발생할 수 있다.
데이터 설정은 최적화해야 한다. 이동 평균 주기 등의 파라미터를 최적화해야 한다.
이 전략은 다음과 같은 부분에서 최적화될 수 있습니다.
입시를 확인하기 위해 더 많은 지표를 추가하고, 잘못된 신호를 피하십시오. 예를 들어, 거래량 판단을 추가하십시오.
쉼표 설정을 추가하세요. 수익이 일정 비율에 도달했을 때 멈춰주세요.
손실을 막는 안전성을 높여줍니다. 시장의 이상 현상이 발생했을 때 손실을 막는 거리를 크게 조정합니다.
거래 품종, 거래 시간 등에 대한 최적화 조정. 다른 품종 및 거래 시간 파라미터를 조정해야 한다.
기계학습을 추가하여 동적으로 변수를 조정합니다. 모델이 자동으로 판단 지표와 중지 손실을 최적화합니다.
이 전략의 전체적인 아이디어는 명확하고 합리적입니다. 급속한 평균선 판단 트렌드를 사용하는 것은 고전적인 방법이며, 동적으로 추적하는 스톱로드를 사용하는 방법은 수익을 효과적으로 잠금하고 위험을 줄일 수 있습니다. 그러나 이러한 지표와 매개 변수는 전략을 안정적으로 수익을 내기 위해 지속적으로 테스트 및 최적화가 필요합니다. 또한 시장의 중요한 변화가 전략에 미치는 영향을 방지해야합니다.
/*backtest
start: 2023-12-01 00:00:00
end: 2023-12-31 23:59:59
period: 4h
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.0
// Date: 05-May-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.
// Enable Trailing - Enable or disable the trailing.
// Stop Loss % - The percentage of the price decrease to set the stop loss price target 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 Stop Loss",
shorttitle = "TSL",
overlay = true,
pyramiding = 0,
calc_on_every_tick = true,
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.")
enableStopLossTrailing = input(defval = true, title = "Enable Trailing", type = input.bool, group = "Strategy", tooltip = "Enable or disable the trailing for stop loss.")
longTrailingStopLossPerc = input(defval = 7.5, title = 'Long Stop Loss %', type = input.float, minval = 0.1, maxval = 100, step = 0.1, inline = "Trailing Stop Loss Perc", group = "Strategy") / 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
// 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 LOGIC ===================================================================================================
fastMA = sma(close, fastMALen)
slowMA = sma(close, slowMALen)
bool startLongDeal = crossover(fastMA, slowMA)
bool longIsActive = startLongDeal or strategy.position_size > 0
// determine trailing stop loss price
float longTrailingStopLossPrice = na
longTrailingStopLossPrice := if (longIsActive)
stopValue = high * (1 - longTrailingStopLossPerc)
max(stopValue, nz(longTrailingStopLossPrice[1]))
else
na
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// STRATEGY EXECUTION ===============================================================================================
if (isWithinBacktestPeriod())
// getting into LONG position
strategy.entry(id = "Long Entry", long = strategy.long, when = startLongDeal, alert_message = "Long(" + syminfo.ticker + "): Started")
// submit exit orders for trailing stop loss price
strategy.exit(id = "Long Stop Loss", from_entry = "Long Entry", stop = longTrailingStopLossPrice, when = longIsActive, alert_message = "Long(" + syminfo.ticker + "): Stop Loss activated")
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// PLOT DATE POSITION MA AND TRAILING TAKE PROFIT STOP LOSS =========================================================
bgcolor(color = showDate and isWithinBacktestPeriod() ? color.gray : na, transp = 90)
plot(series = fastMA, title = "Fast SMA", color = #0056BD, linewidth = 2, style = plot.style_line)
plot(series = slowMA, title = "Slow SMA", color = #FF6A00, linewidth = 2, style = plot.style_line)
plotshape(series = isWithinBacktestPeriod() and startLongDeal and strategy.position_size <= 0 ? fastMA : na, title = "UpTrend Begins", style = shape.circle, location = location.absolute, color = color.green, transp = 0, size = size.tiny)
plotshape(series = isWithinBacktestPeriod() and startLongDeal and strategy.position_size <= 0 ? fastMA : na, title = "Buy", text = "Buy", style = shape.labelup, location = location.absolute, color = color.green, textcolor = color.black, transp = 0, size = size.tiny)
plot(series = strategy.position_avg_price, title = "Position", color = color.blue, linewidth = 2, style = plot.style_linebr, offset = 1)
plot(series = longTrailingStopLossPrice, title = "Long Trail Stop", color = color.fuchsia, linewidth = 2, style = plot.style_linebr, offset = 1)
// ==================================================================================================================