
La estrategia es un sistema de negociación avanzado basado en análisis de múltiples períodos de tiempo, que captura oportunidades de reversión del mercado mediante la identificación de puntos centrales clave en períodos de tiempo más altos. La estrategia combina un mecanismo de stop loss de porcentaje dinámico para controlar el riesgo de manera efectiva y buscar ganancias estables. El sistema también incluye control de intervalo de negociación y funciones de prueba de rango de tiempo, lo que lo hace más adecuado para un entorno de negociación de disco real.
La lógica central de la estrategia se basa en los siguientes elementos clave:
La estrategia proporciona un marco completo para el sistema de negociación a través de análisis de múltiples ciclos de tiempo y gestión de riesgos dinámicos. Si bien hay algunos lugares que necesitan ser optimizados, el concepto de diseño general es razonable y tiene una buena practicidad. A través de la orientación de optimización sugerida, la estrategia espera obtener un rendimiento más estable en diferentes entornos de mercado.
/*backtest
start: 2025-01-01 00:00:00
end: 2025-01-31 23:59:59
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=6
strategy("Pivot Reversal Strategy with MTF TP & SL in Percent and Test Range", overlay=true)
// Входные параметры
higher_tf = input.timeframe("60", title="Higher Timeframe for Breakout Check") // Таймфрейм для анализа пробоя
leftBars = input(4, title="Left Bars")
rightBars = input(2, title="Right Bars")
TP_percent = input.float(1.0, title="Take Profit (%)", minval=0.1, step=0.1) // Тейк-профит в процентах
SL_percent = input.float(0.5, title="Stop Loss (%)", minval=0.1, step=0.1) // Стоп-лосс в процентах
trade_interval = input.int(1440, title="Minimum Time Between Trades (Minutes)") // Интервал между сделками
// Диапазон тестирования (используем UNIX timestamps)
start_date = input(timestamp("2023-01-01 00:00 +0000"), title="Start Date") // Стартовая дата для тестирования
end_date = input(timestamp("2023-12-31 23:59 +0000"), title="End Date") // Конечная дата для тестирования
// Проверка, попадает ли текущая свеча в указанный диапазон времени
in_test_range = true
// Определение пивотов на более крупном таймфрейме
higher_tf_high = request.security(syminfo.tickerid, higher_tf, ta.pivothigh(leftBars, rightBars))
higher_tf_low = request.security(syminfo.tickerid, higher_tf, ta.pivotlow(leftBars, rightBars))
// Последнее время открытия сделки
var float last_trade_time = na
// Логика для лонга
swh_cond = not na(higher_tf_high)
hprice = 0.0
hprice := swh_cond ? higher_tf_high : hprice[1]
le = false
le := swh_cond ? true : (le[1] and high > hprice ? false : le[1])
if le and in_test_range and (na(last_trade_time) or (time - last_trade_time >= trade_interval * 60 * 1000))
tp_price_long = hprice * (1 + TP_percent / 100) // Тейк-профит в процентах
sl_price_long = hprice * (1 - SL_percent / 100) // Стоп-лосс в процентах
strategy.entry("PivRevLE", strategy.long, stop=hprice + syminfo.mintick)
strategy.exit("TP_SL_Long", from_entry="PivRevLE",
limit=tp_price_long,
stop=sl_price_long)
last_trade_time := time
// Логика для шорта
swl_cond = not na(higher_tf_low)
lprice = 0.0
lprice := swl_cond ? higher_tf_low : lprice[1]
se = false
se := swl_cond ? true : (se[1] and low < lprice ? false : se[1])
if se and in_test_range and (na(last_trade_time) or (time - last_trade_time >= trade_interval * 60 * 1000))
tp_price_short = lprice * (1 - TP_percent / 100) // Тейк-профит в процентах
sl_price_short = lprice * (1 + SL_percent / 100) // Стоп-лосс в процентах
strategy.entry("PivRevSE", strategy.short, stop=lprice - syminfo.mintick)
strategy.exit("TP_SL_Short", from_entry="PivRevSE",
limit=tp_price_short,
stop=sl_price_short)
last_trade_time := time
// Для наглядности отображаем уровни на графике
plot(le and in_test_range ? hprice * (1 + TP_percent / 100) : na, color=color.green, title="Long Take Profit")
plot(le and in_test_range ? hprice * (1 - SL_percent / 100) : na, color=color.red, title="Long Stop Loss")
plot(se and in_test_range ? lprice * (1 - TP_percent / 100) : na, color=color.green, title="Short Take Profit")
plot(se and in_test_range ? lprice * (1 + SL_percent / 100) : na, color=color.red, title="Short Stop Loss")