사용자 정의 상향 돌파 전략


생성 날짜: 2024-01-08 10:32:25 마지막으로 수정됨: 2024-01-08 10:32:25
복사: 0 클릭수: 629
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

사용자 정의 상향 돌파 전략

개요

사용자 정의 상향 돌파 전략은 가격 트렌드 판단에 기반한 양적 거래 전략이다. 이 전략은 지정된 주기 내의 K선 비율을 계산하여 시장이 현재 지속적인 상승 상태에 있는지 판단한다. K선 비율이 사용자가 설정한 상위 한계보다 높을 때 전략 판단 현재 상승 상태에 있으며, 이 때 더 많이 한다. K선 비율이 사용자가 설정한 하위 한계보다 낮을 때 전략 판단 현재 하락 상태에 있으며, 이 때 공백한다.

전략 원칙

이 전략의 핵심 지표는 K 라인 비율이다. K 라인 비율은 낮은 시점부터 상장하고, 상장 가격이 상장 가격보다 높은 K 라인을 나타내고, 이 기간 내에 가격이 상승한 것을 나타낸다. 전략은 통계 사용자에 의해 지정된 이전 기간 동안, K 라인의 수를 K 라인 비율로 나타낸다. 상한보다 큰 비율이 현재 지속적인 상향상황에 있다고 판단할 때, 이 때 더 많이 한다.

예: 사용자 설정 사이클은 20이고, 상한은 70이고, 하한은 30이다. 정책은 최근 20개의 K선으로 회귀하고, 그 중 16개가 K선으로 정진한 경우, 1620=80%이다. 이 때 사용자 설정 상한 70보다 높으면, 여러 작업을 수행한다.

우위 분석

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

  1. 전략은 간단하고 직관적이며 이해하기 쉽습니다.
  2. 하지만, 이 지표는 단지 하나의 지표로만 이루어져 있어서, 과대 최적화 위험은 낮아집니다.
  3. 사용자에 맞게 다양한 품종에 맞게 사용자 정의할 수 있습니다.
  4. 내장된 손해 방지 기능으로 큰 손실을 방지할 수 있습니다.
  5. 상장관리자는 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가 상장관리자가

위험 분석

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

  1. 한 가지 지표만 사용해도 잘못된 신호가 나올 수 있습니다.
  2. 지표의 매개 변수가 너무 최적화 될 수 있고, 실디 효과는 크게 달라질 수 있다.
  3. 현황이 급격하게 변동할 때, 정지값이 깨져 손실이 발생할 수 있습니다.
  4. 이 경우, 상장 개설 기능이 손실을 증가시킬 수 있습니다.
  5. 효능과 품종의 연관성이 높기 때문에 개별적으로 테스트를 해야 한다.

위험성을 줄이기 위해 다음과 같은 부분에서 최적화할 수 있습니다.

  1. 필터링 조건을 추가하여 잘못된 신호를 방지합니다.
  2. 단편적 손실을 줄이기 위해 손해 방지 전략을 최적화하십시오.
  3. 단편적 손실을 평가하고 통제합니다.
  4. 다른 품종에서의 테스트 효과.

최적화 방향

이 전략은 다음과 같은 방향으로 최적화될 수 있습니다.

  1. 가격 합리성 등의 보조 판단 지표를 늘리고, 잘못된 신호를 피하십시오.
  2. 이동 상쇄, 진동 상쇄 등을 고려할 수 있는 최적화된 상쇄 방식
  3. 부린 라인을 뚫고 다시 입점하는 것과 같은 개장 필터 조건을 추가합니다.
  4. 다양한 K선변수들의 다양한 품종에 대한 적합성을 테스트하는 방법
  5. 최대 인출을 평가하고 단독 손실 규모를 통제합니다.

요약하다

사용자 정의 상향 돌파 전략 전체적인 아이디어는 명확하고 간단하며, 통계적으로 K선으로 계속되는 상승 또는 하락 상태를 판단하고, 간단한 지표를 사용하여 트렌드를 캡처한다. 이 전략은 이해하기 쉽고, 사용자 친화적이며, 양적 거래의 초보자 연습에 적합하다. 그러나 단일 지표 및 매개 변수 설정에만 의존하는 수익의 일정 변동성이 있으며, 전략의 위험을 위해 계속 최적화하여 더 많은 시장에서 안정적으로 수익을 올릴 수 있습니다.

