유연한 스톱 로스로 PB SAR 백테스트 전략

저자:차오장, 날짜: 2023-10-11 15:22:26
태그:

개요

이 전략은 탄력적인 중단 손실 지표에 기초하여, 구매 및 판매 신호를 설정하고, 장차 및 단차 동작을 수행한다. 지표가 구매 신호가 나타나면 더 많이 하고, 판매 신호가 나타나면 공백한다. 이 전략은 또한 추적 중지 손실 메커니즘을 결합하여 위험을 효과적으로 제어한다.

원리

이 전략은 주로 탄력적 중단 지표가 트렌드를 식별하는 전환점을 활용하여 역전을 수행한다. 지표 내부에서 실제 범위 지표를 사용하여 극한값을 식별하고, 가격이 극한값을 초과할 때 비정상적인 돌파로 간주하여 트렌드 역전의 가능성을 판단한다. 구체적으로 지표 내부에서 두 가지 변수를 유지한다: 극한값 (EP) 및 트리거 가격 (TP). EP는 현재 트렌드 아래의 최고 또는 최저 가격을 나타낸다. TTP는 EP에 의해 계산된다.

상승 추세에서는 가격이 EP보다 높을 때 이상적인 돌파로 결정되며, 이 경우 EP는 최고 가격으로, TP는 최저 가격으로 갱신됩니다. TP보다 낮을 때 추세가 반전되어 판매 신호를 생성합니다. 하락 추세에서는 원리는 비슷합니다.

이 전략은 트래킹 스톱 손실 메커니즘을 결합하여 포지션이 열렸을 때 최적의 스톱 손실 가격을 실시간으로 추적하여 수익을 보장하면서 위험을 제어합니다. 구체적으로, 오버 작업 후 스톱 손실 라인은 종료 하락을 추적합니다.

장점

이 전략은 다음과 같은 장점을 가지고 있습니다.

  1. 이 지표는 트렌드 전환점을 식별하는 지표로 사용되는데, 쉽게 잡히지 않습니다.

  2. 손해배상 매커니즘을 추적하여 수익을 차단하고 손실 확장을 방지할 수 있습니다.

  3. 지표의 매개 변수는 간단하고 구현하기 쉽습니다.

  4. 구매/판매 신호 신호를 설정하여 조작이 편리합니다.

  5. 유연하게 재검토 주기를 구성하여 전략 효과를 종합적으로 평가하십시오.

위험성

이 전략에는 몇 가지 위험이 있습니다.

  1. 지표가 뒤쳐져 있고, 트렌드 전환의 최적의 지점을 놓칠 수 있습니다.

  2. 이 지수는 너무 급격해서 단기적인 가격 불안에 의해 지워질 수 있습니다.

  3. 재검토 주기는 잘못된 선택으로 전략의 효과를 완전히 평가할 수 없습니다.

  4. 거래 비용이 수익에 미치는 영향에 대해 관심을 가져야 합니다.

이러한 위험에 대응하여 다음과 같은 측면에서 최적화 할 수 있습니다.

  1. 지표 매개 변수를 조정하여 지연을 줄입니다.

  2. 손해를 막기 위한 알고리즘을 최적화하여 집단을 피할 수 있습니다.

  3. 적절한 재검토 주기를 선택하여 신뢰성을 보장합니다.

  4. 거래 비용을 줄이기 위해 포지션 관리를 최적화합니다.

최적화 방향

이 전략은 다음과 같은 부분에서 더욱 최적화 될 수 있습니다.

  1. 트렌드 지표와 결합하여 역거래를 피하기 위해 묶여 있습니다. MA와 같은 지표가 큰 트렌드를 판단 할 수 있습니다.

  2. 고정 비율 포지션, 동적 포지션 등 포지션 관리 알고리즘을 최적화합니다.

  3. 거래량 필터링에 참여하여 격차로 인한 잘못된 거래를 피하십시오.

  4. 가장 좋은 파라미터 조합을 찾기 위해 파라미터 최적화를 수행합니다.

  5. 트렌드 실행에 대비하여 정지 전략에 참여하여 정지하십시오.

  6. 중지 손실을 더 부드럽게 만들기 위해 중지 손실 전략을 최적화하십시오. Chandelier Exit와 같은 중지 손실 알고리즘을 시도 할 수 있습니다.

  7. 거래 종류, 시간 단위 등을 최적화하여 전략적 적응성을 높입니다.

  8. 기계 학습 알고리즘을 추가하여 전략을 더 적응시킬 수 있습니다.

