슈퍼 트렌드 추적 중지 손실 전략

저자:차오장, 날짜: 2023-12-19 11:20:15
태그:

img

전반적인 설명

이 전략은 슈퍼 트렌드 지표와 트레일링 스톱 로스를 기반으로 포지션을 열고 닫습니다. 그것은 긴 및 짧은 포지션을 열고 닫기 위해 4 개의 알림을 사용하고 슈퍼 트렌드 전략을 채택합니다. 전략은 트레일링 스톱 로스 기능을 가진 로봇을 위해 특별히 설계되었습니다.

전략 논리

이 전략은 ATR 지표를 사용하여 상위 및 하위 대역을 계산합니다. 폐쇄 가격이 상위 대역을 넘어서면 구매 신호가 생성되고, 하위 대역을 넘어서면 판매 신호가 생성됩니다. 이 전략은 또한 슈퍼 트렌드 라인을 사용하여 트렌드 방향을 결정합니다. 슈퍼 트렌드 라인이 올라갈 때 황소 시장의 시작을 나타냅니다. 내려갈 때 곰 시장의 시작을 나타냅니다. 이 전략은 신호가 생성되면 포지션을 열고 초기 스톱 로스 가격을 설정합니다. 그 다음 가격 변화에 따라 스톱 로스 가격을 조정하여 수익을 잠금하고 후속 스톱 로스 효과를 달성합니다.

이점 분석

이 전략은 트렌드 방향을 결정하기 위한 슈퍼 트렌드 지표와 스톱을 설정하기 위한 ATR 지표의 장점을 결합한다. 이는 가짜 브레이크오프를 효과적으로 필터링할 수 있다. 트레이링 스톱은 이익을 매우 잘 잠금하고 드라우다운을 줄일 수 있다. 또한, 이 전략은 로봇을 위해 특별히 설계되어 자동화된 거래를 가능하게 한다.

위험 분석

슈퍼 트렌드 지표는 더 많은 잘못된 신호를 쉽게 생성 할 수 있습니다. 스톱 손실 조정 범위가 크면 스톱 손실이 발생할 확률이 증가합니다. 또한 로봇 거래는 서버 충돌 및 네트워크 중단과 같은 기술적 위험에 직면합니다.

잘못된 신호의 가능성을 줄이기 위해 ATR 매개 변수를 적절하게 조정하거나 필터링을 위해 다른 지표를 추가 할 수 있습니다. 후속 정지 범위를 조정 할 때 이익과 위험이 균형을 잡아야합니다. 동시에 기술 장애 위험에 대비하기 위해 백업 서버와 네트워크를 준비하십시오.

최적화 방향

이 전략이 최적화 될 수 있는 몇 가지 방향은 다음과 같습니다.

  1. 입력 신호를 필터링하고 잘못된 신호를 피하기 위해 지표 또는 조건을 추가하십시오. 예를 들어 MACD 지표를 추가 할 수 있습니다.

  2. 최적의 매개 변수를 찾기 위해 다양한 ATR 매개 변수 조합을 테스트합니다.

  3. 최대의 균형점을 찾기 위해 후속 스톱 손실 범위를 최적화합니다.

  4. 더 많은 스톱 로스 가격을 추가하여 손실의 대량 스톱을 달성합니다.

  5. 주요 서버가 고장 났을 때 빠르게 전환할 수 있는 주요 서버와 대기 서버를 가진 이중 서버 아키텍처를 구축합니다.

결론

이 전략은 슈퍼 트렌드 지표와 트레일링 스톱 로스의 장점을 통합하여 손실을 자동으로 열고 중지합니다. 라이브 거래 중 최적화 방향의 개선 조치와 결합하여 매우 실용적인 양적 거래 전략이 될 수 있습니다.


