Strategies
SuperTrend动态止盈与时间过滤器策略波动适应型量化交易系统-SuperTrend-Dynamic-Take-Profit-with-Time-Filter-Strategy-Volatility-Adaptive-Quantitative-Trading-System
ianzeng123 · PineScript · Trend Following · 2025-03-26 13:12:56
Trend Following
Mean ReversionVolatility and Channels
Uptrend · InferredDowntrend · InferredRange · Inferred
Sizing
Risk control
Exit
—
Context terms
No English write-up in the source (no author description).
Source code (138 lines)
/*backtest
start: 2024-03-26 00:00:00
end: 2024-07-11 00:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/
//@version=6
strategy("Supertrend Fixed TP Unified with Time Filter (MSK)", overlay=true,
default_qty_value=0.01,
commission_type=strategy.commission.percent,
commission_value=0.06,
pyramiding=0,
process_orders_on_close=true)
// Настройки индикатора
atrPeriod = input(23, "ATR Length")
factor = input.float(1.8, "Factor", step=0.1, minval=0.1)
tradeMode = input.string("Both", "Trade Mode", options=["Long Only", "Short Only", "Both"])
// Общий параметр тейк-профита
takeProfitPercent = input.float(1.5, "Take Profit (%)", minval=0.01)
showTP = input.bool(true, "▲▼ Показывать ТП") // Добавлен переключатель
// Фильтр цены
price_param = input.float(10000.0, "Цена фильтра", step=1.0)
use_price_filter = input.bool(false, "Использовать фильтр цены")
// Фильтр по времени (Московское время)
useTimeFilter = input.bool(true, "▲▼ Использовать фильтр по времени") // Переключатель фильтра времени
timeFrom = input.int(0, "Время С (часы MSK)", minval=0, maxval=23, step=1)
timeTo = input.int(23, "Время ДО (часы MSK)", minval=0, maxval=23, step=1)
// Функция проверки времени (с учетом Московского времени UTC+3)
isTimeInRange() =>
if not useTimeFilter
true // Фильтр отключен
else
// Переводим время сервера (UTC) в Московское время (UTC+3)
mskHour = (hour(time) + 3) % 24 // Добавляем 3 часа для MSK
if timeFrom <= timeTo
mskHour >= timeFrom and mskHour < timeTo // До timeTo (не включая timeTo)
else
mskHour >= timeFrom or mskHour < timeTo // До timeTo (не включая timeTo)
// Расчет Supertrend
[supertrend, dir] = ta.supertrend(factor, atrPeriod)
// Визуализация Supertrend
plot(supertrend, "Supertrend",
color = dir < 0 ? color.green : color.red,
linewidth = 2,
style = plot.style_linebr)
bgcolor(dir < 0 ? color.new(color.green, 90) : color.new(color.red, 90))
// Сигналы входа с фильтром по времени
longEntry = (dir < 0 and dir[1] > 0) and (use_price_filter ? close > price_param : true) and isTimeInRange()
shortEntry = (dir > 0 and dir[1] < 0) and (use_price_filter ? close < price_param : true) and isTimeInRange()
// Логика стратегии
if tradeMode == "Both"
if longEntry
strategy.close("Short", comment="Close Short")
strategy.entry("Long", strategy.long)
if shortEntry
strategy.close("Long", comment="Close Long")
strategy.entry("Short", strategy.short)
else if tradeMode == "Long Only"
if longEntry
strategy.entry("Long", strategy.long)
if shortEntry
strategy.close("Long", comment="Close Long")
else if tradeMode == "Short Only"
if shortEntry
strategy.entry("Short", strategy.short)
if longEntry
strategy.close("Short", comment="Close Short")
// Управление тейк-профитом
var color tpColor = na
var float tpLevel = na
var label tpLabel = na
// Сброс при закрытии позиции
if strategy.position_size == 0 and strategy.position_size[1] != 0
tpLevel := na
tpColor := na
label.delete(tpLabel)
tpLabel := na
// Обновление ТП при открытии позиции
if strategy.position_size > 0
entryPrice = strategy.opentrades.entry_price(0)
tpLevel := entryPrice * (1 + takeProfitPercent/100)
tpColor := color.green
// Закрытие лонга по TP на закрытии бара
if close >= tpLevel
strategy.close("Long", comment="TP Long")
// Обновление метки
if showTP
label.delete(tpLabel)
tpLabel := label.new(
bar_index, tpLevel,
text = str.tostring(tpLevel, "#.##"),
color = color.green,
textcolor = color.white,
style = label.style_label_down,
yloc = yloc.price)
if strategy.position_size < 0
entryPrice = strategy.opentrades.entry_price(0)
tpLevel := entryPrice * (1 - takeProfitPercent/100)
tpColor := color.red
// Закрытие шорта по TP на закрытии бара
if close <= tpLevel
strategy.close("Short", comment="TP Short")
// Обновление метки
if showTP
label.delete(tpLabel)
tpLabel := label.new(
bar_index, tpLevel,
text = str.tostring(tpLevel, "#.##"),
color = color.red,
textcolor = color.white,
style = label.style_label_up,
yloc = yloc.price)
// Визуализация ТП
plot(showTP ? tpLevel : na, "Take Profit",
color = tpColor,
linewidth = 1,
style = plot.style_circles)
// Обновление позиции метки
if showTP and not na(tpLevel)
label.set_xy(tpLabel, bar_index, tpLevel)