손절매 및 이익실현 추적을 사용한 ABCD 패턴 기반의 새로운 양적 거래 전략


생성 날짜: 2024-02-19 11:22:48 마지막으로 수정됨: 2024-02-19 11:25:29
복사: 0 클릭수: 795
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

손절매 및 이익실현 추적을 사용한 ABCD 패턴 기반의 새로운 양적 거래 전략

전략 개요

이 전략의 이름은 ?? 최우수 ABCD 형태 거래 전략 ?? 이다. 그것은 명확한 ABCD 가격 형태 모델을 기반으로 거래 작업을 수행하는 양적 전략이다. 주요 아이디어는 완전한 ABCD 형태 모델을 확인 한 후 형태의 방향에 따라 더 많은 공백을하고, 상쇄 및 중지 추적을 설정하여 위치를 관리하는 것이다.

2. 전략 원칙

  1. 브린 보조 판단법을 사용하여 가격의 상하 분형점을 식별하여 가격의 지그자그 곡선을 얻는다.

  2. 지그자그 곡선에서 완전한 ABCD 형태 모델을 식별하기 위해서는 A, B, C, D의 네 점이 일정 비율 관계를 충족해야 한다. 적합한 ABCD 형태를 식별한 후, 더하거나 공백을 해야 한다.

  3. 더 많은 코스카이드를 취한 후, 손실 추적을 설정하여 위험을 제어하십시오. 중지 시 고정된 스톱을 사용하여, 수익이 일정 비율을 달성 한 후 이동 스톱으로 전환하여 수익의 일부를 잠금합니다.

  4. 마찬가지로, 상쇄선에도 추적 설정이 이루어져 충분한 수익을 얻은 후에 적시에 상쇄를 하고 수익이 회전되는 것을 방지한다. 상쇄 추적도 두 단계로 나뉘어, 먼저 고정 상쇄를 사용하여 수익을 얻으며, 그 다음에는 이동 상쇄로 이동하여 가격을 추적한다.

  5. 가격이 이동 중지 또는 정지를 촉발할 때, 포지션을 평행하여 거래 순환을 완료하십시오.

세, 전략적 장점 분석

  1. 브린 보조 판단법을 사용하여 ZigZag 곡선을 식별하여 전통적인 ZigZag 곡선의 회귀 문제를 피하고 거래 신호를 더 신뢰할 수 있습니다.

  2. ABCD 형태 거래 모델은 성숙하고 안정적이며 거래 기회가 풍부하다. ABCD 형태 방향이 명확하여 시장 진입 방향을 쉽게 판단할 수 있다.

  3. 2단계 스톱 트래킹을 설정하면 위험을 더 잘 제어하고 수익을 얻을 수 있습니다. 모바일 스톱은 전략을 더 유연하게 조정할 수 있습니다.

  4. 전략 파라미터가 합리적으로 설계되어 있으며, 스톱 스톱 퍼센티지, 모바일 스타트 퍼센티지는 사용자 정의가 가능하며, 사용에 있어 유연하다.

  5. 이 전략은 외환, 암호화폐, 주식 지수 등 모든 종류에 적용될 수 있다.

4 전략적 위험 분석

  1. ABCD 형태는 명확하지만 거래 기회는 상대적으로 제한적이며 충분한 거래 빈도를 보장할 수 없습니다.

  2. 진동상태에서, 스로퍼가 자주 작동되는 경우가 있을 수 있다. 이 경우 스로퍼 범위를 넓히기 위해 파라미터를 적절히 조정할 필요가 있다.

  3. 거래 품종 자체의 유동성에 주의를 기울여야 한다. 유동성이 낮은 지표의 경우, 스톱 스톱을 정확하게 실행하기 어렵다.

  4. 전략은 거래 비용에 민감하며, 수수료가 저렴한 브로커와 계정을 선택해야 한다.

  5. 일부 파라미터는 계속 최적화할 수 있으며, 예를 들어, 이동 스톱 및 스톱의 시작 조건은 더 많은 값을 테스트하여 최적의 지점을 찾을 수 있다.

