CVD 디버전스 양적 거래 전략

저자:차오장, 날짜: 2024-03-15 16:47:47
태그:

img

전략 개요: CVD 분산 양적 거래 전략은 잠재적인 트렌드 반전 신호를 캡처하기 위해 CVD 지표와 가격 사이의 분리를 활용합니다. 전략은 CVD 지표를 계산하고 가격과 비교하여 상승 또는 하락 분리가 형성되는지 결정합니다. 분산 신호가 감지되면 전략은 긴 또는 짧은 위치를 여는 것입니다. 또한 리싱 스톱 로스와 고정 비율의 이익을 사용하여 위험을 제어하고 이익을 잠금합니다. 전략은 여러 포지션으로 피라미딩을 지원합니다.

전략 원칙:

  1. CVD 지표 계산: CVD 지표와 그 이동 평균을 상승 및 하락 부피에 기초하여 계산합니다.
  2. 오차를 식별: CVD 지표의 최고와 하락을 가격의 최고와 하락과 비교하여 오차가 형성되었는지 여부를 결정합니다.
    • 규칙적인 상승성 오차: 가격은 낮은 하위치를 만들지만 CVD는 높은 하위치를 형성합니다.
    • 숨겨진 상승성 오차: 가격이 더 높은 하위치를 만들지만 CVD는 더 낮은 하위치를 형성합니다.
    • 규칙적인 하향 분차: 가격은 높은 최고치를 만들지만 CVD는 낮은 최고치를 형성합니다.
    • 숨겨진 하향 분차: 가격이 낮은 최고치를 만들지만 CVD는 더 높은 최고치를 형성합니다.
  3. 오픈 포지션: 디버전스 신호가 확인되면 디버전스 유형에 따라 긴 또는 짧은 포지션을 개척합니다.
  4. 스톱 로스 및 이윤 취득: 후속 스톱 로스 및 고정 비율의 이윤 취득을 사용하십시오. 스톱 로스 가격은 엔트리 가격을 스톱 로스 비율로 곱하여 계산되며, 이윤 취득 가격은 엔트리 가격을 엔트리 이익 비율로 곱하여 계산됩니다.
  5. 피라미딩: 전략은 피라미딩을 위해 최대 3 개의 위치를 허용합니다.

전략적 장점:

  1. 트렌드 반전 신호: CVD 분리는 트렌드 반전 기회를 포착하는 데 도움이 될 수있는 효과적인 트렌드 반전 신호입니다.
  2. 트렌드 지속 신호: 숨겨진 오차는 트렌드 지속 신호로 작용하여 트렌드 도중 전략이 올바른 방향을 유지하는 데 도움이 될 수 있습니다.
  3. 리스크 관리: 후속 스톱 로스 및 일정한 비율의 수익을 사용함으로써 리스크가 효과적으로 관리됩니다.
  4. 피라미딩: 피라미딩을 위한 여러 포지션을 허용하면 트렌딩 시장에서 더 나은 자본을 가능하게 합니다.

전략 위험:

  1. 신호 유효성: 이각 신호는 완전히 신뢰할 수 없으며 때때로 잘못된 신호가 발생할 수 있습니다.
  2. 매개 변수 구성: 전략 결과는 매개 변수 설정에 민감하며, 다른 매개 변수가 다른 결과를 초래할 수 있습니다.
  3. 스톱 로스 미끄러짐: 변동성 있는 시장에서 스톱 로스 오더는 미리 정의된 가격으로 채우지 않을 수 있으며, 추가적인 위험을 초래합니다.
  4. 거래 비용: 포지션의 빈번한 개점과 폐쇄는 높은 거래 비용을 초래할 수 있으며 전략 수익성에 영향을 줄 수 있습니다.

최적화 방향:

  1. 동적 매개 변수 최적화: 신호 유효성을 향상시키기 위해 다른 시장 조건에 적응 가능한 매개 변수를 사용합니다.
  2. 다른 지표와 결합: 신호 신뢰성을 높이기 위해 RSI, MACD 등과 같은 다른 기술 지표와 통합합니다.
  3. 개선된 스톱 로스 및 수익을 취하라: 트래일링 스톱 로스 또는 변동성 기반 스톱 로스와 같은 더 고급 스톱 로스 및 수익 전략을 채택하라.
  4. 포지션 크기: 시장 변동성, 계좌 자본 등에 따라 포지션 크기를 동적으로 조정합니다.

