@@ -19,6 +19,12 @@ IAtr::IAtr() : IndicatorImp("ATR", 1) {
19
19
setParam<int >(" n" , 14 );
20
20
}
21
21
22
+ IAtr::IAtr (const KData& k, int n) : IndicatorImp(" ATR" , 1 ) {
23
+ setParam<int >(" n" , n);
24
+ setParam<KData>(" kdata" , k);
25
+ IAtr::_calculate (Indicator ());
26
+ }
27
+
22
28
IAtr::~IAtr () {}
23
29
24
30
void IAtr::_checkParam (const string& name) const {
@@ -27,45 +33,54 @@ void IAtr::_checkParam(const string& name) const {
27
33
}
28
34
}
29
35
30
- void IAtr::_calculate (const Indicator& indicator) {
31
- size_t total = indicator.size ();
32
- m_discard = indicator.discard ();
36
+ void IAtr::_calculate (const Indicator& data) {
37
+ HKU_WARN_IF (!isLeaf () && !data.empty (),
38
+ " The input is ignored because {} depends on the context!" , m_name);
39
+
40
+ KData kdata = getContext ();
41
+ size_t total = kdata.size ();
42
+ HKU_IF_RETURN (total == 0 , void ());
43
+
44
+ _readyBuffer (total, 1 );
45
+
46
+ int n = getParam<int >(" n" );
47
+ m_discard = n + 1 ;
33
48
if (m_discard >= total) {
34
49
m_discard = total;
35
50
return ;
36
51
}
37
52
38
- int n = getParam<int >(" n" );
39
- size_t startPos = discard ();
53
+ auto * k = kdata.data ();
54
+ vector<value_t > buf (total);
55
+ for (size_t i = 1 ; i < total; ++i) {
56
+ value_t v1 = k[i].highPrice - k[i].lowPrice ;
57
+ value_t v2 = std::abs (k[i].highPrice - k[i - 1 ].closePrice );
58
+ value_t v3 = std::abs (k[i].lowPrice - k[i - 1 ].closePrice );
59
+ buf[i] = std::max (std::max (v1, v2), v3);
60
+ }
40
61
41
- auto const * src = indicator.data ();
42
- auto * dst = this ->data ();
43
- dst[startPos] = src[startPos];
44
- value_t multiplier = 2.0 / (n + 1 );
45
- for (size_t i = startPos + 1 ; i < total; ++i) {
46
- dst[i] = (src[i] - dst[i - 1 ]) * multiplier + dst[i - 1 ];
62
+ value_t sum = 0.0 ;
63
+ for (size_t i = 1 , end = n + 1 ; i < end; ++i) {
64
+ sum += buf[i];
47
65
}
48
- }
49
66
50
- void IAtr::_dyn_run_one_step ( const Indicator& ind, size_t curPos, size_t step) {
51
- HKU_IF_RETURN (step < 1 , void ()) ;
52
- Indicator slice = SLICE (ind, 0 , curPos + 1 );
53
- Indicator atr = ATR (slice, step);
54
- if (atr. size () > 0 ) {
55
- _set (atr[atr. size () - 1 ], curPos) ;
67
+ auto * dst = this -> data ();
68
+ dst[n] = sum / n ;
69
+
70
+ for ( size_t i = n + 1 ; i < total; ++i) {
71
+ sum = buf[i] + sum - buf[i - n];
72
+ dst[i] = sum / n ;
56
73
}
57
74
}
58
75
59
76
Indicator HKU_API ATR (int n) {
60
- IndicatorImpPtr p = make_shared<IAtr>();
77
+ auto p = make_shared<IAtr>();
61
78
p->setParam <int >(" n" , n);
62
79
return Indicator (p);
63
80
}
64
81
65
- Indicator HKU_API ATR (const IndParam& n) {
66
- IndicatorImpPtr p = make_shared<IAtr>();
67
- p->setIndParam (" n" , n);
68
- return Indicator (p);
82
+ Indicator HKU_API ATR (const KData& kdata, int n) {
83
+ return Indicator (make_shared<IAtr>(kdata, n));
69
84
}
70
85
71
86
} /* namespace hku */
0 commit comments