다섯째, 전략적 최적화

  1. 다른 지표와 결합하여 더 많은 필터링 조건을 설정하여 일부 HW 형태를 피할 수 있습니다. 이것은 유효하지 않은 거래의 발생을 줄일 수 있습니다.

  2. 시장의 3단계 구조에 대한 판단을 높이고, 3단계 상황에서만 거래 기회를 찾습니다. 이것은 전략의 승률을 높일 수 있습니다.

  3. 초기 자본 규모를 최적화하여 최적의 초기 자본 수준을 찾습니다. 너무 큰 너무 작은 것은 최적의 수익률을 얻는 데 도움이되지 않습니다.

  4. 샘플 외의 데이터를 테스트하여 매개 변수의 강도를 검증할 수 있다. 이는 전략의 장기적 안정성에 필수적이다.

  5. 이동식 스톱/ 시작 조건과 슬라이드 크기를 계속 최적화하여 전략 실행 효율성을 높여라. SETTINGS 최적화는 끝이 없다.

6 전략 요약

이 전략은 주로 ABCD 가격 형태를 판단하고 시장에 진입한다. 위험과 수익을 관리하기 위해 2 단계의 스톱 스 추적을 설정한다. 전략은 성숙하고 안정적이지만 거래 빈도는 낮을 수 있다. 필터링 조건을 추가하여 더 효율적인 거래 기회를 얻을 수 있다. 또한, 변수 및 자본 규모를 계속 최적화하면 전략의 안정적인 수익성을 더욱 향상시킬 수 있다.

