
Esta estrategia determina la tendencia calculando el cruce de las medias móviles rápidas y las medias móviles lentas, hace un exceso al cruzar las medias móviles lentas en las medias móviles rápidas y establece una línea de parada de seguimiento dinámico para bloquear las ganancias, y se retira de la parada de pérdidas cuando el precio cambia una cierta proporción.
La estrategia utiliza una media móvil rápida y una media móvil lenta para determinar el comienzo de una tendencia múltiple. En concreto, se calcula una media móvil simple del precio de cierre en un período determinado, comparando los valores de la media móvil rápida y la media móvil lenta, cuando la media móvil rápida atraviesa la media móvil lenta, se determina el comienzo de una tendencia múltiple, y se abre una posición más.
La estrategia no establece un stop-loss fijo después de abrir una posición, sino que utiliza una línea de stop-loss de seguimiento dinámico para bloquear los beneficios. El método de configuración de esta línea de stop-loss es:*(1- el porcentaje de stop loss establecido). Esto permite que la línea de stop loss aumente a medida que el precio sube, y que la línea de stop loss se retire cuando el precio descienda en una proporción determinada.
La ventaja de este método es que se puede obtener un beneficio ilimitado y se puede bloquear el beneficio con un stop loss una vez que los beneficios alcanzan un cierto nivel.
Las principales ventajas de esta estrategia de seguimiento dinámico son:
Se puede hacer un seguimiento ilimitado y no perderse un gran evento. El uso de un stop loss fijo es fácil de eliminar después del inicio de un gran evento.
Se puede bloquear la ganancia mediante el establecimiento de un porcentaje de stop loss. Si solo se persigue la pérdida, se puede perder al final de toda la operación. Se puede bloquear la ganancia mediante el establecimiento de un stop loss.
Es más flexible que el stop-loss fijo. El stop-loss fijo solo puede establecer un precio, y aquí el stop-loss cambia según el precio más alto.
El riesgo de retiro es menor. Cuando se utiliza el stop-loss fijo, el precio de parada es más grande que el precio máximo, y puede ser detenido en una recuperación normal.
La estrategia también tiene sus riesgos:
Los indicadores de las señales de entrada son inestables y pueden generar señales erróneas.
El único método de detener el daño, sin tener en cuenta otros factores. El mercado puede sufrir cambios significativos repentinos que pueden hacer que la estrategia no funcione.
No hay límite de parada, depende de la parada de pérdidas. Si la parada de pérdidas no es efectiva, puede causar una pérdida mayor.
La configuración de los datos necesita ser optimizada. Los parámetros como el ciclo de las medias móviles necesitan ser ajustados a lo óptimo.
La estrategia también puede ser optimizada en los siguientes aspectos:
Añadir más indicadores para confirmar la admisión y evitar señales erróneas, como la adición de la cantidad de transacciones.
Aumentar la configuración de la parada. Se detiene cuando el rendimiento alcanza una cierta proporción.
Aumentar la seguridad del stop loss. Ajustar drásticamente la distancia de stop loss cuando ocurren anomalías en el mercado.
Adaptación para la optimización de la variedad de transacción, el tiempo de transacción, etc. Los parámetros de las diferentes variedades y tiempos de transacción requieren ajustes.
Añadir aprendizaje automático para ajustar dinámicamente los parámetros. Permitir que el modelo optimice automáticamente los indicadores de juicio y el stop loss.
La idea general de esta estrategia es clara y razonable, el uso de un criterio de tendencia de mediano rápido y lento es un método más clásico, y el método de seguimiento dinámico del deterioro puede bloquear efectivamente los beneficios y reducir el riesgo. Sin embargo, estos indicadores y parámetros necesitan ser probados y optimizados constantemente para que la estrategia sea rentable y estable. Al mismo tiempo, también debe evitar que los cambios importantes en el mercado afecten a la estrategia, lo que debe lograrse mediante la mejora de la idea general y el marco, aumentando el mecanismo de seguridad.
/*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)
// ==================================================================================================================