- // VIA: https://github.com/freqtrade/freqtrade-strategies/issues/30
-
- function SuperTrend(r, period, multiplier) {
- // atr
- var atr = talib.ATR(r, period)
-
- // baseUp , baseDown
- var baseUp = []
- var baseDown = []
- for (var i = 0; i < r.length; i++) {
- if (isNaN(atr[i])) {
- baseUp.push(NaN)
- baseDown.push(NaN)
- continue
- }
- baseUp.push((r[i].High + r[i].Low) / 2 + multiplier * atr[i])
- baseDown.push((r[i].High + r[i].Low) / 2 - multiplier * atr[i])
- }
-
- // fiUp , fiDown
- var fiUp = []
- var fiDown = []
- var prevFiUp = 0
- var prevFiDown = 0
- for (var i = 0; i < r.length; i++) {
- if (isNaN(baseUp[i])) {
- fiUp.push(NaN)
- } else {
- fiUp.push(baseUp[i] < prevFiUp || r[i - 1].Close > prevFiUp ? baseUp[i] : prevFiUp)
- prevFiUp = fiUp[i]
- }
-
- if (isNaN(baseDown[i])) {
- fiDown.push(NaN)
- } else {
- fiDown.push(baseDown[i] > prevFiDown || r[i - 1].Close < prevFiDown ? baseDown[i] : prevFiDown)
- prevFiDown = fiDown[i]
- }
- }
-
- var st = []
- var prevSt = NaN
- for (var i = 0; i < r.length; i++) {
- if (i < period) {
- st.push(NaN)
- continue
- }
-
- var nowSt = 0
- if (((isNaN(prevSt) && isNaN(fiUp[i - 1])) || prevSt == fiUp[i - 1]) && r[i].Close <= fiUp[i]) {
- nowSt = fiUp[i]
- } else if (((isNaN(prevSt) && isNaN(fiUp[i - 1])) || prevSt == fiUp[i - 1]) && r[i].Close > fiUp[i]) {
- nowSt = fiDown[i]
- } else if (((isNaN(prevSt) && isNaN(fiDown[i - 1])) || prevSt == fiDown[i - 1]) && r[i].Close >= fiDown[i]) {
- nowSt = fiDown[i]
- } else if (((isNaN(prevSt) && isNaN(fiDown[i - 1])) || prevSt == fiDown[i - 1]) && r[i].Close < fiDown[i]) {
- nowSt = fiUp[i]
- }
-
- st.push(nowSt)
- prevSt = st[i]
- }
-
- var up = []
- var down = []
- for (var i = 0; i < r.length; i++) {
- if (isNaN(st[i])) {
- up.push(st[i])
- down.push(st[i])
- }
-
- if (r[i].Close < st[i]) {
- down.push(st[i])
- up.push(NaN)
- } else {
- down.push(NaN)
- up.push(st[i])
- }
- }
-
- return [up, down]
- }
-
- // 测试指标用的main函数,并非交易策略
- function main() {
- while (1) {
- var r = _C(exchange.GetRecords)
- var st = SuperTrend(r, 10, 3)
-
- $.PlotRecords(r, "K")
- $.PlotLine("L", st[0][st[0].length - 2], r[r.length - 2].Time)
- $.PlotLine("S", st[1][st[1].length - 2], r[r.length - 2].Time)
-
- Sleep(2000)
- }
- }
复制代码
|