ZigZag
https://gyazo.com/657a9484894398f5d4c84181d3082ac5
参考
code:zigzag.js
//@version=4
study("Zig Zag", overlay=true)
// Deviation = 偏差
dev_threshold = input(title="Deviation (%)", type=input.float, defval=.1, minval=0.01, maxval=100)
// Depth = 深さ
depth = input(title="Depth", type=input.integer, defval=10, minval=1)
//**
//* depth -> length -> zero
//* lengthが最高値・最安値であるかを確認
//* trueならbar_indexと価格を返す
//*
pivots(src, length, isHigh) =>
if length == 0
else
isFound = true
// length -> zeroの最高値・最安値を確認
for i = 0 to length - 1
isFound := false
if not isHigh and srci < p isFound := false
// depth -> lengthの最高値・最安値を確認
for i = length + 1 to 2 * length
isFound := false
if not isHigh and srci <= p isFound := false
// lengthが最高値・最安値だった場合は値を返す
if isFound and length * 2 <= bar_index
// そうでない場合はnaを返す
else
iH, pH = pivots(high, floor(depth / 2), true) iL, pL = pivots(low, floor(depth / 2), false) // データ確認用
// plot( pH )
// plot( pL )
// plot( iH )
// plot( na(iH) ? 1 : 0 )
// plot( iL )
// 変化率を算出する関数
calc_dev(base_price, price) =>
100 * (price - base_price) / base_price
// 直近のpivotの情報を格納
var line lineLast = na // lineのid (実際はidではなく識別している何か)
var int iLast = 0 // bar_index
var float pLast = 0 // price
var bool isHighLast = true // High か Low か
// 描画したラインの数
var int linesCount = 0
// データ確認用
// plot( lineLast )
// plot( iLast )
// plot( pLast )
// plot( linesCount )
//**
//* Lineを描画する関数
//*
pivotFound(dev, isHigh, index, price) =>
// zigzagの頂点を更新する
if isHighLast == isHigh and not na(lineLast)
if isHighLast ? price > pLast : price < pLast
if linesCount <= 1
line.set_xy1(lineLast, index, price)
line.set_xy2(lineLast, index, price)
else
// zigzagの方向を変える(zigzagの頂点)
else
// 一番最初のLine
if na(lineLast)
id = line.new(index, price, index, price, color=color.red, width=2)
else
// 変化率が設定値以上であることを確認
if abs(dev) >= dev_threshold
id = line.new(iLast, pLast, index, price, color=color.red, width=2)
else
//**
//* 描画処理
//*
// iH iL のデータある
// iH と iL の値(bar_index)が同じ
// 高値と安値の描画処理を行う
if not na(iH) and not na(iL) and iH == iL
dev1 = calc_dev(pLast, pH)
if isNew2
linesCount := linesCount + 1
if not na(id2)
lineLast := id2
isHighLast := isHigh2
iLast := iH
pLast := pH
dev2 = calc_dev(pLast, pL)
if isNew1
linesCount := linesCount + 1
if not na(id1)
lineLast := id1
isHighLast := isHigh1
iLast := iL
pLast := pL
else
// iH の値がある
if not na(iH)
dev1 = calc_dev(pLast, pH)
if isNew
linesCount := linesCount + 1
if not na(id)
lineLast := id
isHighLast := isHigh
iLast := iH
pLast := pH
// iL の値がある
else
if not na(iL)
dev2 = calc_dev(pLast, pL)
if isNew
linesCount := linesCount + 1
if not na(id)
lineLast := id
isHighLast := isHigh
iLast := iL
pLast := pL