/*backtest
start: 2023-11-18 00:00:00
end: 2023-12-18 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © arminomid1375
//@version=5
strategy('Mizar_BOT_super trend', overlay=true, default_qty_value=100, currency=currency.USD, default_qty_type=strategy.percent_of_equity, initial_capital=100, max_bars_back=4000)


//===== INPUTS ==========================================================================//

factor = input.float(4.5, title='ATR Factor', step=0.1,group = 'ATR')
period = input.int(59, minval=1, maxval=100, title='ATR Period',group = 'ATR')
up = (high + low) / 2 - factor * ta.atr(period)
down = (high + low) / 2 + factor * ta.atr(period)
trend_up = 0.0
trend_up := close[1] > trend_up[1] ? math.max(up, trend_up[1]) : up
trend_down = 0.0
trend_down := close[1] < trend_down[1] ? math.min(down, trend_down[1]) : down
trend = 0.0
trend := close > trend_down[1] ? 1 : close < trend_up[1] ? -1 : nz(trend[1], 1)
tsl = trend == 1 ? trend_up : trend_down
line_color = trend == 1 ? 'green' : 'red'
long_signal = trend == 1 and trend[1] == -1
short_signal = trend == -1 and trend[1] == 1
background = true


//ss =  input.float(defval=15.0, minval=0.0, title=' stop loss %',group = 'stop loss')
use_sl = input(title='trailing stop ?', defval=true,group = 'stop loss')
initial_sl_pct = input.float(defval=15.0, minval=0.0, title='trailing stop %',group = 'stop loss')

Tpactive1 = input(title='Take profit1 On/Off ?', defval=true, group='take profit')
tp1percent = input.float(5.0, title='TP1 %', group='take profit') *100
tp1amt = input.int(10, title='TP1 Amount %', group='take profit')
Tpactive2 = input(title='Take profit2 On/Off ?', defval=true, group='take profit')
tp2percent = input.float(10, title='TP2 %', group='take profit') *100
tp2amt = input.int(15, title='TP2 Amount %', group='take profit')
Tpactive3 = input(title='Take profit3 On/Off ?', defval=true, group='take profit')
tp3percent = input.float(15, title='TP3 %', group='take profit')*100
tp3amt = input.int(20, title='TP3 Amount %', group='take profit')

//===== TIMEFRAME ==========================================================================//

from_month = input.int(defval=1, title='From Month', minval=1, maxval=12)
from_day = input.int(defval=1, title='From Day', minval=1, maxval=31)
from_year = input.int(defval=2019, title='From Year', minval=2017)
to_month = input.int(defval=1, title='To Month', minval=1, maxval=12)
to_day = input.int(defval=1, title='To Day', minval=1, maxval=31)
to_year = input.int(defval=9999, title='To Year', minval=2017)
start = timestamp(from_year, from_month, from_day, 00, 00)

finish = timestamp(to_year, to_month, to_day, 23, 59)
window() =>
    time >= start and time <= finish ? true : false

//===== PLOTS ==========================================================================//

// Line
line_plot = plot(tsl, color=trend == 1 ? color.green : color.red, linewidth=2, title='Trend Line')
// Labels
plotshape(long_signal and window() ? up : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.normal, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
plotshape(short_signal and window() ? down : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.normal, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
// Circles
plotshape(long_signal and window() ? up : na, title='Uptrend starts', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.green, 0))
plotshape(short_signal and window() ? down : na, title='Downtrend starts', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.red, 0))
// Background
long_fill = background ? trend == 1 ? color.green : na : na
short_fill = background ? trend == -1 ? color.red : na : na
candle_plot = plot(ohlc4, title='Price Line', color=trend == 1 ? long_fill : short_fill, linewidth=2, transp=90)
fill(candle_plot, line_plot, title='Long Background', color=long_fill, transp=90)
fill(candle_plot, line_plot, title='Short Background', color=short_fill, transp=90)

//===== GLOBAL ==========================================================================//

var entry_price = 0.0
var updated_entry_price = 0.0
var sl_price = 0.0

longString = "Input your custom alert message here.\nAnd put {{strategy.order.alert_message}} in the message box."
longclose = "Input your custom alert message here.\nAnd put {{strategy.order.alert_message}} in the message box."
shortString = "Input your custom alert message here.\nAnd put {{strategy.order.alert_message}} in the message box."
shortclose = "Input your custom alert message here.\nAnd put {{strategy.order.alert_message}} in the message box."


longAlertMessage = input(title="Long Alert Message", defval="long", group="Alert Messages", tooltip=longString)
longcloseAlertMessage = input(title="Long close Alert Message", defval="long", group="Alert Messages", tooltip=longclose)
shortAlertMessage = input(title="Short Alert Message", defval="short", group="Alert Messages", tooltip=shortString)
shortcloseAlertMessage = input(title="Short close Alert Message", defval="short", group="Alert Messages", tooltip=shortclose)


has_open_trade() =>
    strategy.position_size != 0
has_no_open_trade() =>
    strategy.position_size == 0

is_long() =>
    strategy.position_size > 0 ? true : false
is_short() =>
    strategy.position_size < 0 ? true : false

plot(use_sl ? has_no_open_trade() ? close : sl_price : na, color=has_no_open_trade() ? na : color.blue, title='Stop Loss')

strategy_close() =>
    if is_long()
        strategy.close('Long')
        alert(longcloseAlertMessage)
    if is_short()
        strategy.close('Short')
        alert(shortcloseAlertMessage)

    
    
strategy_long() =>
    strategy.entry('Long', strategy.long)    

    

strategy_short() =>
    strategy.entry('Short', strategy.short)

sl_pct = initial_sl_pct
if long_signal or is_long() and not(short_signal or is_short())
    sl_pct := initial_sl_pct * -1
    sl_pct

//===== STRATEGY ==========================================================================//


crossed_sl = false
if is_long() and use_sl
    crossed_sl := close <= sl_price
    crossed_sl
if is_short() and use_sl
    crossed_sl := close >= sl_price
    crossed_sl

terminate_operation = window() and has_open_trade() and crossed_sl

if terminate_operation and not(long_signal or short_signal)  // Do not close position if trend is flipping anyways.
    entry_price := 0.0
    updated_entry_price := entry_price
    sl_price := 0.0
    strategy_close()



start_operation = window() and (long_signal or short_signal)

if start_operation
    entry_price := close
    updated_entry_price := entry_price
    sl_price := entry_price + entry_price * sl_pct / 100
    if long_signal
        strategy_long()
        if Tpactive1==true
            strategy.exit('TPL1','Long', qty_percent=tp1amt,profit =tp1percent)

        alert(shortcloseAlertMessage)
        alert(longAlertMessage)
    

    if short_signal
        strategy_short()
        if Tpactive1==true
            strategy.exit('TPL1','Short', qty_percent=tp1amt,profit =tp1percent)

        alert(longcloseAlertMessage)
        alert(shortAlertMessage)


//===== TRAILING ==========================================================================//

if is_long() and use_sl
    strategy_pct = (close - updated_entry_price) / updated_entry_price * 100.00
    if strategy_pct > 1
        sl_pct += strategy_pct - 1.0
        new_sl_price = updated_entry_price + updated_entry_price * sl_pct / 100
        sl_price := math.max(sl_price, new_sl_price)
        updated_entry_price := sl_price
        updated_entry_price
        

if is_short() and use_sl
    strategy_pct = (close - updated_entry_price) / updated_entry_price * 100.00
    if strategy_pct < -1
        sl_pct += strategy_pct + 1.0
        new_sl_price = updated_entry_price + updated_entry_price * sl_pct / 100
        sl_price := math.min(sl_price, new_sl_price)
        updated_entry_price := sl_price
        updated_entry_price
        




더 많은