요약

이 전략은 전반적으로 간단하고 신뢰할 수 있으며, 탄력적인 중단 지표를 사용하여 반전 지점을 식별하고, 중단 메커니즘을 추적하여 위험을 제어 할 수 있으며, 단선 역전 전략으로 사용될 수 있습니다. 그러나 여전히 지표 지체, 중단 지표가 너무 급격하다는 문제와 같은 문제에 주의해야합니다. 추가 최적화로 더 나은 전략 효과를 얻을 수 있습니다.

전반적인 설명

이 전략은 장기 및 단위 포지션에 대한 구매 및 판매 신호를 생성하기 위해 Parabolic SAR 지표를 기반으로합니다. 또한 위험을 효과적으로 제어하기 위해 후속 스톱 로스 메커니즘을 통합합니다.

원칙

이 전략의 핵심은 트렌드 반전 지점을 확인하는 데에 있다. 트렌드 상거래를 위해 파라볼릭 SAR 지표를 사용한다. 이 지표는 극한 가격을 감지하기 위해 진정한 범위를 사용합니다. 가격이 극한을 초과할 때, 그것은 브레이크업으로 간주되며 잠재적인 트렌드 반전의 신호입니다. 구체적으로, 지표는 두 가지 변수를 유지합니다: 극한 가격 (EP) 및 트리거 가격 (TP). EP는 현재 트렌드의 가장 높고 가장 낮은 가격을 나타냅니다. TP는 EP에서 파생됩니다.

상승 트렌드에서는 가격이 EP보다 높을 때 브레이크오웃으로 간주됩니다. EP는 가장 높은 가격으로 업데이트되고 TP는 가장 낮은 가격으로 업데이트됩니다. 가격이 TP 이하로 떨어지면 트렌드 역전이 확인되고 판매 신호가 생성됩니다. 같은 원칙은 하락 트렌드에 적용됩니다.

이 전략은 또한 트레일링 스톱 로스 메커니즘을 포함합니다. 포지션을 열면 최적의 스톱 로스 가격을 실시간으로 추적하여 리스크를 제어하면서 수익을 잠금합니다. 구체적으로, 긴 엔트리 후, 스톱 로스는 닫는 최저치를 추적합니다. 짧은 엔트리 후, 닫는 최고치를 추적합니다.

장점

이 전략의 주요 장점은 다음과 같습니다.

  1. 트렌드 전환 지점을 지표로 파악하여 트렌드에 갇히지 않도록 합니다.

  2. 손해를 막는 것은 수익을 막고 더 큰 손실을 방지합니다.

  3. 간단한 지표 매개 변수, 실행하기 쉬운

  4. 편리함을 위해 구매/판매 신호 알림을 구성할 수 있습니다.

  5. 융통성 있는 백테스트 기간 구성

위험성

또한 고려해야 할 몇 가지 위험이 있습니다.

  1. 지표 지연은 최적의 반전 지점을 놓칠 수 있습니다.

  2. 공격적인 정지는 단기 변동에 의해 중단 될 수 있습니다.

  3. 잘못된 백테스트 기간 선택은 전략을 완전히 평가 할 수 없습니다.

  4. 거래 비용은 수익을 저하시킬 수 있습니다.

위험 요소 를 해결 할 수 있는 몇 가지 방법 은 다음과 같다.

  1. 지연을 줄이기 위해 파라미터 최적화

  2. 불필요하게 멈추지 않도록 스톱 로스 알고리즘을 개선합니다.

  3. 신뢰성을 위해 적절한 백테스트 기간을 선택합니다.

  4. 거래 비용을 낮추기 위해 포지션 사이즈를 최적화합니다.

강화