전략 소스 코드
/*backtest
start: 2024-02-11 00:00:00
end: 2024-02-18 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// @version=4
// @author=Daveatt - BEST

// ABCD Pattern Strat

StrategyName        = "BEST ABCD Pattern Strategy (Trailing SL + TP)"
ShortStrategyName   = "BEST ABCD Strategy (Trailing)" 

strategy(title=StrategyName, shorttitle=ShortStrategyName, overlay=true )

filterBW = input(false, title="filter Bill Williams Fractals?")

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////// UTILITIES ///////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

//  ||-----------------------------------------------------------------------------------------------------||
//  ||---   Fractal Recognition Functions:  ---------------------------------------------------------------||
isRegularFractal(mode, _high, _low) =>
    ret = mode == 1 ? _high[4] < _high[3] and _high[3] < _high[2] and _high[2] > _high[1] and _high[1] > _high[0] :
     mode == -1 ? _low[4] > _low[3] and _low[3] > _low[2] and _low[2] < _low[1] and _low[1] < _low[0] : false

isBWFractal(mode, _high, _low) =>
    ret = mode == 1 ? _high[4] < _high[2] and _high[3] <= _high[2] and _high[2] >= _high[1] and _high[2] > _high[0] :
     mode == -1 ? _low[4] > _low[2] and _low[3] >= _low[2] and _low[2] <= _low[1] and _low[2] < _low[0] : false

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////////////////////////////// ABCD PATTERN ///////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

f_abcd()=>

    _r = timeframe.period
    _g = barmerge.gaps_off
    _l = barmerge.lookahead_on

    _high = high
    _low = low

    filteredtopf = filterBW ? isRegularFractal(1, _high, _low) : isBWFractal(1, _high, _low)
    filteredbotf = filterBW ? isRegularFractal(-1, _high, _low) : isBWFractal(-1, _high, _low)

    //  ||---   ZigZag:
    istop = filteredtopf
    isbot = filteredbotf
    topcount = barssince(istop)
    botcount = barssince(isbot)

    zigzag = (istop and topcount[1] > botcount[1] ? _high[2] :
     isbot and topcount[1] < botcount[1] ? _low[2] : na)

    x = valuewhen(zigzag, zigzag, 4) 
    a = valuewhen(zigzag, zigzag, 3) 
    b = valuewhen(zigzag, zigzag, 2) 
    c = valuewhen(zigzag, zigzag, 1) 
    d = valuewhen(zigzag, zigzag, 0)

    xab = (abs(b-a)/abs(x-a))
    xad = (abs(a-d)/abs(x-a))
    abc = (abs(b-c)/abs(a-b))
    bcd = (abs(c-d)/abs(b-c))

    // ABCD Part
    _abc = abc >= 0.382 and abc <= 0.886
    _bcd = bcd >= 1.13 and bcd <= 2.618
    
    _bull_abcd = _abc and _bcd and d < c 
    _bear_abcd = _abc and _bcd and d > c

    _bull   = _bull_abcd and not _bull_abcd[1]
    _bear   = _bear_abcd and not _bear_abcd[1]

    [_bull, _bear, zigzag]

lapos_x = timenow + round(change(time)*12)

[isLong, isShort, zigzag]  = f_abcd()

plot(zigzag, title= 'ZigZag', color=color.black, offset=-2)
plotshape(isLong, style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), size=size.normal, text="ABCD", textcolor=color.white)
plotshape(isShort, style=shape.labeldown, location=location.abovebar, color=color.new(color.maroon, 0), size=size.normal, text="ABCD", textcolor=color.white)


long_entry_price    = valuewhen(isLong, close, 0)
short_entry_price   = valuewhen(isShort, close, 0)

sinceNUP = barssince(isLong)
sinceNDN = barssince(isShort)

buy_trend   = sinceNDN > sinceNUP
sell_trend  = sinceNDN < sinceNUP

change_trend = (buy_trend and sell_trend[1]) or (sell_trend and buy_trend[1])

entry_price  = buy_trend ? long_entry_price : short_entry_price

///////////////////////////////
//======[ Trailing STOP ]======//
///////////////////////////////

// use SL?
useSL = input(true, "Use stop Loss")
// Configure trail stop level with input
StopTrailPerc = input(title="Trail Loss (%)", type=input.float, minval=0.0, step=0.1, defval=3) * 0.01
// Will trigger the take profit trailing once reached
use_SL_Trigger = input(true, "Use stop Loss Trigger")
StopTrailTrigger   = input(2.0, "SL Trigger (%)",minval=0,step=0.5,type=input.float) * 0.01


StopLossPriceTrigger = 0.0
StopLossPriceTrigger := if (use_SL_Trigger)
    if buy_trend
        entry_price * (1 + StopTrailTrigger) 
    else
        entry_price * (1 - StopTrailTrigger)
else
    -1


var SL_Trigger_Long_HIT = false
SL_Trigger_Long_HIT := useSL and use_SL_Trigger and buy_trend and high >= StopLossPriceTrigger
 ? true : SL_Trigger_Long_HIT[1]


var SL_Trigger_Short_HIT = false
SL_Trigger_Short_HIT := useSL and use_SL_Trigger and sell_trend and low <= StopLossPriceTrigger
 ? true : SL_Trigger_Short_HIT[1]


display_long_SL_trigger     = useSL and buy_trend  and use_SL_Trigger 
 and SL_Trigger_Long_HIT == false and StopLossPriceTrigger != -1
display_short_SL_trigger    = useSL and sell_trend and use_SL_Trigger 
 and SL_Trigger_Short_HIT == false and StopLossPriceTrigger != -1
display_SL_trigger          = display_long_SL_trigger or display_short_SL_trigger

plot(display_SL_trigger ? StopLossPriceTrigger : na, title='SLPriceTrigger', transp=0, 
 color=color.maroon, style=plot.style_circles, linewidth=3)


// Determine trail stop loss prices
longStopPrice = 0.0, shortStopPrice = 0.0

longStopPrice := if useSL and buy_trend
    stopValue = low * (1 - StopTrailPerc)
    max(stopValue, longStopPrice[1])
else
    0

shortStopPrice := if useSL and sell_trend
    stopValue = high * (1 + StopTrailPerc)
    min(stopValue, shortStopPrice[1])
else
    999999

//////////////////////////////////////////////////////////////////////////////////////////
//*** STOP LOSS HIT CONDITIONS  ***//
//////////////////////////////////////////////////////////////////////////////////////////

cond_long_stop_loss_hit  = useSL and buy_trend and crossunder(low, longStopPrice[1]) 
 and (SL_Trigger_Long_HIT or use_SL_Trigger == false)
cond_short_stop_loss_hit = useSL and sell_trend and crossover(high, shortStopPrice[1]) 
 and (SL_Trigger_Short_HIT or use_SL_Trigger == false)


// Plot stop loss values for confirmation
plot(series=useSL and buy_trend and low >= longStopPrice 
 and (SL_Trigger_Long_HIT or use_SL_Trigger == false)
 ? longStopPrice : na,
 color=color.fuchsia, style=plot.style_cross,
 linewidth=2, title="Long Trail Stop")

plot(series=useSL and sell_trend and high <= shortStopPrice 
 and (SL_Trigger_Short_HIT or use_SL_Trigger == false)
 ? shortStopPrice : na,
 color=color.fuchsia, style=plot.style_cross,
 linewidth=2, title="Short Trail Stop")


///////////////////////////////
//======[ Take Profit ]======//
///////////////////////////////