전략 소스 코드
/*backtest
start: 2023-12-31 00:00:00
end: 2024-01-04 00:00:00
period: 1m
basePeriod: 1m
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/
// © ZenAndTheArtOfTrading 
// © TweakerID

// Based on the calculations by ZenAndTheArtOfTrading, I added stop loss, take profit and reverse line codes.
// The Positive Bars % calculates the number of green (positive) bars, relative to a lookback period, defined 
// by the user. If the percentage is low, it means that there was a bigger number of red candles in the 
// lookback period. The strategy goes long when the percentage is high and short when it's low, although
// this logic can be reversed with positive results on different time frames.

//@version=4
strategy("Positive Bars % Strat", 
     overlay=true, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100, 
     initial_capital=10000, 
     commission_value=0.04, 
     calc_on_every_tick=false, 
     slippage=0)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))

/////////////////////// STRATEGY INPUTS ////////////////////////////////////////
title1=input(true, "-----------------Strategy Inputs-------------------")  

lookback = input(title="Lookback", type=input.integer, defval=13)
upperLimit = input(title="Upper Limit", type=input.integer, defval=70)
lowerLimit = input(title="Lower Limit", type=input.integer, defval=30)

/////////////////////// BACKTESTER /////////////////////////////////////////////
title2=input(true, "-----------------General Inputs-------------------")  

// Backtester General Inputs
i_SL=input(true, title="Use Stop Loss and Take Profit")
i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])
i_SPL=input(defval=10, title="Swing Point Lookback")
i_PercIncrement=input(defval=2, step=.1, title="Swing Point SL Perc Increment")*0.01
i_ATR = input(14, title="ATR Length")
i_ATRMult = input(10, step=.1, title="ATR Multiple")
i_TPRRR = input(1.6, step=.1, title="Take Profit Risk Reward Ratio")

// Bought and Sold Boolean Signal
bought = strategy.position_size > strategy.position_size[1] 
 or strategy.position_size < strategy.position_size[1]

// Price Action Stop and Take Profit
LL=(lowest(i_SPL))*(1-i_PercIncrement)
HH=(highest(i_SPL))*(1+i_PercIncrement)
LL_price = valuewhen(bought, LL, 0)
HH_price = valuewhen(bought, HH, 0)
entry_LL_price = strategy.position_size > 0 ? LL_price : na 
entry_HH_price = strategy.position_size < 0 ? HH_price : na 
tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR
stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR

// ATR Stop
ATR=atr(i_ATR)*i_ATRMult
ATRLong = ohlc4 - ATR
ATRShort = ohlc4 + ATR
ATRLongStop = valuewhen(bought, ATRLong, 0)
ATRShortStop = valuewhen(bought, ATRShort, 0)
LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na 
ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na 
ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR
ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR

// Strategy Stop
float LongStop = na
float ShortStop = na
float StratTP = na
float StratSTP = na

/////////////////////// STRATEGY LOGIC /////////////////////////////////////////

//Calculations
positiveBars = 0
for i = (lookback - 1) to 0
    if close[i] > open[i]
        positiveBars := positiveBars + 1
positiveBarsPercent = (positiveBars / lookback) * 100

BUY=positiveBarsPercent >= upperLimit
SELL=positiveBarsPercent <= lowerLimit

//Trading Inputs
DPR=input(true, "Allow Direct Position Reverse")
reverse=input(false, "Reverse Trades")

// Entries
if reverse
    if not DPR
        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)
    else     
        strategy.entry("long", strategy.long, when=SELL)
        strategy.entry("short", strategy.short, when=BUY)
else
    if not DPR 
        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)
    else
        strategy.entry("long", strategy.long, when=BUY)
        strategy.entry("short", strategy.short, when=SELL)


SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop
SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop
TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP
STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP

strategy.exit("TP & SL", "long", limit=TP, stop=SL, when=i_SL)
strategy.exit("TP & SL", "short", limit=STP, stop=SSL, when=i_SL)

/////////////////////// PLOTS //////////////////////////////////////////////////

plot(i_SL and strategy.position_size > 0 ? SL : na , title='SL', style=plot.style_cross, color=color.red)
plot(i_SL and strategy.position_size < 0 ? SSL : na , title='SSL', style=plot.style_cross, color=color.red)
plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green)
plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green)
// Draw price action setup arrows
plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, 
 color=color.green, title="Bullish Setup", size=size.auto)
plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, 
 color=color.red, title="Bearish Setup", size=size.auto)