-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchoppiness_index_php7.php
102 lines (87 loc) · 2.66 KB
/
choppiness_index_php7.php
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
<?php
/**
* The Choppiness Index is designed to measure the market's trendiness
* (values below 20.00) versus the market's choppiness (values above
* 60.00). When the indicator is reading values near 100, the market is
* considered to be in choppy consolidation. The lower the value of the
* Choppiness Index, the more the market is trending. The period supplied
* by the user dictates how many bars are used to compute the index.
*
* Class choppiness_index
*/
final class choppiness_index {
private $period = null;
private $data = null;
private $data_with_extra_period = null;
/**
* @param array $data - Newest data should be at the end of the array
* @param int $period
*
* @return float
*/
public function get(array $data, int $period = 4): float {
$this->setPeriod($period);
$this->setPeriodData($data);
return 100 * log10($this->getAtrSum() / ($this->getMaxHigh() - $this->getMinLow())) / log10($this->period);
}
/**
* @return float
*/
private function getMaxHigh(): float {
$high = null;
foreach ($this->data as $row) {
if ($high === null || $high < $row->high) {
$high = $row->high;
}
}
return $high;
}
/**
* @return float
*/
private function getMinLow(): float {
$low = null;
foreach ($this->data as $row) {
if ($low === null || $low > $row->low) {
$low = $row->low;
}
}
return $low;
}
/**
* @return float
*/
private function getAtrSum(): float {
$highs = [];
$lows = [];
$closes = [];
foreach ($this->data_with_extra_period as $row) {
$highs[] = $row->high;
$lows[] = $row->low;
$closes[] = $row->close;
}
$atrs = trader_atr($highs, $lows, $closes, 1); // ATR (1 period)
$sum = 0;
foreach ($atrs as $atr) {
$sum += $atr;
}
return $sum;
}
/**
* @param int $period
*/
private function setPeriod(int $period) {
if ($this->period === null) {
$this->period = $period;
}
}
/**
* @param array $full_data
*/
private function setPeriodData(array $full_data) {
if ($this->data === null) {
$this->data = array_slice($full_data, (-1 * abs($this->period))); // Get the last X elements only (end element is the most recent)
$this->data_with_extra_period = array_slice($full_data, (-1 * abs($this->period+1))); // Get the last X elements only (end element is the most recent)
}
}
}