// Use TP?
useTP = input(true, "Use take profit")
// TP trailing
ProfitTrailPerc     = input(1.0, "Trailing Profit (%)",minval=0,step=0.5,type=input.float) * 0.01

use_TP_Trigger = input(true, "Use Take Profit Trigger")
// Will trigger the take profit trailing once reached
takeProfitTrigger   = input(3.0, "Take Profit Trigger (%)",minval=0,step=0.5,type=input.float) * 0.01


// ttp := ttp>tp ? tp : ttp

takeprofitPriceTrigger = 0.0
takeprofitPriceTrigger := if (use_TP_Trigger)
    if (buy_trend)
        entry_price * (1 + takeProfitTrigger) 
    else
        entry_price * (1 - takeProfitTrigger)
else
    -1

//plot(entry_price, title='entry_price', transp=100)

var TP_Trigger_Long_HIT = false
TP_Trigger_Long_HIT := useTP and use_TP_Trigger and buy_trend and high >= takeprofitPriceTrigger
 ? true : TP_Trigger_Long_HIT[1]


var TP_Trigger_Short_HIT = false
TP_Trigger_Short_HIT := useTP and use_TP_Trigger and sell_trend and low <= takeprofitPriceTrigger
 ? true : TP_Trigger_Short_HIT[1]


display_long_TP_trigger     = useTP and buy_trend  and TP_Trigger_Long_HIT == false 
 and takeprofitPriceTrigger != -1
display_short_TP_trigger    = useTP and sell_trend and TP_Trigger_Short_HIT == false 
 and takeprofitPriceTrigger != -1
display_TP_trigger          = display_long_TP_trigger or display_short_TP_trigger


//🔷🔷🔷
// @hugo: Will display the TP trigger as long as not hit
// once the TP trigger is hit, the TP trailing will activate
plot(display_TP_trigger ? takeprofitPriceTrigger : na, title='takeprofitPriceTrigger', transp=0, color=color.orange, 
 style=plot.style_cross, linewidth=3)

longTrailTP= 0.0, shortTrailTP = 0.0

// Trailing Profit
// Start trailing once trigger is reached
longTrailTP := if useTP and buy_trend 
    tpValue = high * (1 + ProfitTrailPerc)
    max(tpValue, longTrailTP[1])
else
    0

shortTrailTP := if useTP and sell_trend
    tpValue = low * (1 - ProfitTrailPerc)
    min(tpValue, shortTrailTP[1])
else
    999999

//plot(longTrailTP, title='debug longTrailTP', transp=100)
//plot(shortTrailTP, title='debug shortTrailTP', transp=100)

//////////////////////////////////////////////////////////////////////////////////////////
//*** TRAILING TAKE PROFIT HIT CONDITIONS TO BE USED IN ALERTS  ***//
//////////////////////////////////////////////////////////////////////////////////////////


//🔷🔷🔷
// @hugo: I use crossover/crossunder for the alerts to trigger the events only once
cond_long_trail_tp_hit      = useTP and buy_trend   and crossover(high, longTrailTP[1]) 
 and (TP_Trigger_Long_HIT or use_TP_Trigger == false)
cond_short_trail_tp_hit     = useTP and sell_trend  and crossunder(low, shortTrailTP[1]) 
 and (TP_Trigger_Short_HIT or use_TP_Trigger == false)
// 🔷🔷🔷


// Plot take profits values for confirmation
// Display the trailing TP until not hit
plot(series= useTP and buy_trend and high <= longTrailTP and 
 (TP_Trigger_Long_HIT or use_TP_Trigger == false) ? longTrailTP : na,
 color=color.aqua, style=plot.style_circles,
 linewidth=2, title="Long Trail TP")

plot(series= useTP and sell_trend and low >= shortTrailTP and 
 (TP_Trigger_Short_HIT or use_TP_Trigger == false) ? shortTrailTP : na,
 color=color.aqua, style=plot.style_circles,
 linewidth=2, title="Short Trail TP")

close_long  = cond_long_trail_tp_hit or cond_long_stop_loss_hit
close_short = cond_short_trail_tp_hit or cond_short_stop_loss_hit


strategy.entry("Long", 1, when=isLong)
strategy.close("Long", when=close_long)

strategy.entry("Short", 0,  when=isShort)
strategy.close("Short", when=close_short)

if change_trend
    SL_Trigger_Long_HIT := false
    SL_Trigger_Short_HIT := false
    TP_Trigger_Long_HIT := false
    TP_Trigger_Short_HIT := false