Oscillator는 시장의 과매수, 과매도 구간을 확인할 수 있는 보조지표들을 통칭한 표현이다.
Oscillator는 통상적으로 과매수 구간에서는 매도를, 과매도 구간에서는 매수를 하는 전략으로 이용한다.
다만 시장의 추세에 따라 과매수 구간이 계속 이어지며 상승하기도 하고,
과매도 구간이 계속 이어지며 하락하는 경우도 있어 보조지표 해석과 활용에 주의해야 한다.
그러나 Oscilator 보조지표의 활용법은 이것만 있는 것이 아니다.
발생 빈도는 적으나 신뢰도가 높은 다이버전스가 있기 때문이다.
이번 글에서는 대표적인 Oscilator 지표인 RSI의 다이버전스를 자동으로 찾는 코드를 다룰 것이다.
위 코드는 다른 코드를 참고하여 나에게 맞게 변형했다.
출처는 다음과 같다.
https://kr.tradingview.com/script/sxZRzQzQ-Divergence-Indicator-any-oscillator/
Divergence Indicator (any oscillator) by yatrader2
A modification of the TV builtin "Divergence indicator" (Version 10) that can be applied to any indicator, and can be plotted on price as well. Usage: Add your favorite oscillator, RSI, Klinger, TSI, CMF, or anything else to a chart. Click the little ... (
www.tradingview.com
일부 코드를 설명하도록 하겠다.
canR, canL 변수는 저점 또는 고점인 캔들을 찾기 위해 기준 캔들의 좌우 몇 개의 캔들을 확인할지를 결정하는 변수다. canR과 canL이 5라면 기준 캔들의 우측 5개, 좌측 5개 캔들을 확인한다는 뜻이다.
rangeMax와 rangeMin은 _inRange(condition) 함수와 같이 쓰인다. condition이 true일 때 _inRange 함수는 condition이 발생한 지점이 현재 캔들로부터 얼마나 떨어져 있는지 캔들의 개수를 세서 return한다. _inRange 함수는 이후 indicatorHL = indicator[canR] > valuewhen(plFound, indicator[canR], 1) and _inRange(plFound[1])와 같이 indicatorHL 변수에서 쓰이는데 가장 최근에 발생한 저점 또는 고점이 그 직전에 발생한 저점 또는 고점과 멀리 떨어져 있지 않은 경우에만 indicatorHL이 true가 되어야하기 때문이다. 이는 indicatorHL뿐만 아니라 LH, HH, LL 변수도 마찬가지로 적용되어 있다. RSI의 저점과 고점 간의 거리가 멀어지면 신뢰도가 떨어지기 때문에 추가한 조건이다.
plotBull, plotHiddenBull, plotBear, plotHiddenBear는 일반 상승, 히든 상승, 일반 하락, 히든 하락 다이버전스를 RSI 지표에 나타낼지 아닐지를 결정하는 변수다. 설정에서 on/off가 가능하다.
repaint = barstate.ishistory or barstate.isconfirmed , 해당 코드는 캔들의 종가가 정해지지 않았을 때, 즉 캔들이 완성되지 않았을 때 해당 지점에 다이버전스 지지, 저항선을 그리는 걸 막아주는 코드다. barstate.ishistory와 barstate.isconfimed, 즉 캔들의 종가가 정해졌을 때 repaint 변수는 true를 return 받으며 repaint == true일때만 다이버전스 지지, 저항선이 그려지도록 되어 있다.
plFound, phFound는 price_low,와 price_high, 즉 저점과 고점을 찾았는지를 확인하는 boolean 변수다. pivotlow, high 함수를 이용해 저점과 고점을 찾은 경우에 plFound와 phFound 함수는 true를 할당받고, 그렇지 않으면 false를 할당받는다. *_isTrue ? A : B라는 코드는 _isTrue가 참일 때는 A를, 거짓일 때는 B를 출력한다.
bullCond = plotBull and priceLL and indicatorHL and plFound and repaint
plot(
plFound ? indicator[canR] : na,
offset=-canR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor)
) // 저점이 존재하는 경우 indicator[canR], 즉 저점을 plot, 저점이 없으면 na를 plot, 다음 저점이 생기는 경우 이전 저점과 자동으로 선이 이어짐.
이 코드에서 bullCond 변수는 BullCondition을 의미하며 plotBull, priceLL, indicatorHL, plFound, repaint 모두 true일 때 true를 할당 받는 bollean 변수다. 즉 일반 상승 다이버전스를 차트에 나타나게 할 것이며(plotBull), 가격의 저점은 낮아지는 대신(priceLL), rsi의 저점은 높아지고 있으며(indicatorHL), rsi의 저점이 발견됐고(plFound), 캔들의 종가가 정해진 경우(repaint) bullCond = true가 성립한다.
그 경우 plot(C언어의 print와 역할이 유사) 함수로 넘어가게 되는데 plFound = true일 때 indicator[canR] 값을 return하고 그 이외에는 na를 return 한다. 즉, 저점이 발견될 경우 저점의 값을 return하는 것이다. 참고로 pivotlow 함수의 경우 우측에 5개의 캔들이 있을 때만 작동하므로 저점을 발견했다는 것은 저점이 지금으로부터 5개 이전 캔들에 위치했다는 것이다. 고로 indicator가 아닌 indicator[canR]를 return한다.
그리고 color의 경우 bullCond를 만족할 때만 bullColor를, 이외에는 noneColor를 return 받는다. 즉 rsi의 저점을 잇는 지지선을 계속 그리되, 그 중에서 다이버전스가 발생한 위치의 지지선만 색깔을 입혀 보이게 하는 것이다.
위 코드는 일반 상승 다이버전스를 출력하는 코드지만 히든 상승, 일반 하락, 히든 하락 모두 비슷한 코드를 갖고 있다. 원리는 동일하기 때문이다.
참고로 RSI 이외에 다른 Oscillator 지표를 이용하고 싶다면 indicator = rsi(close,RSI_length)에서 rsi 대신 다른 지표의 빌트인 함수를 넣으면 된다.
[Copy and Paste용 코드]
//@version=4
study(title="RSI Divergence Finder", format=format.price, overlay=true)
//------------------------------------------------------------------------------
// RSI 지표 출력
RSI_length = input(title = "RSI length", type = input.integer, defval = 14, minval = 1) // RSI Length를 입력 받는 변수
indicator = rsi(close, RSI_length) // RSI 지표를 indicator 변수에 할당
plot(indicator, color = color.black) // RSI 지표 출력
plot(70, color = color.black)
plot(50, color = color.black)
plot(30, color = color.black) // 30, 50, 70 기준선 출력
//------------------------------------------------------------------------------
// 변수 선언
canR = input(title="Candles on Right of Pivot Point", defval=5) // 기준 캔들에서 우측에 있는 캔들을 몇개까지 검사할 것인지
canL = input(title="Candles on Left of Pivot Point", defval=5) // 기준 캔들 좌측에 있는 캔들을 몇개까지 검사할 것인지
rangeMax = input(title="Max of Candles Range", defval=60) // 검사 대상인 좌우 캔들의 최대 범위, 과도하게 멀리 떨어진 저점, 고점을 잇는 경우를 방지하기 위함
rangeMin = input(title="Min of Candles Range", defval=5) // 검사 대상인 좌우 캔들의 최소 범위
plotBull = input(title="Regular Bullish", defval=true) // 일반 상승 다이버전스를 차트에 나오게 할 것인지 아닌지
plotHiddenBull = input(title="Hidden Bullish", defval=true) // 히든 상승 다이버전스를 차트에 나오게 할 것인지 아닌지
plotBear = input(title="Regular Bearish", defval=true) // 일반 하락 다이버전스를 차트에 나오게 할 것인지 아닌지
plotHiddenBear = input(title="Hidden Bearish", defval=true) // 히든 하락 다이버전스를 차트에 나오게 할 것인지 아닌지
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 0)
hiddenBearColor = color.new(color.red, 0)
textColor = color.white
noneColor = color.new(color.white, 100) // 다이버전스 지지 저항선 및 라벨, 라벨에 들어가는 문구의 색깔을 할당한 변수
repaint = barstate.ishistory or barstate.isconfirmed // 캔들의 저점, 고점, 시가, 종가가 완성됐는지 확인하는 boolean 변수
plFound = na(pivotlow(indicator, canL, canR)) ? false : true // pivotlow가 없으면 na는 true를 리턴해 plFound는 false, pivotlow 존재시 na는 false를 리턴해 plFound는 true
phFound = na(pivothigh(indicator, canL, canR)) ? false : true // pivothigh가 없으면 na는 true를 리턴해 phFound는 false, pivothigh 존재시 na는 false를 리턴해 phFound는 true
_inRange(condition) =>
bars = barssince(condition == true) // 조건 만족시 그 캔들이 현재 캔들로부터 몇개의 캔들만큼 떨어져 있는지를 확인, 저점 또는 고점 간 거리가 지나치게 멀어지는 걸 방지
rangeMin <= bars and bars <= rangeMax // 조건 만족시 좌우캔들이 최대 범위 안에 속해 있는지 아닌지 그 여부를 true/false로 확인할 수 있게하는 _inRange 함수
//------------------------------------------------------------------------------
// 일반 상승 다이버전스
// RSI 저점 상승, 가격차트 저점 하락
indicatorHL = indicator[canR] > valuewhen(plFound, indicator[canR], 1) and _inRange(plFound[1]) // valuewhen 함수는 n번째 이전에 발생한 경우 특정 값을 return, 최근에서 두번째로 plFound가 발생한 지점의 rsi 값을 return
priceLL = low[canR] < valuewhen(plFound, low[canR], 1)
bullCond = plotBull and priceLL and indicatorHL and plFound and repaint
plot(
plFound ? indicator[canR] : na,
offset=-canR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor)
) // 저점이 존재하는 경우 indicator[canR], 즉 저점을 plot, 저점이 없으면 na를 plot, 다음 저점이 생기는 경우 이전 저점과 자동으로 선이 이어짐.
plotshape(
bullCond ? indicator[canR] : na,
offset=-canR,
title="Regular Bullish Label",
text=" Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// 히든 상승 다이버전스
// RSI 저점 하락, 가격차트 저점 상승
indicatorLL = indicator[canR] < valuewhen(plFound, indicator[canR], 1) and _inRange(plFound[1])
priceHL = low[canR] > valuewhen(plFound, low[canR], 1)
hiddenBullCond = plotHiddenBull and priceHL and indicatorLL and plFound and repaint
plot(
plFound ? indicator[canR] : na,
offset=-canR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor)
)
plotshape(
hiddenBullCond ? indicator[canR] : na,
offset=-canR,
title="Hidden Bullish Label",
text=" H Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// 일반 하락 다이버전스
// RSI 고점 하락, 가격차트 고점 상승
indicatorLH = indicator[canR] < valuewhen(phFound, indicator[canR], 1) and _inRange(phFound[1])
priceHH = high[canR] > valuewhen(phFound, high[canR], 1)
bearCond = plotBear and priceHH and indicatorLH and phFound and repaint
plot(
phFound ? indicator[canR] : na,
offset=-canR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor)
)
plotshape(
bearCond ? indicator[canR] : na,
offset=-canR,
title="Regular Bearish Label",
text=" Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// 히든 하락 다이버전스
// RSI 고점 상승, 가격차트 고점 하락
indicatorHH = indicator[canR] > valuewhen(phFound, indicator[canR], 1) and _inRange(phFound[1])
priceLH = high[canR] < valuewhen(phFound, high[canR], 1)
hiddenBearCond = plotHiddenBear and priceLH and indicatorHH and phFound and repaint
plot(
phFound ? indicator[canR] : na,
offset=-canR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor)
)
plotshape(
hiddenBearCond ? indicator[canR] : na,
offset=-canR,
title="Hidden Bearish Label",
text=" H Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
'Pine Script > Indicator' 카테고리의 다른 글
[Indicator] Pivots High and Low, 파인 스크립트로 지지/저항 포인트 찾기 (0) | 2022.09.01 |
---|
댓글