-
Notifications
You must be signed in to change notification settings - Fork 2
/
supertrend.go
112 lines (101 loc) · 2.49 KB
/
supertrend.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package indicator
import (
"github.com/markcheno/go-talib"
"math"
)
// SuperTrend V1.0 - Buy or Sell Signal
// https://cn.tradingview.com/chart/5wBFaZWw/
// trend true = green, false = red
// red->green = false->true = buy
// green->red = true->false = sell
func SuperTrend(factor float64, period int, inHigh, inLow, inClose []float64) ([]float64, []bool) {
l := len(inHigh)
hl2 := talib.MedPrice(inHigh, inLow)
atr := talib.Atr(inHigh, inLow, inClose, period)
up := make([]float64, l)
down := make([]float64, l)
trendUp := make([]float64, l)
trendDown := make([]float64, l)
trend := make([]bool, l)
tsl := make([]float64, l)
for i := 0; i < l; i++ {
up[i] = hl2[i] - atr[i]*factor
down[i] = hl2[i] + atr[i]*factor
if i == 0 {
trendUp[i] = up[i]
trendDown[i] = down[i]
trend[i] = true
tsl[i] = trendUp[i]
continue
}
if inClose[i-1] > trendUp[i-1] {
trendUp[i] = math.Max(up[i], trendUp[i-1])
} else {
trendUp[i] = up[i]
}
if inClose[i-1] < trendDown[i-1] {
trendDown[i] = math.Min(down[i], trendDown[i-1])
} else {
trendDown[i] = down[i]
}
if inClose[i] > trendDown[i-1] {
trend[i] = true
} else if inClose[i] < trendUp[i-1] {
trend[i] = false
} else {
trend[i] = trend[i-1]
}
if trend[i] {
tsl[i] = trendUp[i]
} else {
tsl[i] = trendDown[i]
}
}
return tsl, trend
}
// SuperTrend with upper/lower bands
func SuperTrendDetail(factor float64, period int, inHigh, inLow, inClose []float64) ([]float64, []float64, []float64, []bool) {
l := len(inHigh)
hl2 := talib.MedPrice(inHigh, inLow)
atr := talib.Atr(inHigh, inLow, inClose, period)
up := make([]float64, l)
down := make([]float64, l)
trendUp := make([]float64, l)
trendDown := make([]float64, l)
trend := make([]bool, l)
tsl := make([]float64, l)
for i := 0; i < l; i++ {
up[i] = hl2[i] - atr[i]*factor
down[i] = hl2[i] + atr[i]*factor
if i == 0 {
trendUp[i] = up[i]
trendDown[i] = down[i]
trend[i] = true
tsl[i] = trendUp[i]
continue
}
if inClose[i-1] > trendUp[i-1] {
trendUp[i] = math.Max(up[i], trendUp[i-1])
} else {
trendUp[i] = up[i]
}
if inClose[i-1] < trendDown[i-1] {
trendDown[i] = math.Min(down[i], trendDown[i-1])
} else {
trendDown[i] = down[i]
}
if inClose[i] > trendDown[i-1] {
trend[i] = true
} else if inClose[i] < trendUp[i-1] {
trend[i] = false
} else {
trend[i] = trend[i-1]
}
if trend[i] {
tsl[i] = trendUp[i]
} else {
tsl[i] = trendDown[i]
}
}
return trendUp, trendDown, tsl, trend
}