전략을 더 최적화 할 수있는 몇 가지 방법:

  1. MA와 같은 트렌드 지표를 포함하여 역 트렌드에 갇히지 않도록 합니다.

  2. 위치 사이즈 알고리즘을 최적화, 예를 들어 고정 분수, 동적.

  3. 빈틈에서 잘못된 신호를 피하기 위해 볼륨 필터를 추가합니다.

  4. 최적의 조합을 찾기 위해 매개 변수 최적화

  5. 트렌드에서 수익을 확보하기 위해 수익을 취하는 전략을 실행하십시오.

  6. 더 부드러운 스톱 손실 알고리즘을 정비합니다. 캔들리어 출구 등을 실험합니다.

  7. 제품, 시간 프레임 등을 최적화하여 적응력을 향상시킵니다.

  8. 더 많은 적응력을 위해 기계 학습을 통합합니다.

요약

요약하자면, 이것은 리버설을 식별하고 위험을 제어하기 위해 트레일링 스톱 로스를 사용하는 단순하고 강력한 전략입니다. 단기 평균 리버설 전략으로 작동 할 수 있습니다. 그러나 지표 지연 및 과민 스톱은 해결해야합니다. 추가 최적화는 향상된 성능으로 이어질 수 있습니다.


/*backtest
start: 2023-09-10 00:00:00
end: 2023-10-10 00:00:00
period: 2h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4
strategy("PB SAR BackTest - Colorbar", overlay=false)

// Full credit to Sawcruhteez, Lucid Investment Strategies LLC, Casey Bowman and Peter Brandt.
// This is a strategy version of the Peterbolic SAR indicator created by the above-mentioned parties.
// Original version of the indicator: https://www.tradingview.com/script/6nYrH3Vm-Peterbolic-SAR/

// SAR #1
// Lucid Sar
// Branded under the name "Lucid SAR"
// as agreed to with Lucid Investment Strategies LLC on July 9, 2019
// https://lucidinvestmentstrategies.com/
// see branch "lucid"

// SAR #2
// Peterbolic Sar
// Using the name "Peterbolic SAR"
// as agreed to by Peter Brandt on October 2, 2019
// - https://twitter.com/PeterLBrandt/status/1179365590668075008
// in response to request from Sawcruhteez
// - https://twitter.com/Sawcruhteez/status/1179213105705836544
// Sawcruhteez gives credit to @CrazyGabey for coming up with the name
// - https://twitter.com/Sawcruhteez/status/1179213196583940097
// see branch "peterbolic"

// SAR #3
// Sawcruhteez Sar
// Branded under the name "Sawcruhteez SAR"
// as agreed to with Sawcruhteez on September 11, 2019
// see branch "sawcruhteez"

// Open Source on github
// https://github.com/casey-bowman/sar/blob/peterbolic/peterbolic.pine

// Created by Casey Bowman on July 4, 2019

// MIT License

// Copyright (c) 2019 Casey Bowman

// 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.



TSR() =>

    // start with uptrend
    var uptrend = true
    var EP = high       // extreme price - high or low depending on trend
    var SP = low        // setup price
    var TP = float(na)  // trigger price


    var setup   = low
    var trigger = float(na)

    if barstate.isnew
        setup := low
        trigger = float(na)

    extreme_candle = false
    first_extreme_candle = false
    setup_candle = false
    trigger_candle = false

    waiting_for_setup = false
    waiting_for_trigger = false

    var since_extreme = 0
    var since_setup = 0

    waiting_for_setup   := not extreme_candle and not na(SP)
    waiting_for_trigger := not na(TP)

    if not barstate.isfirst
        if barstate.isnew and extreme_candle[1]
            trigger := float(na)
        if barstate.isnew and setup_candle[1]
            setup := float(na)
        if barstate.isnew and waiting_for_trigger
            since_setup := since_setup + 1
            trigger := TP
        if barstate.isnew and waiting_for_setup
            since_extreme := since_extreme + 1
            setup := SP
        if uptrend

            if extreme_candle
                EP := high
                SP := low
            else
                if high > EP
                    extreme_candle := true
                    EP := high
                    SP := low
                    since_extreme := 0
                    since_setup   := 0
                else
                    if waiting_for_setup
                        if barstate.isconfirmed
                            if close < SP
                                setup_candle := true
                                SP := float(na)
                                TP := low
            if waiting_for_trigger
                if low < TP
                    trigger_candle := true
                    extreme_candle := true
                    EP := low
                    SP := high
                    TP := float(na)
                    uptrend := false
                    since_extreme := 0
                    since_setup := 0
                else
                    if barstate.isconfirmed and extreme_candle
                        TP := float(na)
                        trigger := float(na)

        else
            if extreme_candle
                EP := low
                SP := high
            else
                if low <  EP
                    extreme_candle := true
                    EP := low
                    SP := high
                    since_extreme := 0
                    since_setup   := 0
                else
                    if waiting_for_setup
                        if barstate.isconfirmed
                            if close > SP
                                setup_candle := true
                                SP := float(na)
                                TP := high
            if waiting_for_trigger
                if high > TP
                    trigger_candle := true
                    extreme_candle := true
                    EP := high
                    SP := low
                    TP := float(na)
                    uptrend := true
                    since_extreme := 0
                    since_setup := 0
                else
                    if barstate.isconfirmed and extreme_candle
                        TP := float(na)
                        trigger := float(na)


    [trigger_candle, trigger, since_setup, setup_candle, setup, since_extreme, extreme_candle, uptrend]


[TC, T, SS, SC, S, SE, EC, up] = TSR()

// Make input options that configure backtest date range
StartMonth = input(title="Start Month", type=input.integer,
     defval=1, minval=1, maxval=12)
StartDate = input(title="Start Date", type=input.integer,
     defval=1, minval=1, maxval=31)
StartYear = input(title="Start Year", type=input.integer,
     defval=(2019), minval=1800, maxval=2100)

EndMonth = input(title="End Month", type=input.integer,
     defval=1, minval=1, maxval=12)
EndDate = input(title="End Date", type=input.integer,
     defval=1, minval=1, maxval=31)
EndYear = input(title="End Year", type=input.integer,
     defval=(2020), minval=1800, maxval=2100)
     
// Look if the close time of the current bar falls inside the date range
inDateRange = true

buytrigger = (TC and up)
selltrigger = (TC and not up)
buysetup = (SC and not up)
sellsetup = (SC and up)

IntBuy = buytrigger ? 1 : 0
IntSB = buysetup ? 0.5 : 0

IntSell= selltrigger ? -1 : 0
IntSS = sellsetup ? -0.5 : 0

bgcolor = buytrigger ? color.green : selltrigger ? color.red : buysetup ? color.yellow : sellsetup ? color.orange : color.black
trans = buytrigger ? 20 : selltrigger ? 20 : 100

bgcolor(bgcolor, 30)

NUM = IntBuy + IntSB + IntSell + IntSS
linecolor = color.orange
plot(NUM, color=linecolor, linewidth=2)

alertcondition(NUM > 0.5, title="Buy Signal", message="Buy Alert")
alertcondition(NUM < -0.5, title="Sell Signal", message="Sell Alert")

alertcondition(NUM == 0.5, title="Buy Setup", message="Buy Setup")
alertcondition(NUM == -0.5, title="Sell Setup", message="Sell Setup")

//Switch on for strategy moves

if(inDateRange and buytrigger)
    strategy.exit("SHORT", "SHORT_SL", comment="Short_Exit")
    strategy.entry("LONG", strategy.long, comment="")
if(inDateRange and selltrigger)
    strategy.exit("LONG", "LONG_SL", comment="Long_Exit")
    strategy.entry("SHORT", strategy.short, comment="")
if (not inDateRange)
    strategy.close_all()

// plotshape(SC and not up, color = color.yellow, style = shape.triangleup, location = location.belowbar, size = size.auto, transp = 0, title = "Setup to Buy")
// plotshape(TC and up, color = color.green, style = shape.triangleup, location = location.belowbar, size = size.auto, title = "Trigger to Buy")
// plotshape(SC and up, color = color.yellow, style = shape.triangledown, location = location.abovebar, size = size.auto, transp = 0, title = "Setup to Sell")
// plotshape(TC and not up, color = color.red, style = shape.triangledown, location = location.abovebar, size = size.auto, title = "Trigger to Sell")


더 많은