결론: CVD 디버전스 양적 거래 전략은 CVD 지표와 가격 사이의 차이를 파악함으로써 잠재적 인 트렌드 역전 기회를 식별하는 것을 목표로합니다. 리스크를 관리하기 위해 트레일링 스톱 로스와 고정 비율의 수익을 취합니다. 전략의 주요 장점은 트렌드 역전 및 지속 신호를 효과적으로 캡처하고 피라미딩을 통해 트렌드 시장을 더 잘 활용하는 능력에 있습니다. 그러나 전략은 또한 신호 유효성, 매개 변수 구성, 스톱 로스 미끄러움 및 거래 비용과 같은 위험에 직면합니다. 향후 개선은 동적 매개 변수 최적화, 다른 지표와 결합, 향상된 스톱 로스 및 수익 취득 메커니즘 및 위치 사이징 관리로 이루어질 수 있습니다. 전반적으로, CVD 디버전스 양적 거래 전략은 트렌드 기회를 관리하는 동안 위험을 캡처하는 것을 목표로하는 거래자에게 적합한 효과적이고 최적화 가능한 트렌드 추종 전략입니다.


/*backtest
start: 2023-03-09 00:00:00
end: 2024-03-14 00:00:00
period: 1d
basePeriod: 1h
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/

//@version=5
//@ mmattman

//Thank you to @ contrerae and Tradingview each for parts of the code to make 
//this indicator and matching strategy and also theCrypster for the clean concise TP/SL code.

// indicator(title="CVD Divergence Indicator 1", shorttitle='CVD Div1', format=format.price, timeframe="", timeframe_gaps=true)

strategy("CVD Divergence Strategy.1.mm", shorttitle = 'CVD Div Str 1', overlay=false)


//..................................................................................................................
// Inputs
periodMa = input.int(title='MA Length', minval=1, defval=20)
plotMa = input(title='Plot MA?', defval=false)

// Calculations (Bull & Bear Balance Indicator by Vadim Gimelfarb)
iff_1 = close[1] < open ? math.max(high - close[1], close - low) : math.max(high - open, close - low)
iff_2 = close[1] > open ? high - low : math.max(open - close[1], high - low)
iff_3 = close[1] < open ? math.max(high - close[1], close - low) : high - open
iff_4 = close[1] > open ? high - low : math.max(open - close[1], high - low)
iff_5 = close[1] < open ? math.max(open - close[1], high - low) : high - low
iff_6 = close[1] > open ? math.max(high - open, close - low) : iff_5
iff_7 = high - close < close - low ? iff_4 : iff_6
iff_8 = high - close > close - low ? iff_3 : iff_7
iff_9 = close > open ? iff_2 : iff_8
bullPower = close < open ? iff_1 : iff_9
iff_10 = close[1] > open ? math.max(close[1] - open, high - low) : high - low
iff_11 = close[1] > open ? math.max(close[1] - low, high - close) : math.max(open - low, high - close)
iff_12 = close[1] > open ? math.max(close[1] - open, high - low) : high - low
iff_13 = close[1] > open ? math.max(close[1] - low, high - close) : open - low
iff_14 = close[1] < open ? math.max(open - low, high - close) : high - low
iff_15 = close[1] > open ? math.max(close[1] - open, high - low) : iff_14
iff_16 = high - close < close - low ? iff_13 : iff_15
iff_17 = high - close > close - low ? iff_12 : iff_16
iff_18 = close > open ? iff_11 : iff_17
bearPower = close < open ? iff_10 : iff_18

// Calculations (Bull & Bear Pressure Volume)
bullVolume = bullPower / (bullPower + bearPower) * volume
bearVolume = bearPower / (bullPower + bearPower) * volume

// Calculations Delta
delta = bullVolume - bearVolume
cvd = ta.cum(delta)
cvdMa = ta.sma(cvd, periodMa)

// Plotting
customColor = cvd > cvdMa ? color.new(color.teal, 50) : color.new(color.red, 50)
plotRef1 = plot(cvd, style=plot.style_line, linewidth=1, color=color.new(color.yellow, 0), title='CVD')
plotRef2 = plot(plotMa ? cvdMa : na, style=plot.style_line, linewidth=1, color=color.new(color.white, 0), title='CVD MA')
fill(plotRef1, plotRef2, color=customColor)
//..................................................................................................................


// len = input.int(title="RSI Period", minval=1, defval=14)
// src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=3)
lbL = input(title="Pivot Lookback Left", defval=7)
rangeUpper = input(title="Max of Lookback Range", defval=60)
rangeLower = input(title="Min of Lookback Range", defval=5)
plotBull = input(title="Plot Bullish", defval=true)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=true)
plotBear = input(title="Plot Bearish", defval=true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=true)
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
osc = cvd

// plot(osc, title="CVD", linewidth=2, color=#2962FF)
// hline(50, title="Middle Line", color=#787B86, linestyle=hline.style_dotted)
// obLevel = hline(70, title="Overbought", color=#787B86, linestyle=hline.style_dotted)
// osLevel = hline(30, title="Oversold", color=#787B86, linestyle=hline.style_dotted)
// fill(obLevel, osLevel, title="Background", color=color.rgb(33, 150, 243, 90))

plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
	bars = ta.barssince(cond == true)
	rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low

oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Lower Low

priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCondAlert = priceLL and oscHL and plFound
bullCond = plotBull and bullCondAlert

plot(
     plFound ? osc[lbR] : na,
     offset=-lbR,
     title="Regular Bullish",
     linewidth=2,
     color=(bullCond ? bullColor : noneColor)
     )

plotshape(
	 bullCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Regular Bullish Label",
	 text=" Bull ",
	 style=shape.labelup,
	 location=location.absolute,
	 color=bullColor,
	 textcolor=textColor
	 )

//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low

oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Higher Low

priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCondAlert = priceHL and oscLL and plFound
hiddenBullCond = plotHiddenBull and hiddenBullCondAlert

plot(
	 plFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bullish",
	 linewidth=2,
	 color=(hiddenBullCond ? hiddenBullColor : noneColor)
	 )

plotshape(
	 hiddenBullCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bullish Label",
	 text=" H Bull ",
	 style=shape.labelup,
	 location=location.absolute,
	 color=bullColor,
	 textcolor=textColor
	 )

//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High

oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Higher High

priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)

bearCondAlert = priceHH and oscLH and phFound
bearCond = plotBear and bearCondAlert

plot(
	 phFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Regular Bearish",
	 linewidth=2,
	 color=(bearCond ? bearColor : noneColor)
	 )

plotshape(
	 bearCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Regular Bearish Label",
	 text=" Bear ",
	 style=shape.labeldown,
	 location=location.absolute,
	 color=bearColor,
	 textcolor=textColor
	 )

//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High

oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Lower High

priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)

hiddenBearCondAlert = priceLH and oscHH and phFound
hiddenBearCond = plotHiddenBear and hiddenBearCondAlert

plot(
	 phFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bearish",
	 linewidth=2,
	 color=(hiddenBearCond ? hiddenBearColor : noneColor)
	 )

plotshape(
	 hiddenBearCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bearish Label",
	 text=" H Bear ",
	 style=shape.labeldown,
	 location=location.absolute,
	 color=bearColor,
	 textcolor=textColor
	 )

// alertcondition(bullCondAlert, title='Regular Bullish CVD Divergence', message="Found a new Regular Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar")
// alertcondition(hiddenBullCondAlert, title='Hidden Bullish CVD Divergence', message='Found a new Hidden Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')
// alertcondition(bearCondAlert, title='Regular Bearish CVD Divergence', message='Found a new Regular Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')
// alertcondition(hiddenBearCondAlert, title='Hidden Bearisn CVD Divergence', message='Found a new Hidden Bearisn Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')

le = bullCondAlert or hiddenBullCondAlert

se = bearCondAlert or hiddenBearCondAlert

ltp = se

stp = le

// Check if the entry conditions for a long position are met
if (le) //and (close > ema200)
    strategy.entry("Long", strategy.long, comment="EL")

 // Check if the entry conditions for a short position are met
if (se) //and (close < ema200)
    strategy.entry("Short", strategy.short, comment="ES")

// Close long position if exit condition is met
if (ltp) // or (close < ema200)
    strategy.close("Long", comment="XL")

    // Close short position if exit condition is met
if (stp) //or (close > ema200)
    strategy.close("Short", comment="XS")


// The Fixed Percent Stop Loss Code
// User Options to Change Inputs (%)
stopPer = input.float(5.0, title='Stop Loss %') / 100
takePer = input.float(10.0, title='Take Profit %') / 100

// Determine where you've entered and in what direction
longStop = strategy.position_avg_price * (1 - stopPer)
shortStop = strategy.position_avg_price * (1 + stopPer)
shortTake = strategy.position_avg_price * (1 - takePer)
longTake = strategy.position_avg_price * (1 + takePer)

if strategy.position_size > 0 
    strategy.exit("Close Long", "Long", stop=longStop, limit=longTake)
if strategy.position_size < 0 
    strategy.exit("Close Short", "Short", stop=shortStop, limit=shortTake)









더 많은